Author SHA1 Message Date
MasseR a7becaf2d4 Use scenes instead of stateful applications of adaptive sleep mode 2026-09-25 09:55:48 +03:00
MasseR 9c47bbcb42 More 2026-09-24 20:27:11 +03:00
MasseR 6063aafe8b Toggle adaptive mode 2026-09-24 20:21:33 +03:00
MasseR fafc7111bb The center button also disables sleep mode 2026-09-24 10:07:02 +03:00
MasseR 69cac934ec Fix tests 2026-09-24 10:06:20 +03:00
MasseR b2a74cbee4 Sleep mode in the bedroom 2026-09-24 09:48:35 +03:00
MasseR 769ab43fd2 Untested three-state for dinner table 2026-09-24 08:17:22 +03:00
MasseR 15f3fe7c9e Hups 2026-09-21 18:59:32 +03:00
MasseR 416a9484a5 Listen on 0.0.0.0 to be usable by tailscale 2026-09-21 08:11:49 +03:00
MasseR e3bc25ce54 Quick buttons 2026-09-17 11:48:22 +03:00
MasseR 036473ab81 Don't catch async exceptions 2026-09-17 11:05:27 +03:00
MasseR 27f271691c Hallway lights automation 2026-09-17 09:57:12 +03:00
MasseR 73d546395b Fix the bad use of async
Propagate errors with `mapConcurrently_`
2026-09-16 14:54:36 +03:00
MasseR a969730de1 Update tests 2026-09-16 14:52:39 +03:00
MasseR 213f9d5d2a More graphs 2026-09-16 14:42:31 +03:00
MasseR 2cb8035ef4 Increase the backoff 2026-09-16 12:51:58 +03:00
MasseR 1ec8c7211f Render ratelimiter 2026-09-16 12:32:32 +03:00
13 changed files with 428 additions and 134 deletions

No files matched your search

