Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ea75beb7b | ||
|
|
96d3482af8 | ||
|
|
7fc07c1883 | ||
|
|
a7becaf2d4 |
No files matched your search
+6
-8
@@ -1,9 +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
|
, filepath, hedgehog, hspec, hspec-hedgehog, http-types, katip
|
||||||
, katip, lens, lens-aeson, lib, network, process, retry, scotty
|
, lens, lens-aeson, lib, network, process, retry, scotty, stm, text
|
||||||
, servant, servant-server, stm, text, time, unliftio
|
, time, unordered-containers, uuid, wai, warp, websockets
|
||||||
, unordered-containers, uuid, wai, warp, websockets
|
|
||||||
}:
|
}:
|
||||||
mkDerivation {
|
mkDerivation {
|
||||||
pname = "home-assistant-controller";
|
pname = "home-assistant-controller";
|
||||||
@@ -13,10 +12,9 @@ mkDerivation {
|
|||||||
isExecutable = true;
|
isExecutable = true;
|
||||||
libraryHaskellDepends = [
|
libraryHaskellDepends = [
|
||||||
aeson annotated-exception async base bytestring cereal
|
aeson annotated-exception async base bytestring cereal
|
||||||
cereal-conduit conduit containers directory ekg-core exceptions
|
cereal-conduit conduit containers directory ekg-core filepath
|
||||||
filepath http-types katip lens lens-aeson network process retry
|
http-types katip lens lens-aeson network process retry scotty stm
|
||||||
scotty servant servant-server stm text time unliftio
|
text time unordered-containers uuid wai warp websockets
|
||||||
unordered-containers uuid wai warp websockets
|
|
||||||
];
|
];
|
||||||
executableHaskellDepends = [ base ];
|
executableHaskellDepends = [ base ];
|
||||||
testHaskellDepends = [
|
testHaskellDepends = [
|
||||||
|
|||||||
@@ -74,7 +74,6 @@ library
|
|||||||
, 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:
|
||||||
@@ -85,7 +84,6 @@ 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
|
||||||
@@ -110,8 +108,7 @@ library
|
|||||||
, filepath
|
, filepath
|
||||||
, conduit
|
, conduit
|
||||||
, cereal-conduit
|
, cereal-conduit
|
||||||
, servant
|
, scotty
|
||||||
, servant-server
|
|
||||||
, http-types
|
, http-types
|
||||||
, warp
|
, warp
|
||||||
, wai
|
, wai
|
||||||
@@ -185,7 +182,6 @@ test-suite home-assistant-controller-test
|
|||||||
bytestring,
|
bytestring,
|
||||||
hspec,
|
hspec,
|
||||||
stm,
|
stm,
|
||||||
servant,
|
|
||||||
aeson,
|
aeson,
|
||||||
cereal,
|
cereal,
|
||||||
text,
|
text,
|
||||||
|
|||||||
@@ -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"] )
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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.makuuhuone_lepotila") -< ()
|
||||||
|
_ -> returnA -< ()
|
||||||
@@ -36,12 +36,12 @@ 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 -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
|
||||||
step path trace st a = do
|
step path trace st a = do
|
||||||
@@ -63,6 +63,7 @@ controllers =
|
|||||||
, Controller True "livingroom-presence" livingroomPresenceController
|
, Controller True "livingroom-presence" livingroomPresenceController
|
||||||
, Controller True "hallway-motion-controller" hallwayLightsController
|
, Controller True "hallway-motion-controller" hallwayLightsController
|
||||||
, Controller True "children-button" childrenBedroomButtonController
|
, Controller True "children-button" childrenBedroomButtonController
|
||||||
|
, Controller True "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
|
||||||
@@ -115,7 +116,7 @@ defaultMain = withSocketsDo $ do
|
|||||||
[ ("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", HomeAssistant.Runtime.Graphing.graphAction rrdPath rrdtool metricsPort)
|
||||||
] ++ [ (name, runController rootPath bus c) | c@(Controller True name _) <- active ]
|
] ++ [ (name, runController rootPath bus c) | c@(Controller True name _) <- active ]
|
||||||
runKatipContextT (busLogEnv bus) () mempty $
|
runKatipContextT (busLogEnv bus) () mempty $
|
||||||
mapConcurrently_ (uncurry supervised) workers
|
mapConcurrently_ (uncurry supervised) workers
|
||||||
|
|||||||
@@ -11,19 +11,37 @@ module HomeAssistant.Runtime.Graphing
|
|||||||
, parseNameParam
|
, parseNameParam
|
||||||
, buildGraphArgs
|
, buildGraphArgs
|
||||||
, readProcessBytes
|
, readProcessBytes
|
||||||
, Graph(..)
|
, graphAction
|
||||||
, 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 Servant.API (FromHttpApiData (..), ToHttpApiData (..))
|
import Web.Scotty
|
||||||
|
( 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)
|
||||||
@@ -38,12 +56,6 @@ 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
|
||||||
|
|
||||||
@@ -79,7 +91,6 @@ data GraphSpec = GraphSpec
|
|||||||
{ gsName :: Text
|
{ gsName :: Text
|
||||||
, gsTitle :: String
|
, gsTitle :: String
|
||||||
, gsPlots :: [Plot]
|
, gsPlots :: [Plot]
|
||||||
, gsIdentifier :: Graph
|
|
||||||
}
|
}
|
||||||
deriving (Eq, Show)
|
deriving (Eq, Show)
|
||||||
|
|
||||||
@@ -130,7 +141,6 @@ ratelimitGraph =
|
|||||||
, serLabel = "Requests exhausted/min"
|
, serLabel = "Requests exhausted/min"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
, gsIdentifier = RateLimit
|
|
||||||
}
|
}
|
||||||
|
|
||||||
trafficGraph :: GraphSpec
|
trafficGraph :: GraphSpec
|
||||||
@@ -154,7 +164,6 @@ trafficGraph =
|
|||||||
, serLabel = "Service calls out/min"
|
, serLabel = "Service calls out/min"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
, gsIdentifier = Traffic
|
|
||||||
}
|
}
|
||||||
|
|
||||||
memoryGraph :: GraphSpec
|
memoryGraph :: GraphSpec
|
||||||
@@ -165,21 +174,17 @@ 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]
|
||||||
|
|
||||||
-- XXX: Proper lookup..?
|
lookupGraph :: [GraphSpec] -> Text -> Maybe GraphSpec
|
||||||
lookupGraph :: [GraphSpec] -> Graph -> Maybe GraphSpec
|
lookupGraph specs name = case [g | g <- specs, gsName g == name] of
|
||||||
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 = rightToMaybe (parseQueryParam t) >>= lookupGraph specs
|
parseNameParam specs t = T.stripSuffix ".png" t >>= lookupGraph specs
|
||||||
where
|
|
||||||
rightToMaybe = either (const Nothing) Just
|
|
||||||
|
|
||||||
cfName :: CF -> String
|
cfName :: CF -> String
|
||||||
cfName = \case
|
cfName = \case
|
||||||
@@ -250,32 +255,39 @@ 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")
|
||||||
|
|
||||||
renderGraph :: MonadIO m => FilePath -> FilePath -> GraphSpec -> Range -> m (Either Text BS.ByteString)
|
respond :: Status -> TL.Text -> ActionM ()
|
||||||
renderGraph rrdPath rrdtool spec range = do
|
respond st body = status st >> text body
|
||||||
|
|
||||||
|
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) -> pure $ Right out
|
| not (BS.null out) -> do
|
||||||
| otherwise -> pure $ Left "empty graph"
|
setHeader "Content-Type" "image/png"
|
||||||
_ -> pure $ Left (T.pack $ take 200 err)
|
raw (BL.fromStrict out)
|
||||||
|
| 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
|
||||||
data Graph
|
graphAction rrdPath rrdtool port = liftIO $ forever $ scottyOpts opts (app rrdPath rrdtool)
|
||||||
= Memory
|
where
|
||||||
| Traffic
|
opts = defaultOptions
|
||||||
| RateLimit
|
{ settings = setHost "0.0.0.0" (setPort port defaultSettings)
|
||||||
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")
|
|
||||||
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-}
|
|
||||||
{-# LANGUAGE DerivingVia #-}
|
|
||||||
module HttpServer where
|
|
||||||
|
|
||||||
import Control.Monad (forever)
|
|
||||||
import Control.Monad.IO.Class (liftIO, MonadIO)
|
|
||||||
import qualified Data.ByteString as BS
|
|
||||||
import Data.Void (Void)
|
|
||||||
import Network.Wai.Handler.Warp (run)
|
|
||||||
import Servant.API ((:>), Capture, Get, QueryParam, (:-), MimeRender (..), Accept (..), NamedRoutes)
|
|
||||||
import Data.ByteString (ByteString)
|
|
||||||
import GHC.Generics (Generic)
|
|
||||||
import Servant (Handler, err404)
|
|
||||||
import Control.Monad.Catch (throwM, MonadCatch, MonadThrow)
|
|
||||||
import Servant.Server (err500, ServerT)
|
|
||||||
import Data.Maybe (fromMaybe)
|
|
||||||
import Control.Exception.Annotated (checkpoint, Annotation (Annotation))
|
|
||||||
import Servant.Server.Generic (genericServeT)
|
|
||||||
import Network.Wai (Application)
|
|
||||||
import Network.HTTP.Media ((//))
|
|
||||||
import HomeAssistant.Runtime.Graphing (Graph, Range (..), lookupGraph, graphs, renderGraph)
|
|
||||||
import Katip (KatipContextT, Katip, runKatipContextT, LogEnv, KatipContext, ls, Severity (..), logFM)
|
|
||||||
|
|
||||||
data ImagePng
|
|
||||||
|
|
||||||
instance MimeRender ImagePng ByteString where
|
|
||||||
mimeRender _ = BS.fromStrict
|
|
||||||
|
|
||||||
instance Accept ImagePng where
|
|
||||||
contentType _ = "image" // "png"
|
|
||||||
|
|
||||||
|
|
||||||
newtype API mode = API
|
|
||||||
{ getMetrics :: mode :- "metrics" :> Capture "graph" Graph :> QueryParam "range" Range :> Get '[ImagePng] ByteString
|
|
||||||
}
|
|
||||||
deriving Generic
|
|
||||||
|
|
||||||
|
|
||||||
getMetricsHandler :: FilePath -> FilePath -> Graph -> Maybe Range -> LoggingHandler ByteString
|
|
||||||
getMetricsHandler rrdPath rrdtool graphMode mRange = checkpoint (Annotation (graphMode, mRange)) $ do
|
|
||||||
case lookupGraph graphs graphMode of
|
|
||||||
Nothing -> throwM err404
|
|
||||||
Just spec -> do
|
|
||||||
let range = fromMaybe OneDay mRange
|
|
||||||
g <- renderGraph rrdPath rrdtool spec range
|
|
||||||
either (\e -> logFM ErrorS (ls e) >> throwM err500) pure g
|
|
||||||
|
|
||||||
-- server :: FilePath -> FilePath -> API AsServer
|
|
||||||
server :: FilePath -> FilePath -> ServerT (NamedRoutes API) LoggingHandler
|
|
||||||
server rrdPath rrdtool = API { getMetrics = getMetricsHandler rrdPath rrdtool }
|
|
||||||
|
|
||||||
servantApp :: LogEnv -> FilePath -> FilePath -> Application
|
|
||||||
servantApp le rrdPath rrdtool = genericServeT (toHandler le) (server rrdPath rrdtool)
|
|
||||||
|
|
||||||
runHttpServer :: MonadIO m => LogEnv -> FilePath -> FilePath -> Int -> m Void
|
|
||||||
runHttpServer le rrdPath rrdtool port = liftIO $ forever $ run port (servantApp le rrdPath rrdtool)
|
|
||||||
|
|
||||||
newtype LoggingHandler a = LoggingHandler (KatipContextT Handler a)
|
|
||||||
deriving (Functor, Applicative, Monad, MonadIO, Katip, KatipContext, MonadCatch, MonadThrow) via (KatipContextT Handler)
|
|
||||||
|
|
||||||
toHandler :: LogEnv -> (forall a. LoggingHandler a -> Handler a)
|
|
||||||
toHandler le (LoggingHandler k) = runKatipContextT le () "http" k
|
|
||||||
|
|
||||||
|
|
||||||
+1
-19
@@ -20,30 +20,15 @@ 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
|
||||||
@@ -139,6 +124,3 @@ spec = do
|
|||||||
out `shouldSatisfy` BS.isPrefixOf pngMagic
|
out `shouldSatisfy` BS.isPrefixOf pngMagic
|
||||||
)
|
)
|
||||||
`finally` cleanup
|
`finally` cleanup
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Reference in new issue
Block a user