Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73d4255fd7 | ||
|
|
7ad36d8ccb | ||
|
|
f4c82df968 | ||
|
|
219f75c0e4 | ||
|
|
7ed846d0fc | ||
|
|
53c36a81de | ||
|
|
1bf2258167 | ||
|
|
4d8cb8dc36 | ||
|
|
1697d55ad5 | ||
|
|
bd1402ab3a | ||
|
|
c412435172 | ||
|
|
3b08988e30 | ||
|
|
44497173de | ||
|
|
894d8f8436 | ||
|
|
bd5f97f96e | ||
|
|
d6f785662b | ||
|
|
5d16bf4ade | ||
|
|
05bd609c7e | ||
|
|
4ea75beb7b | ||
|
|
96d3482af8 | ||
|
|
7fc07c1883 |
No files matched your search
@@ -10,3 +10,4 @@ docs/superpowers
|
|||||||
*.eventlog
|
*.eventlog
|
||||||
*.eventlog.html
|
*.eventlog.html
|
||||||
*.rrd
|
*.rrd
|
||||||
|
*.rrd.*bak*
|
||||||
+5
-1
@@ -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"
|
||||||
+10
-8
@@ -1,8 +1,9 @@
|
|||||||
{ 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
|
||||||
, filepath, hedgehog, hspec, hspec-hedgehog, http-types, katip
|
, exceptions, filepath, hedgehog, hspec, hspec-hedgehog, http-media
|
||||||
, lens, lens-aeson, lib, network, process, retry, scotty, stm, text
|
, http-types, katip, lens, lens-aeson, lib, network, process, retry
|
||||||
, time, unordered-containers, uuid, wai, warp, websockets
|
, servant, servant-server, stm, temporary, text, time, unliftio
|
||||||
|
, unordered-containers, uuid, wai, warp, websockets
|
||||||
}:
|
}:
|
||||||
mkDerivation {
|
mkDerivation {
|
||||||
pname = "home-assistant-controller";
|
pname = "home-assistant-controller";
|
||||||
@@ -12,15 +13,16 @@ mkDerivation {
|
|||||||
isExecutable = true;
|
isExecutable = true;
|
||||||
libraryHaskellDepends = [
|
libraryHaskellDepends = [
|
||||||
aeson annotated-exception async base bytestring cereal
|
aeson annotated-exception async base bytestring cereal
|
||||||
cereal-conduit conduit containers directory ekg-core filepath
|
cereal-conduit conduit containers directory ekg-core exceptions
|
||||||
http-types katip lens lens-aeson network process retry scotty stm
|
filepath http-media http-types katip lens lens-aeson network
|
||||||
text time unordered-containers uuid wai warp websockets
|
process retry servant servant-server stm text time unliftio
|
||||||
|
unordered-containers uuid wai warp websockets
|
||||||
];
|
];
|
||||||
executableHaskellDepends = [ base ];
|
executableHaskellDepends = [ base ];
|
||||||
testHaskellDepends = [
|
testHaskellDepends = [
|
||||||
aeson annotated-exception async base bytestring cereal containers
|
aeson annotated-exception async base bytestring cereal containers
|
||||||
directory ekg-core hedgehog hspec hspec-hedgehog katip process 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";
|
||||||
|
|||||||
@@ -70,10 +70,12 @@ 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
|
||||||
, HomeAssistant.Runtime.RateLimit
|
, HomeAssistant.Runtime.RateLimit
|
||||||
|
, HttpServer
|
||||||
|
|
||||||
-- Modules included in this library but not exported.
|
-- Modules included in this library but not exported.
|
||||||
-- other-modules:
|
-- other-modules:
|
||||||
@@ -84,6 +86,7 @@ library
|
|||||||
-- Other library packages from which modules are imported.
|
-- Other library packages from which modules are imported.
|
||||||
build-depends: base ^>=4.20.2.0
|
build-depends: base ^>=4.20.2.0
|
||||||
, websockets
|
, websockets
|
||||||
|
, http-media
|
||||||
, aeson
|
, aeson
|
||||||
, lens-aeson
|
, lens-aeson
|
||||||
, lens
|
, lens
|
||||||
@@ -108,7 +111,8 @@ library
|
|||||||
, filepath
|
, filepath
|
||||||
, conduit
|
, conduit
|
||||||
, cereal-conduit
|
, cereal-conduit
|
||||||
, scotty
|
, servant
|
||||||
|
, servant-server
|
||||||
, http-types
|
, http-types
|
||||||
, warp
|
, warp
|
||||||
, wai
|
, wai
|
||||||
@@ -158,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
|
||||||
@@ -182,6 +189,7 @@ test-suite home-assistant-controller-test
|
|||||||
bytestring,
|
bytestring,
|
||||||
hspec,
|
hspec,
|
||||||
stm,
|
stm,
|
||||||
|
servant,
|
||||||
aeson,
|
aeson,
|
||||||
cereal,
|
cereal,
|
||||||
text,
|
text,
|
||||||
@@ -196,4 +204,5 @@ test-suite home-assistant-controller-test
|
|||||||
ekg-core,
|
ekg-core,
|
||||||
unordered-containers,
|
unordered-containers,
|
||||||
process,
|
process,
|
||||||
directory
|
directory,
|
||||||
|
temporary
|
||||||
+21
-21
@@ -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
|
||||||
@@ -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)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ module HomeAssistant.Controller
|
|||||||
, IkeaButton(..)
|
, IkeaButton(..)
|
||||||
, IkeaGesture(..)
|
, IkeaGesture(..)
|
||||||
, activateScene
|
, activateScene
|
||||||
|
, activateSceneWith
|
||||||
, ikeaBoxRemote
|
, ikeaBoxRemote
|
||||||
, IkeaController(..)
|
, IkeaController(..)
|
||||||
) where
|
) where
|
||||||
@@ -259,9 +260,12 @@ ikeaBoxRemote entityId = entityChangeEvent' entityId
|
|||||||
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaController . traversed
|
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 :: T.Text -> Service
|
||||||
activateScene sceneId = Service
|
activateScene sceneId = activateSceneWith sceneId Nothing
|
||||||
|
|
||||||
|
activateSceneWith :: T.Text -> Maybe Value -> Service
|
||||||
|
activateSceneWith sceneId d = Service
|
||||||
{ serviceDomain="scene"
|
{ serviceDomain="scene"
|
||||||
, serviceName= "turn_on"
|
, serviceName= "turn_on"
|
||||||
, serviceTarget= [EntityId sceneId]
|
, serviceTarget= [EntityId sceneId]
|
||||||
, serviceData = Nothing
|
, serviceData = d
|
||||||
}
|
}
|
||||||
@@ -56,11 +56,13 @@ bedroomPresenceController = proc x -> do
|
|||||||
Event LightsOff -> do
|
Event LightsOff -> do
|
||||||
callService (light bedroomLights Off) -< ()
|
callService (light bedroomLights Off) -< ()
|
||||||
Event LightsOn -> do
|
Event LightsOn -> do
|
||||||
callService (activateScene "scene.makuuhuone_lights_snapshot") -< ()
|
callService (activateSceneWith "scene.makuuhuone_lights_snapshot" transition) -< ()
|
||||||
Event LightsSleep -> do
|
Event LightsSleep -> do
|
||||||
callService createBedroomScene -< ()
|
callService createBedroomScene -< ()
|
||||||
callService (activateScene "scene.makuuhuone_lepotila") -< ()
|
callService (activateSceneWith "scene.makuuhuone_lepotila" transition) -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
|
where
|
||||||
|
transition = Just $ object ["transition" .= (10 :: Int)]
|
||||||
|
|
||||||
|
|
||||||
data BedroomControls
|
data BedroomControls
|
||||||
@@ -84,22 +86,24 @@ bedroomButtonController = proc x -> do
|
|||||||
-- Any event will cause the sleep mode to be turned off
|
-- Any event will cause the sleep mode to be turned off
|
||||||
case ev of
|
case ev of
|
||||||
Event (Masse (OnButton ShortRelease)) -> do
|
Event (Masse (OnButton ShortRelease)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_masse") -< ()
|
callService (activateSceneWith "scene.makuuhuone_masse" transition) -< ()
|
||||||
Event (Masse (OnButton DoubleClick)) -> do
|
Event (Masse (OnButton DoubleClick)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_keski") -< ()
|
callService (activateSceneWith "scene.makuuhuone_keski" transition) -< ()
|
||||||
Event (Masse (OnButton LongClick)) -> do
|
Event (Masse (OnButton LongClick)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
callService (activateSceneWith "scene.makuuhuone_kirkas" transition) -< ()
|
||||||
Event (Masse (OffButton _)) -> do
|
Event (Masse (OffButton _)) -> do
|
||||||
callService (light [AreaId "makuuhuone"] Off) -< ()
|
callService (light [AreaId "makuuhuone"] Off) -< ()
|
||||||
Event (Enishen (OnButton ShortRelease)) -> do
|
Event (Enishen (OnButton ShortRelease)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_jemina") -< ()
|
callService (activateSceneWith "scene.makuuhuone_jemina" transition) -< ()
|
||||||
Event (Enishen (OnButton DoubleClick)) -> do
|
Event (Enishen (OnButton DoubleClick)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_keski") -< ()
|
callService (activateSceneWith "scene.makuuhuone_keski" transition) -< ()
|
||||||
Event (Enishen (OnButton LongClick)) -> do
|
Event (Enishen (OnButton LongClick)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
callService (activateSceneWith "scene.makuuhuone_kirkas" transition) -< ()
|
||||||
Event (Enishen (OffButton _)) -> do
|
Event (Enishen (OffButton _)) -> do
|
||||||
callService (light [AreaId "makuuhuone"] Off) -< ()
|
callService (light [AreaId "makuuhuone"] Off) -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
|
where
|
||||||
|
transition = Just $ object ["transition" .= (5 :: Int)]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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 -< ()
|
||||||
@@ -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 qualified HomeAssistant.Runtime.Graphing
|
|
||||||
import HomeAssistant.Controller.Hallway (hallwayLightsController)
|
import HomeAssistant.Controller.Hallway (hallwayLightsController)
|
||||||
|
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", HomeAssistant.Runtime.Graphing.graphAction 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
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -11,37 +11,19 @@ module HomeAssistant.Runtime.Graphing
|
|||||||
, parseNameParam
|
, parseNameParam
|
||||||
, buildGraphArgs
|
, buildGraphArgs
|
||||||
, readProcessBytes
|
, readProcessBytes
|
||||||
, graphAction
|
, Graph(..)
|
||||||
|
, renderGraph
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Control.Exception (evaluate)
|
import Control.Exception (evaluate)
|
||||||
import Control.Monad (forever)
|
|
||||||
import Control.Monad.IO.Class (liftIO, MonadIO)
|
import Control.Monad.IO.Class (liftIO, MonadIO)
|
||||||
import qualified Data.ByteString as BS
|
import qualified Data.ByteString as BS
|
||||||
import qualified Data.ByteString.Lazy as BL
|
|
||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
import qualified Data.Text as T
|
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.Exit (ExitCode (..))
|
||||||
import System.IO (hGetContents)
|
import System.IO (hGetContents)
|
||||||
import System.Process (CreateProcess (..), StdStream (..), proc, waitForProcess, withCreateProcess)
|
import System.Process (CreateProcess (..), StdStream (..), proc, waitForProcess, withCreateProcess)
|
||||||
import Web.Scotty
|
import Servant.API (FromHttpApiData (..), ToHttpApiData (..))
|
||||||
( ActionM
|
|
||||||
, ScottyM
|
|
||||||
, defaultOptions
|
|
||||||
, get
|
|
||||||
, pathParam
|
|
||||||
, queryParamMaybe
|
|
||||||
, raw
|
|
||||||
, scottyOpts
|
|
||||||
, setHeader
|
|
||||||
, settings
|
|
||||||
, status
|
|
||||||
, text
|
|
||||||
)
|
|
||||||
|
|
||||||
data Range = TenMinutes | OneHour | OneDay | OneWeek | OneMonth
|
data Range = TenMinutes | OneHour | OneDay | OneWeek | OneMonth
|
||||||
deriving (Eq, Show, Bounded, Enum)
|
deriving (Eq, Show, Bounded, Enum)
|
||||||
@@ -56,6 +38,12 @@ rangeSuffix OneMonth = "30d"
|
|||||||
parseRange :: Text -> Maybe Range
|
parseRange :: Text -> Maybe Range
|
||||||
parseRange t = lookup t [(T.pack (rangeSuffix r), r) | r <- [minBound .. maxBound]]
|
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 :: Range -> String
|
||||||
rangeStart r = "end-" ++ rangeSuffix r
|
rangeStart r = "end-" ++ rangeSuffix r
|
||||||
|
|
||||||
@@ -91,6 +79,7 @@ data GraphSpec = GraphSpec
|
|||||||
{ gsName :: Text
|
{ gsName :: Text
|
||||||
, gsTitle :: String
|
, gsTitle :: String
|
||||||
, gsPlots :: [Plot]
|
, gsPlots :: [Plot]
|
||||||
|
, gsIdentifier :: Graph
|
||||||
}
|
}
|
||||||
deriving (Eq, Show)
|
deriving (Eq, Show)
|
||||||
|
|
||||||
@@ -141,6 +130,7 @@ ratelimitGraph =
|
|||||||
, serLabel = "Requests exhausted/min"
|
, serLabel = "Requests exhausted/min"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
, gsIdentifier = RateLimit
|
||||||
}
|
}
|
||||||
|
|
||||||
trafficGraph :: GraphSpec
|
trafficGraph :: GraphSpec
|
||||||
@@ -164,6 +154,7 @@ trafficGraph =
|
|||||||
, serLabel = "Service calls out/min"
|
, serLabel = "Service calls out/min"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
, gsIdentifier = Traffic
|
||||||
}
|
}
|
||||||
|
|
||||||
memoryGraph :: GraphSpec
|
memoryGraph :: GraphSpec
|
||||||
@@ -174,17 +165,21 @@ memoryGraph =
|
|||||||
[ area "live" "#99ccff" (average "rts_gc_current__a7a")
|
[ area "live" "#99ccff" (average "rts_gc_current__a7a")
|
||||||
, line "peak" "#cc0000" (maximumCF "rts_gc_current__a7a")
|
, line "peak" "#cc0000" (maximumCF "rts_gc_current__a7a")
|
||||||
]
|
]
|
||||||
|
Memory
|
||||||
|
|
||||||
graphs :: [GraphSpec]
|
graphs :: [GraphSpec]
|
||||||
graphs = [memoryGraph, ratelimitGraph, trafficGraph]
|
graphs = [memoryGraph, ratelimitGraph, trafficGraph]
|
||||||
|
|
||||||
lookupGraph :: [GraphSpec] -> Text -> Maybe GraphSpec
|
-- XXX: Proper lookup..?
|
||||||
lookupGraph specs name = case [g | g <- specs, gsName g == name] of
|
lookupGraph :: [GraphSpec] -> Graph -> Maybe GraphSpec
|
||||||
|
lookupGraph specs graphMode = case [g | g <- specs, gsIdentifier g == graphMode] of
|
||||||
(g : _) -> Just g
|
(g : _) -> Just g
|
||||||
[] -> Nothing
|
[] -> Nothing
|
||||||
|
|
||||||
parseNameParam :: [GraphSpec] -> Text -> Maybe GraphSpec
|
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 :: CF -> String
|
||||||
cfName = \case
|
cfName = \case
|
||||||
@@ -255,39 +250,32 @@ readProcessBytes cmd args =
|
|||||||
pure (code, out, err)
|
pure (code, out, err)
|
||||||
_ -> pure (ExitFailure 1, BS.empty, "failed to create pipes")
|
_ -> pure (ExitFailure 1, BS.empty, "failed to create pipes")
|
||||||
|
|
||||||
respond :: Status -> TL.Text -> ActionM ()
|
renderGraph :: MonadIO m => FilePath -> FilePath -> GraphSpec -> Range -> m (Either Text BS.ByteString)
|
||||||
respond st body = status st >> text body
|
renderGraph rrdPath rrdtool spec range = do
|
||||||
|
|
||||||
serve :: FilePath -> FilePath -> GraphSpec -> Range -> ActionM ()
|
|
||||||
serve rrdPath rrdtool spec range = do
|
|
||||||
(code, out, err) <- liftIO (readProcessBytes rrdtool (buildGraphArgs rrdPath spec range))
|
(code, out, err) <- liftIO (readProcessBytes rrdtool (buildGraphArgs rrdPath spec range))
|
||||||
case code of
|
case code of
|
||||||
ExitSuccess
|
ExitSuccess
|
||||||
| not (BS.null out) -> do
|
| not (BS.null out) -> pure $ Right out
|
||||||
setHeader "Content-Type" "image/png"
|
| otherwise -> pure $ Left "empty graph"
|
||||||
raw (BL.fromStrict out)
|
_ -> pure $ Left (T.pack $ take 200 err)
|
||||||
| otherwise -> respond status500 "empty graph"
|
|
||||||
_ -> respond status500 (TL.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)
|
data Graph
|
||||||
where
|
= Memory
|
||||||
opts = defaultOptions
|
| Traffic
|
||||||
{ settings = setHost "0.0.0.0" (setPort port defaultSettings)
|
| RateLimit
|
||||||
}
|
deriving (Show, Eq, Enum, Bounded)
|
||||||
|
|
||||||
|
instance ToHttpApiData Graph where
|
||||||
|
toQueryParam Memory = "memory.png"
|
||||||
|
toQueryParam Traffic = "traffic.png"
|
||||||
|
toQueryParam RateLimit = "ratelimit.png"
|
||||||
|
|
||||||
|
instance FromHttpApiData Graph where
|
||||||
|
parseQueryParam "memory.png" = Right Memory
|
||||||
|
parseQueryParam "traffic.png" = Right Traffic
|
||||||
|
parseQueryParam "ratelimit.png" = Right RateLimit
|
||||||
|
parseQueryParam x = Left ("Can't parse '" <> x <> "' as Graph")
|
||||||
|
|
||||||
@@ -0,0 +1,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
|
||||||
|
|
||||||
|
|
||||||
+2
-2
@@ -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).
|
||||||
|
|||||||
+7
-7
@@ -5,7 +5,7 @@ module BedroomSpec (spec) where
|
|||||||
import AFRP (Event (..), entities)
|
import AFRP (Event (..), entities)
|
||||||
import qualified Data.Set as S
|
import qualified Data.Set as S
|
||||||
import qualified Data.Text as T
|
import qualified Data.Text as T
|
||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value, object, (.=))
|
||||||
import HomeAssistant.Controller
|
import HomeAssistant.Controller
|
||||||
import HomeAssistant.Controller.Bedroom
|
import HomeAssistant.Controller.Bedroom
|
||||||
import Support
|
import Support
|
||||||
@@ -91,15 +91,15 @@ buttonSpec = describe "bedroomButtonController" $ do
|
|||||||
|
|
||||||
it "Masse single click turns on his nightstand scene (lowest)" $
|
it "Masse single click turns on his nightstand scene (lowest)" $
|
||||||
concat (services (runHASS bedroomButtonController [masseButton "1_short_release"]))
|
concat (services (runHASS bedroomButtonController [masseButton "1_short_release"]))
|
||||||
`shouldContain` [activateScene "scene.makuuhuone_masse"]
|
`shouldContain` [activateSceneWith "scene.makuuhuone_masse" (Just $ object ["transition" .= (5 :: Int)])]
|
||||||
|
|
||||||
it "Masse double click turns on the middle scene" $
|
it "Masse double click turns on the middle scene" $
|
||||||
concat (services (runHASS bedroomButtonController [masseButton "1_double_press"]))
|
concat (services (runHASS bedroomButtonController [masseButton "1_double_press"]))
|
||||||
`shouldContain` [activateScene "scene.makuuhuone_keski"]
|
`shouldContain` [activateSceneWith "scene.makuuhuone_keski" (Just $ object ["transition" .= (5 :: Int)])]
|
||||||
|
|
||||||
it "Masse long click turns on the bright scene" $
|
it "Masse long click turns on the bright scene" $
|
||||||
concat (services (runHASS bedroomButtonController [masseButton "1_long_press"]))
|
concat (services (runHASS bedroomButtonController [masseButton "1_long_press"]))
|
||||||
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
|
`shouldContain` [activateSceneWith "scene.makuuhuone_kirkas" (Just $ object ["transition" .= (5 :: Int)])]
|
||||||
|
|
||||||
it "Masse off click turns the bedroom lights off" $
|
it "Masse off click turns the bedroom lights off" $
|
||||||
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
|
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
|
||||||
@@ -107,15 +107,15 @@ buttonSpec = describe "bedroomButtonController" $ do
|
|||||||
|
|
||||||
it "Enishen single click turns on her nightstand scene (lowest)" $
|
it "Enishen single click turns on her nightstand scene (lowest)" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
|
||||||
`shouldContain` [activateScene "scene.makuuhuone_jemina"]
|
`shouldContain` [activateSceneWith "scene.makuuhuone_jemina" (Just $ object ["transition" .= (5 :: Int)])]
|
||||||
|
|
||||||
it "Enishen double click turns on the middle scene" $
|
it "Enishen double click turns on the middle scene" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "1_double_press"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "1_double_press"]))
|
||||||
`shouldContain` [activateScene "scene.makuuhuone_keski"]
|
`shouldContain` [activateSceneWith "scene.makuuhuone_keski" (Just $ object ["transition" .= (5 :: Int)])]
|
||||||
|
|
||||||
it "Enishen long click turns on the bright scene" $
|
it "Enishen long click turns on the bright scene" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "1_long_press"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "1_long_press"]))
|
||||||
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
|
`shouldContain` [activateSceneWith "scene.makuuhuone_kirkas" (Just $ object ["transition" .= (5 :: Int)])]
|
||||||
|
|
||||||
it "Enishen off click turns the bedroom lights off" $
|
it "Enishen off click turns the bedroom lights off" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
|
||||||
|
|||||||
+27
-3
@@ -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
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
+19
-1
@@ -20,15 +20,30 @@ import System.Directory (findExecutable, getTemporaryDirectory, removeFile)
|
|||||||
import System.Exit (ExitCode (..))
|
import System.Exit (ExitCode (..))
|
||||||
import System.Process (readProcessWithExitCode)
|
import System.Process (readProcessWithExitCode)
|
||||||
import Test.Hspec
|
import Test.Hspec
|
||||||
|
import Servant.API (FromHttpApiData(..), ToHttpApiData (..))
|
||||||
|
import HomeAssistant.Runtime.Graphing (Graph(..))
|
||||||
|
|
||||||
traffic :: GraphSpec
|
traffic :: GraphSpec
|
||||||
traffic = case lookupGraph graphs "traffic" of
|
traffic = case lookupGraph graphs Traffic of
|
||||||
Just s -> s
|
Just s -> s
|
||||||
Nothing -> error "traffic graph is missing from the table"
|
Nothing -> error "traffic graph is missing from the table"
|
||||||
|
|
||||||
spec :: Spec
|
spec :: Spec
|
||||||
spec = do
|
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
|
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" $
|
it "accepts every suffix in the closed set" $
|
||||||
map parseRange ["10m", "1h", "24h", "7d", "30d"]
|
map parseRange ["10m", "1h", "24h", "7d", "30d"]
|
||||||
`shouldBe` [ Just TenMinutes
|
`shouldBe` [ Just TenMinutes
|
||||||
@@ -124,3 +139,6 @@ spec = do
|
|||||||
out `shouldSatisfy` BS.isPrefixOf pngMagic
|
out `shouldSatisfy` BS.isPrefixOf pngMagic
|
||||||
)
|
)
|
||||||
`finally` cleanup
|
`finally` cleanup
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -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]]
|
||||||
@@ -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,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
@@ -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
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user