diff options
author | Fabian Kirchner <kirchner@posteo.de> | 2024-08-13 09:25:32 +0200 |
---|---|---|
committer | Fabian Kirchner <kirchner@posteo.de> | 2024-08-13 09:25:32 +0200 |
commit | 3533c6941bf7a7732a0cf81465e97949c4969be4 (patch) | |
tree | e443254a983e7a7535da100370bf42bd093917f5 /app/Sensor.hs | |
parent | 5049d28f806b746e6f69bdf616a88d7ed53292de (diff) |
refactor: introduce ADT for battery state
Diffstat (limited to 'app/Sensor.hs')
-rw-r--r-- | app/Sensor.hs | 38 |
1 files changed, 30 insertions, 8 deletions
diff --git a/app/Sensor.hs b/app/Sensor.hs index a9acf15..8c984f8 100644 --- a/app/Sensor.hs +++ b/app/Sensor.hs @@ -195,7 +195,13 @@ mem = diagram 3 memStat data BatStat = BatStat deriving (Show) -instance (S.MonadSensor m) => S.Aggregate m BatStat (Float, Bool) where +data BatState + = NotCharging + | Charging + | Discharging + deriving (Generic, Eq, NFData) + +instance (S.MonadSensor m) => S.Aggregate m BatStat (Float, BatState) where aggregate _ = forever do S.yield =<< parse <* sleep where parse = liftIO do @@ -204,9 +210,14 @@ instance (S.MonadSensor m) => S.Aggregate m BatStat (Float, Bool) where =<< listDirectory "/sys/class/power_supply" combine abs = ( product (map fst abs), - or (map Prelude.snd abs) + if any ((==) Discharging) (map Prelude.snd abs) + then Discharging + else + if any ((==) Charging) (map Prelude.snd abs) + then Charging + else NotCharging ) - parse1 :: FilePath -> IO (Float, Bool) + parse1 :: FilePath -> IO (Float, BatState) parse1 fp = liftM2 (,) @@ -219,13 +230,24 @@ instance (S.MonadSensor m) => S.Aggregate m BatStat (Float, Bool) where <*> (readFile (fp </> "energy_full") (pure . read)) ] ) - (choice False [readFile (fp </> "status") (pure . (==) "charging" . map toLower)]) + (choice NotCharging [readFile (fp </> "status") (pure . parseBatState . map toLower)]) + parseBatState :: String -> BatState + parseBatState string = + case string of + "not charging" -> + NotCharging + "charging" -> + Charging + "discharging" -> + Discharging + _ -> + error ("invalid bat state: " ++ string) bat :: (S.MonadSensor m) => S.Sensor m () P.Doc bat = - S.sensor BatStat >>= \(value, charging) -> - if charging - then + S.sensor BatStat >>= \(value, batState) -> + case batState of + Charging -> if | value >= 0.9 -> pure (P.pretty "\xf0085") | value >= 0.8 -> pure (P.pretty "\xf008b") @@ -237,7 +259,7 @@ bat = | value >= 0.2 -> pure (P.pretty "\xf0087") | value >= 0.1 -> pure (P.pretty "\xf0086") | otherwise -> pure (P.pretty "\xf089c") - else + _ -> if | value >= 0.95 -> pure (P.pretty "\xf0079") | value >= 0.9 -> pure (P.pretty "\xf0082") |