+1
View File
@@ -62,6 +62,7 @@ library
exposed-modules: AFRP
, HomeAssistant.Controller
, HomeAssistant.Controller.Bedroom
, HomeAssistant.Controller.Hallway
, HomeAssistant.Controller.Kitchen
, HomeAssistant.Controller.Children
, HomeAssistant.Controller.Livingroom
+75 -1
View File
@@ -28,6 +28,12 @@ module HomeAssistant.Controller
, Target(..)
, brightness
, Light(..)
, ikeaQuickButton
, IkeaButton(..)
, IkeaGesture(..)
, activateScene
, ikeaBoxRemote
, IkeaController(..)
) where
import AFRP (Mealy (..), eff, Event(..), events, filterA, (>>|), toEvent, Request, hold, lMerge, waitFor, tag, edge)
@@ -36,7 +42,7 @@ import Control.Category ((>>>))
import Data.Aeson (Value, object, (.=))
import qualified Data.Text as T
import qualified Data.Set as S
import Control.Lens (has, only, (^?), to)
import Control.Lens (has, only, (^?), to, traversed)
import Data.Aeson.Lens (key, _String, _Integral)
import qualified Data.Text.Lens as TL
import Data.Bool (bool)
@@ -191,3 +197,71 @@ brightness entityId =
>>> AFRP.toEvent
where
eventBrightness v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "brightness" . _Integral
data IkeaGesture
= ShortClick
| ShortRelease
| DoubleClick
| LongClick
deriving Show
data IkeaButton a = OnButton !a | OffButton !a
deriving Show
toIkeaQuickButton :: T.Text -> Maybe (IkeaButton IkeaGesture)
toIkeaQuickButton = \case
-- 1 is on, 2 is off side of the button
"1_initial_press" -> Just $ OnButton ShortClick
"1_short_release" -> Just $ OnButton ShortRelease
"1_double_press" -> Just $ OnButton DoubleClick
"1_long_press" -> Just $ OnButton LongClick
"2_initial_press" -> Just $ OffButton ShortClick
"2_short_release" -> Just $ OffButton ShortRelease
"2_double_press" -> Just $ OffButton DoubleClick
"2_long_press" -> Just $ OffButton LongClick
_ -> Nothing
ikeaQuickButton :: T.Text -> HASS (Event Value) (Event (IkeaButton IkeaGesture))
ikeaQuickButton entityId =
entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaQuickButton . traversed
data IkeaController
= ControllerOn -- Short press on
| ControllerOff -- Short press off
| ControllerBrighnessUp -- Turn brightness up
| ControllerBrighnessDown -- Turn brighness down
| ControllerArrowRight -- Turn brighness down
| ControllerArrowLeft -- Turn brighness down
| ControllerBrighnessStop
deriving Show
toIkeaController :: T.Text -> Maybe IkeaController
toIkeaController = \case
"on" -> Just ControllerOn
"off" -> Just ControllerOff
"brightness_move_up" -> Just ControllerBrighnessUp
"brightness_move_down" -> Just ControllerBrighnessDown
"brightness_stop" -> Just ControllerBrighnessStop
"arrow_right_click" -> Just ControllerArrowRight
"arrow_left_click" -> Just ControllerArrowLeft
_ -> Nothing
ikeaBoxRemote :: T.Text -> HASS (Event Value) (Event IkeaController)
ikeaBoxRemote entityId = entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaController . traversed
activateScene :: T.Text -> Service
activateScene sceneId = Service
{ serviceDomain="scene"
, serviceName= "turn_on"
, serviceTarget= [EntityId sceneId]
, serviceData = Nothing
}
+47 -54
View File
@@ -4,11 +4,9 @@ module HomeAssistant.Controller.Bedroom where
import HomeAssistant.Controller
import qualified Data.Text as T
import AFRP (Event (..), (>>|), toEvent, lMerge, duration, edge)
import AFRP (Event (..), lMerge, duration, edge)
import Data.Aeson (Value, object, (.=))
import Control.Arrow ((>>>), returnA, arr, Arrow (..))
import Control.Lens ((^?), to, traversed)
import Data.Aeson.Lens (key, _String)
import Data.Bool (bool)
import Data.Time (NominalDiffTime)
import qualified AFRP
@@ -29,83 +27,78 @@ createBedroomScene = Service
, serviceTarget= []
}
activateScene :: T.Text -> Service
activateScene sceneId = Service
{ serviceDomain="scene"
, serviceName= "turn_on"
, serviceTarget= [EntityId sceneId]
, serviceData = Nothing
}
data PresenceLights
= LightsOn -- Restore lights
| LightsOff -- Timer expired, darkness
| LightsSleep -- No presence detected, sleep mode
deriving Show
-- Bedroom presence
bedroomPresence :: HASS (Event Value) (Event Presence)
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
presenceLightEvents :: HASS (Event Value) (Event PresenceLights)
presenceLightEvents =
bedroomPresence >>> AFRP.hold Unoccupied
>>> arr lightWanted
>>> (sleepEvent &&& offEvent &&& onEvent)
>>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
where
lightWanted o = o == Occupied
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightsSleep)
onEvent = AFRP.edge >>> arr (AFRP.tag LightsOn)
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightsOff)
bedroomPresenceController :: HASS (Event Value) ()
bedroomPresenceController = proc x -> do
p <- bedroomPresence >>> traceEvent -< x
p <- presenceLightEvents >>> traceEvent -< x
case p of
Event Unoccupied -> callService createBedroomScene >>> callService (light bedroomLights Off) -< ()
Event Occupied -> callService (activateScene "scene.makuuhuone_lights_snapshot") -< ()
Event LightsOff -> do
callService (light bedroomLights Off) -< ()
Event LightsOn -> do
callService (activateScene "scene.makuuhuone_lights_snapshot") -< ()
Event LightsSleep -> do
callService createBedroomScene -< ()
callService (activateScene "scene.makuuhuone_lepotila") -< ()
_ -> returnA -< ()
data IkeaGesture
= ShortClick
| ShortRelease
| DoubleClick
| LongClick
deriving Show
data IkeaButton a = OnButton !a | OffButton !a
deriving Show
toIkeaQuickButton :: T.Text -> Maybe (IkeaButton IkeaGesture)
toIkeaQuickButton = \case
-- 1 is on, 2 is off side of the button
"1_initial_press" -> Just $ OnButton ShortClick
"1_short_release" -> Just $ OnButton ShortRelease
"1_double_press" -> Just $ OnButton DoubleClick
"1_long_press" -> Just $ OnButton LongClick
"2_initial_press" -> Just $ OffButton ShortClick
"2_short_release" -> Just $ OffButton ShortRelease
"2_double_press" -> Just $ OffButton DoubleClick
"2_long_press" -> Just $ OffButton LongClick
_ -> Nothing
ikeaQuickButton :: T.Text -> HASS (Event Value) (Event (IkeaButton IkeaGesture))
ikeaQuickButton entityId =
entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaQuickButton . traversed
data BedroomControls
= Masse (IkeaButton IkeaGesture)
| Enishen (IkeaButton IkeaGesture)
| Central IkeaController
deriving Show
bedroomButton :: HASS (Event Value) (Event BedroomControls)
bedroomButton = (masseButton &&& enishenButton) >>> arr (uncurry lMerge)
bedroomButton = (masseButton &&& enishenButton &&& centralButton)
>>> arr (\(a,(b,c)) -> a `lMerge` b `lMerge` c)
where
masseButton = fmap Masse <$> ikeaQuickButton "event.bedroom_quick_remote_masse_action"
enishenButton = fmap Enishen <$> ikeaQuickButton "event.bedroom_quick_jemina_action"
centralButton = fmap Central <$> ikeaBoxRemote "event.bedroom_remote_action"
bedroomButtonController :: HASS (Event Value) ()
bedroomButtonController = proc x -> do
ev <- bedroomButton >>> traceEvent -< x
-- Any event will cause the sleep mode to be turned off
case ev of
Event (Masse (OnButton ShortRelease)) -> callService (activateScene "scene.makuuhuone_masse") -< ()
Event (Masse (OnButton DoubleClick)) -> callService (activateScene "scene.makuuhuone_keski") -< ()
Event (Masse (OnButton LongClick)) -> callService (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Masse (OffButton _)) -> callService (light [AreaId "makuuhuone"] Off) -< ()
Event (Enishen (OnButton ShortRelease)) -> callService (activateScene "scene.makuuhuone_jemina") -< ()
Event (Enishen (OnButton DoubleClick)) -> callService (activateScene "scene.makuuhuone_keski") -< ()
Event (Enishen (OnButton LongClick)) -> callService (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Enishen (OffButton _)) -> callService (light [AreaId "makuuhuone"] Off) -< ()
Event (Masse (OnButton ShortRelease)) -> do
callService (activateScene "scene.makuuhuone_masse") -< ()
Event (Masse (OnButton DoubleClick)) -> do
callService (activateScene "scene.makuuhuone_keski") -< ()
Event (Masse (OnButton LongClick)) -> do
callService (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Masse (OffButton _)) -> do
callService (light [AreaId "makuuhuone"] Off) -< ()
Event (Enishen (OnButton ShortRelease)) -> do
callService (activateScene "scene.makuuhuone_jemina") -< ()
Event (Enishen (OnButton DoubleClick)) -> do
callService (activateScene "scene.makuuhuone_keski") -< ()
Event (Enishen (OnButton LongClick)) -> do
callService (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Enishen (OffButton _)) -> do
callService (light [AreaId "makuuhuone"] Off) -< ()
_ -> returnA -< ()
+18 -4
View File
@@ -1,13 +1,14 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Children where
import HomeAssistant.Controller (HASS, callService, Target (AreaId), light, Light(..))
import AFRP (Event)
import HomeAssistant.Controller (HASS, callService, Target (AreaId), light, Light(..), ikeaQuickButton, IkeaGesture (..), IkeaButton (..), traceEvent, activateScene)
import AFRP (Event (..))
import qualified AFRP
import Control.Arrow (Arrow(..), (>>>))
import Control.Arrow (Arrow(..), (>>>), returnA)
import Data.Time (Day, TimeOfDay (..), localDay, LocalTime (..))
import Data.Time.Calendar.OrdinalDate (WeekOfYear, mondayStartWeek)
import Data.Functor.Contravariant (Predicate (..), (>$<))
import Data.Aeson (Value)
-- Let's see building some reasonable interface for utctime
dow :: Day -> (WeekOfYear, Int)
@@ -62,7 +63,6 @@ timersOn =
, day 3 <> at (07,30)
, day 4 <> at (07,30)
, day 5 <> at (07,30)
, at (18,55) -- debug
]
where
dayOfWeek = snd . mondayStartWeek . localDay
@@ -80,3 +80,17 @@ lightsOn = foldMap atTime timersOn
lightsOff :: HASS a ()
lightsOff = foldMap atTime timersOff
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] Off))
bedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
bedroomButton = ikeaQuickButton "event.children_quick_remote_action"
childrenBedroomButtonController :: HASS (Event Value) ()
childrenBedroomButtonController = proc x -> do
ev <- bedroomButton >>> traceEvent -< x
case ev of
Event (OnButton ShortRelease) -> callService (activateScene "scene.lasten_nukkuvalmistelu") -< ()
Event (OnButton DoubleClick) -> callService (activateScene "scene.lasten_luku") -< ()
Event (OnButton LongClick) -> callService (activateScene "scene.lasten_kirkas") -< ()
Event (OffButton _) -> callService (light [AreaId "lasten_makuuhuone"] Off) -< ()
_ -> returnA -< ()
+38
View File
@@ -0,0 +1,38 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Arrows #-}
module HomeAssistant.Controller.Hallway where
import HomeAssistant.Controller (Presence (..), HASS, motion, motionToPresence, traceEvent, callServiceDyn, light, Target (..), Light (..))
import AFRP (Event (..))
import qualified AFRP
import Data.Aeson (Value)
import Control.Arrow ((>>>), Arrow (..), returnA)
import Data.Time (LocalTime(..), TimeOfDay (..))
hallwayPresence :: HASS (Event Value) Presence
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
data Lights = LightsOn | LightsOff
deriving (Show)
eventLights :: HASS Presence (Event Lights)
eventLights = AFRP.changes >>> arr (fmap presenceLights)
where
presenceLights Occupied = LightsOn
presenceLights Unoccupied = LightsOff
hallwayLightsController :: HASS (Event Value) ()
hallwayLightsController = proc x -> do
now <- AFRP.currentTime -< ()
p <- hallwayPresence -< x
ev <- eventLights -< p
traceEvent -< ev
case ev of
-- The lights entity is a "group of lights" in hass
Event LightsOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< On Nothing
Event LightsOff -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< Off
_ -> returnA -< ()
where
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
+29 -8
View File
@@ -6,14 +6,13 @@ import AFRP (Event (..))
import qualified AFRP
import Data.Aeson (Value)
import Control.Arrow ((>>>), Arrow (..), returnA)
import Data.Bool (bool)
import Prelude hiding (id)
import Data.Time (LocalTime(..), TimeOfDay (..))
-- Kitchen has two "presence" sensors. One IKEA motion sensor and one SwitchBot presence sensor
data Lights = LightsOn | LightsOff
data Lights = LightsOn | LightsOff | LightsSleep
deriving (Show)
kitchenPresence :: HASS (Event Value) Presence
@@ -46,21 +45,43 @@ dinnerPresence :: HASS (Event Value) Presence
dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
dinnerLightEvents :: HASS (Event Value) (Event Lights)
dinnerLightEvents = ((,) <$> dinnerLightLevel <*> dinnerPresence)
dinnerLightEvents =
((,) <$> dinnerLightLevel <*> dinnerPresence)
>>> arr lightWanted
>>> AFRP.changes
>>> arr (fmap (bool LightsOff LightsOn))
>>> (sleepEvent &&& offEvent &&& onEvent)
>>> arr (\(s, (o, n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
where
-- This means that both light level and occupancy can change the light state
lightWanted (lightLevel, occ) = occ == Occupied && lightLevel < 13
onEvent =
AFRP.edge
>>> arr (fmap (const LightsOn))
sleepEvent =
arr not
>>> AFRP.edge
>>> arr (fmap (const LightsSleep))
offEvent =
arr not
>>> AFRP.waitFor 300
>>> arr (fmap (const LightsOff))
dinnerTableController :: HASS (Event Value) ()
dinnerTableController = proc x -> do
ev <- dinnerLightEvents -< x
case ev of
Event LightsOn -> callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On Nothing
Event LightsOff -> callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< Off
Event LightsOn -> do
sleep -< False
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On Nothing
Event LightsOff -> do
sleep -< False
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< Off
Event LightsSleep -> do
sleep -< True
_ -> returnA -< ()
where
sleep = callServiceDyn (switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"])
kitchenMotionController :: HASS (Event Value) ()
kitchenMotionController = kitchenCeilingController <> dinnerTableController
+19 -20
View File
@@ -18,7 +18,7 @@ import Control.Concurrent.STM (atomically, dupTChan, readTChan)
import Data.Aeson (Value)
import qualified Data.Text as T
import Data.Time (getCurrentTime, getCurrentTimeZone)
import Data.Void (Void, absurd)
import Data.Void (Void)
import HomeAssistant.Controller (HASS, HASSEff (..))
import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Connection (writerAction, readerAction)
@@ -29,8 +29,7 @@ import Data.UUID (UUID, toText)
import qualified Data.UUID.V4 as UUID.V4
import Katip (runKatipT, logF, sl, Severity (..), ls, Namespace (Namespace), runKatipContextT)
import Control.Monad.IO.Class (liftIO, MonadIO)
import HomeAssistant.Controller.Ruuvi (ruuviController)
import HomeAssistant.Controller.Children (schoolLightController)
import HomeAssistant.Controller.Children (schoolLightController, childrenBedroomButtonController)
import Data.Maybe (fromMaybe)
import qualified System.Metrics
import qualified HomeAssistant.Runtime.Metrics
@@ -42,6 +41,7 @@ import HomeAssistant.Runtime.RateLimit (slidingWindowLimiter, registerRateLimitM
import UnliftIO.Async
import HomeAssistant.Runtime.Supervisor (supervised)
import qualified HomeAssistant.Runtime.Graphing
import HomeAssistant.Controller.Hallway (hallwayLightsController)
step :: (MonadIO m) => FilePath -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
step path trace st a = do
@@ -50,25 +50,26 @@ step path trace st a = do
let req = Request now tz trace
stepAutoSerializing path st req a
data Controller = forall b. Controller T.Text (HASS (Event Value) b) Bool
data Controller = forall b. Controller Bool T.Text (HASS (Event Value) b)
controllers :: [Controller]
controllers =
[ Controller "bedroom-presence" bedroomPresenceController True
, Controller "bedroom-button" bedroomButtonController True
, Controller "bedroom-drawer" bedroomDrawerController True
, Controller "bedroom-humidifier" humidifierController True
, Controller "ruuvi-controller" ruuviController False
, Controller "school-light-controller" schoolLightController True
, Controller "kitchen-motion-controller" kitchenMotionController True
, Controller "livingroom-presence" livingroomPresenceController True
[ Controller True "bedroom-presence" bedroomPresenceController
, Controller True "bedroom-button" bedroomButtonController
, Controller True "bedroom-drawer" bedroomDrawerController
, Controller True "bedroom-humidifier" humidifierController
, Controller True "school-light-controller" schoolLightController
, Controller True "kitchen-motion-controller" kitchenMotionController
, Controller True "livingroom-presence" livingroomPresenceController
, Controller True "hallway-motion-controller" hallwayLightsController
, Controller True "children-button" childrenBedroomButtonController
]
-- | Steps the machine for every inbound message; service calls go to the
-- bus. A restart re-dups the inbound channel and starts from the machine's
-- initial state; messages broadcast during the restart window are lost.
runController :: MonadIO m => FilePath -> Bus -> Controller -> m Void
runController rootDir bus (Controller name machine _enabled) = liftIO $ do
runController rootDir bus (Controller _enabled name machine ) = liftIO $ do
inbound <- atomically (dupTChan (busInbound bus))
let ns = Namespace [name]
let workerDefinition = runMealy machine (runKatipContextT (busLogEnv bus) () ns . channelHassEval bus)
@@ -108,18 +109,16 @@ defaultMain = withSocketsDo $ do
rrdtool <- fromMaybe "rrdtool" <$> lookupEnv "HA_RRDTOOL"
metricsPort <- lookupPort
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
let active = [c | c@(Controller _ _ True) <- controllers]
ents = foldMap (\(Controller _ m _) -> entities m) active
let active = [c | c@(Controller True _ _) <- controllers]
ents = foldMap (\(Controller _ _ m) -> entities m) active
workers =
[ ("reader", readerAction host 8123 token ents bus)
, ("writer", writerAction writerLimiter bus)
, ("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool)
, ("metrics-http", HomeAssistant.Runtime.Graphing.graphAction rrdPath rrdtool metricsPort)
] ++ [ (name, runController rootPath bus c) | c@(Controller name _ True) <- controllers ]
as <- runKatipContextT (busLogEnv bus) () mempty $
mapM (\(name, act) -> async (supervised name act)) workers
(_, v) <- waitAny as
absurd v
] ++ [ (name, runController rootPath bus c) | c@(Controller True name _) <- active ]
runKatipContextT (busLogEnv bus) () mempty $
mapConcurrently_ (uncurry supervised) workers
dryRunHassEval :: Namespace -> Bus -> HASSEff a -> IO a
dryRunHassEval ns bus = \case
+150 -20
View File
@@ -59,30 +59,124 @@ parseRange t = lookup t [(T.pack (rangeSuffix r), r) | r <- [minBound .. maxBoun
rangeStart :: Range -> String
rangeStart r = "end-" ++ rangeSuffix r
data CF = Average | Minimum | Maximum | Last
deriving (Eq, Show)
data Source = Source
{ srcDs :: String
, srcCF :: CF
}
deriving (Eq, Show)
data Transform
= Identity
| Multiply Double
deriving (Eq, Show)
data Series = Series
{ serDs :: String
{ serSource :: Source
, serTransform :: Transform
, serAlias :: String
, serColor :: String
, serLabel :: String
}
deriving (Eq, Show)
data Plot
= Line Int Series
| Area Series
deriving (Eq, Show)
data GraphSpec = GraphSpec
{ gsName :: Text
, gsTitle :: String
, gsSeries :: [Series]
, gsPlots :: [Plot]
}
deriving (Eq, Show)
average :: String -> Source
average ds = Source ds Average
maximumCF :: String -> Source
maximumCF ds = Source ds Maximum
line :: String -> String -> Source -> Plot
line alias color source =
Line 2 Series
{ serSource = source
, serTransform = Identity
, serAlias = alias
, serColor = color
, serLabel = alias
}
area :: String -> String -> Source -> Plot
area alias color source =
Area Series
{ serSource = source
, serTransform = Identity
, serAlias = alias
, serColor = color
, serLabel = alias
}
ratelimitGraph :: GraphSpec
ratelimitGraph =
GraphSpec
{ gsName = "ratelimit"
, gsTitle = "Rate limiting"
, gsPlots =
[ Line 2 Series
{ serSource = Source "ratelimit_retry" Average
, serTransform = Multiply 60
, serAlias = "retry"
, serColor = "#0066cc"
, serLabel = "Requests retried/min"
}
, Line 2 Series
{ serSource = Source "ratelimit_exhausted" Average
, serTransform = Multiply 60
, serAlias = "exhaust"
, serColor = "#cc0000"
, serLabel = "Requests exhausted/min"
}
]
}
trafficGraph :: GraphSpec
trafficGraph =
GraphSpec
{ gsName = "traffic"
, gsTitle = "Hass triggers in / services out"
, gsPlots =
[ Line 2 Series
{ serSource = Source "hass_trigger_in" Average
, serTransform = Multiply 60
, serAlias = "in"
, serColor = "#0066cc"
, serLabel = "Triggers in/min"
}
, Line 2 Series
{ serSource = Source "hass_service_out" Average
, serTransform = Multiply 60
, serAlias = "out"
, serColor = "#cc0000"
, serLabel = "Service calls out/min"
}
]
}
memoryGraph :: GraphSpec
memoryGraph =
GraphSpec
"memory"
"Memory use"
[ area "live" "#99ccff" (average "rts_gc_current__a7a")
, line "peak" "#cc0000" (maximumCF "rts_gc_current__a7a")
]
graphs :: [GraphSpec]
graphs =
[ GraphSpec
"traffic"
"Hass triggers in / services out"
[ Series "hass_trigger_in" "trig" "#0066cc" "triggers in/min"
, Series "hass_service_out" "svc" "#cc0000" "services out/min"
]
]
graphs = [memoryGraph, ratelimitGraph, trafficGraph]
lookupGraph :: [GraphSpec] -> Text -> Maybe GraphSpec
lookupGraph specs name = case [g | g <- specs, gsName g == name] of
@@ -92,6 +186,48 @@ lookupGraph specs name = case [g | g <- specs, gsName g == name] of
parseNameParam :: [GraphSpec] -> Text -> Maybe GraphSpec
parseNameParam specs t = T.stripSuffix ".png" t >>= lookupGraph specs
cfName :: CF -> String
cfName = \case
Average -> "AVERAGE"
Minimum -> "MIN"
Maximum -> "MAX"
Last -> "LAST"
defArgs :: FilePath -> Series -> [String]
defArgs rrdPath series =
[ "DEF:" ++ rawF ++ "=" ++ rrdPath ++ ":"
++ srcDs source ++ ":" ++ cfName (srcCF source)
]
++ transformArgs
where
source = serSource series
alias = serAlias series
rawF = alias ++ "_raw"
transformArgs = case serTransform series of
Identity ->
[ "CDEF:" ++ alias ++ "=" ++ rawF ]
Multiply factor ->
[ "CDEF:" ++ alias ++ "=" ++ rawF
++ "," ++ show factor ++ ",*"
]
plotArg :: Plot -> String
plotArg = \case
Line width series ->
"LINE" ++ show width ++ ":" ++ serAlias series
++ serColor series ++ ":" ++ serLabel series
Area series ->
"AREA:" ++ serAlias series
++ serColor series ++ ":" ++ serLabel series
plotSeries :: Plot -> Series
plotSeries = \case
Line _ series -> series
Area series -> series
buildGraphArgs :: FilePath -> GraphSpec -> Range -> [String]
buildGraphArgs rrdPath spec range =
[ "graph"
@@ -102,15 +238,9 @@ buildGraphArgs rrdPath spec range =
, "--height", "250"
, "--imgformat", "PNG"
]
++ concatMap defArgs (gsSeries spec)
++ map line (gsSeries spec)
where
defArgs (Series ds alias _ _) =
[ "DEF:" ++ alias ++ "=" ++ rrdPath ++ ":" ++ ds ++ ":AVERAGE"
, "CDEF:" ++ alias ++ "_min=" ++ alias ++ ",60,*"
]
line (Series _ alias color label) =
"LINE2:" ++ alias ++ "_min" ++ color ++ ":" ++ label
++ concatMap (defArgs rrdPath . plotSeries) (gsPlots spec)
++ map plotArg (gsPlots spec)
readProcessBytes :: FilePath -> [String] -> IO (ExitCode, BS.ByteString, String)
readProcessBytes cmd args =
@@ -159,5 +289,5 @@ graphAction :: MonadIO m => FilePath -> FilePath -> Int -> m Void
graphAction rrdPath rrdtool port = liftIO $ forever $ scottyOpts opts (app rrdPath rrdtool)
where
opts = defaultOptions
{ settings = setHost "127.0.0.1" (setPort port defaultSettings)
{ settings = setHost "0.0.0.0" (setPort port defaultSettings)
}
+1 -1
View File
@@ -69,6 +69,6 @@ runRateLimited (RateLimiter metrics run) action = checkpointCallStack $ do
run action
maybe (incReject >> throw RateLimitExhausted) pure x
where
retryPolicy = fullJitterBackoff 50000 <> limitRetries 5
retryPolicy = fullJitterBackoff 500_000 <> limitRetries 5
incRetry = liftIO $ Counter.inc (rlRetries metrics)
incReject = liftIO $ Counter.inc (rlRejects metrics)
+3 -3
View File
@@ -16,7 +16,7 @@ import Data.Void (Void)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Catch (MonadCatch, MonadMask)
import Katip (KatipContext, logFM, ls)
import Control.Retry (RetryStatus(..), recovering, limitRetries, fullJitterBackoff)
import Control.Retry (RetryStatus(..), recovering, fullJitterBackoff, capDelay, skipAsyncExceptions)
import Control.Monad (when)
import Katip.Core (Severity(..))
@@ -41,7 +41,7 @@ instance Exception SupervisorException
-- restarted instead of escalated.
supervised :: (MonadIO m, MonadCatch m, KatipContext m, MonadMask m) => Text -> m Void -> m Void
supervised name action = checkpoint (Annotation name) $ do
recovering retryPolicy handlers $ \RetryStatus{rsIterNumber} -> do
recovering retryPolicy (skipAsyncExceptions ++ handlers) $ \RetryStatus{rsIterNumber} -> do
when (rsIterNumber > 0) $ logFM WarningS $ ls $ "Child crashed, retry no " <> show rsIterNumber
action
where
@@ -49,4 +49,4 @@ supervised name action = checkpoint (Annotation name) $ do
[ \_retryStatus -> Handler $ \(_ :: Fatal) -> pure False
, \_retryStatus -> Handler $ \(_ :: SomeException) -> pure True
]
retryPolicy = fullJitterBackoff 50000 <> limitRetries 5
retryPolicy = capDelay (15 * 1_000_000) (fullJitterBackoff 50_000)
+17 -16
View File
@@ -45,6 +45,7 @@ entitySpec = describe "entities" $ do
`shouldBe` S.fromList
[ "event.bedroom_quick_remote_masse_action"
, "event.bedroom_quick_jemina_action"
, "event.bedroom_remote_action"
]
it "bedroomPresenceController subscribes to the presence sensor" $
@@ -89,36 +90,36 @@ buttonSpec = describe "bedroomButtonController" $ do
let area = AreaId "makuuhuone"
it "Masse single click turns on his nightstand scene (lowest)" $
services (runHASS bedroomButtonController [masseButton "1_short_release"])
`shouldBe` [[activateScene "scene.makuuhuone_masse"]]
concat (services (runHASS bedroomButtonController [masseButton "1_short_release"]))
`shouldContain` [activateScene "scene.makuuhuone_masse"]
it "Masse double click turns on the middle scene" $
services (runHASS bedroomButtonController [masseButton "1_double_press"])
`shouldBe` [[activateScene "scene.makuuhuone_keski"]]
concat (services (runHASS bedroomButtonController [masseButton "1_double_press"]))
`shouldContain` [activateScene "scene.makuuhuone_keski"]
it "Masse long click turns on the bright scene" $
services (runHASS bedroomButtonController [masseButton "1_long_press"])
`shouldBe` [[activateScene "scene.makuuhuone_kirkas"]]
concat (services (runHASS bedroomButtonController [masseButton "1_long_press"]))
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
it "Masse off click turns the bedroom lights off" $
services (runHASS bedroomButtonController [masseButton "2_short_release"])
`shouldBe` [[light [area] Off]]
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
`shouldContain` [light [area] Off]
it "Enishen single click turns on her nightstand scene (lowest)" $
services (runHASS bedroomButtonController [enishenButton "1_short_release"])
`shouldBe` [[activateScene "scene.makuuhuone_jemina"]]
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
`shouldContain` [activateScene "scene.makuuhuone_jemina"]
it "Enishen double click turns on the middle scene" $
services (runHASS bedroomButtonController [enishenButton "1_double_press"])
`shouldBe` [[activateScene "scene.makuuhuone_keski"]]
concat (services (runHASS bedroomButtonController [enishenButton "1_double_press"]))
`shouldContain` [activateScene "scene.makuuhuone_keski"]
it "Enishen long click turns on the bright scene" $
services (runHASS bedroomButtonController [enishenButton "1_long_press"])
`shouldBe` [[activateScene "scene.makuuhuone_kirkas"]]
concat (services (runHASS bedroomButtonController [enishenButton "1_long_press"]))
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
it "Enishen off click turns the bedroom lights off" $
services (runHASS bedroomButtonController [enishenButton "2_short_release"])
`shouldBe` [[light [area] Off]]
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
`shouldContain` [light [area] Off]
it "ignores the initial press (scene only fires on release)" $
services (runHASS bedroomButtonController [masseButton "1_initial_press"])
+6 -6
View File
@@ -83,12 +83,12 @@ spec = do
, "--width", "800"
, "--height", "250"
, "--imgformat", "PNG"
, "DEF:trig=hass-controller.rrd:hass_trigger_in:AVERAGE"
, "CDEF:trig_min=trig,60,*"
, "DEF:svc=hass-controller.rrd:hass_service_out:AVERAGE"
, "CDEF:svc_min=svc,60,*"
, "LINE2:trig_min#0066cc:triggers in/min"
, "LINE2:svc_min#cc0000:services out/min"
, "DEF:in_raw=hass-controller.rrd:hass_trigger_in:AVERAGE"
, "CDEF:in=in_raw,60.0,*"
, "DEF:out_raw=hass-controller.rrd:hass_service_out:AVERAGE"
, "CDEF:out=out_raw,60.0,*"
, "LINE2:in#0066cc:Triggers in/min"
, "LINE2:out#cc0000:Service calls out/min"
]
describe "end-to-end (rrdtool-gated)" $ do
+24 -1
View File
@@ -1,9 +1,32 @@
{-# LANGUAGE OverloadedStrings #-}
module RuntimeSpec (spec) where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (async, cancel, race, waitCatch)
import Control.Exception (bracket)
import Control.Monad (forever)
import Control.Monad.IO.Class (liftIO)
import HomeAssistant.Runtime.Supervisor (supervised)
import Katip (LogEnv, closeScribes, initLogEnv, runKatipContextT)
import Test.Hspec
spec :: Spec
spec = pure ()
spec = describe "supervised" $ do
it "propagates ThreadKilled instead of retrying" $
withTestLogEnv $ \le -> do
worker <- async $ runKatipContextT le () mempty $
supervised "test" (liftIO (forever (threadDelay 100000)))
threadDelay 200000
cancel worker
result <- race (threadDelay 5000000) (waitCatch worker)
case result of
Left () -> expectationFailure
"supervised retried on ThreadKilled (process would hang)"
Right _ -> pure ()
withTestLogEnv :: (LogEnv -> IO a) -> IO a
withTestLogEnv = bracket (initLogEnv "test" "test") closeScribes
-- I'm commenting out the test as that specific controller
-- was just a dummy for seeing how the data flows (dead code)