xmonad-config/lib/ACPI.hs

85 lines
2.2 KiB
Haskell
Raw Normal View History

2020-03-28 18:38:38 -04:00
{-# LANGUAGE LambdaCase #-}
2020-03-22 23:20:10 -04:00
{-# LANGUAGE OverloadedStrings #-}
module ACPI
( ACPIEvent(..)
, isDischarging
, runPowermon
2020-03-28 18:38:38 -04:00
, handleACPI
2020-03-22 23:20:10 -04:00
) where
2020-03-28 18:38:38 -04:00
import Power
2020-03-22 23:46:56 -04:00
import SendXMsg
2020-03-13 20:50:13 -04:00
2020-03-22 23:46:56 -04:00
import Control.Exception
import Control.Monad
2020-03-13 20:50:13 -04:00
2020-03-22 23:46:56 -04:00
import Data.ByteString hiding (readFile)
import Data.ByteString.Char8 as C hiding (readFile)
import Data.Connection
2020-03-22 23:20:10 -04:00
2020-03-22 23:46:56 -04:00
import System.IO.Streams.Internal as S (read)
import System.IO.Streams.UnixSocket
2020-03-22 23:20:10 -04:00
2020-03-28 18:38:38 -04:00
import Text.Read (readMaybe)
import XMonad.Core
2020-03-22 23:20:10 -04:00
data ACPIEvent = Power
| Sleep
| LidClose
deriving (Eq)
instance Enum ACPIEvent where
toEnum 0 = Power
toEnum 1 = Sleep
toEnum 2 = LidClose
2020-03-22 23:46:56 -04:00
toEnum _ = errorWithoutStackTrace "ACPI.Enum.ACPIEvent.toEnum: bad argument"
2020-03-22 23:20:10 -04:00
fromEnum Power = 0
fromEnum Sleep = 1
fromEnum LidClose = 2
sendACPIEvent :: ACPIEvent -> IO ()
2020-03-25 14:45:21 -04:00
sendACPIEvent = sendXMsg ACPI . show . fromEnum
2020-03-22 23:20:10 -04:00
parseLine :: ByteString -> Maybe ACPIEvent
parseLine line =
case splitLine line of
(_:"PBTN":_) -> Just Power
(_:"PWRF":_) -> Just Power
(_:"SLPB":_) -> Just Sleep
(_:"SBTN":_) -> Just Sleep
(_:"LID":"close":_) -> Just LidClose
_ -> Nothing
where
splitLine = C.words . C.reverse . C.dropWhile (== '\n') . C.reverse
2020-03-13 20:50:13 -04:00
isDischarging :: IO (Maybe Bool)
isDischarging = do
status <- try $ readFile "/sys/class/power_supply/BAT0/status"
:: IO (Either IOException String)
case status of
2020-03-22 23:20:10 -04:00
Left _ -> return Nothing
2020-03-13 20:50:13 -04:00
Right s -> return $ Just (s == "Discharging")
2020-03-22 23:20:10 -04:00
runPowermon :: IO ()
runPowermon = do
-- TODO barf when the socket doesn't exist
Connection { source = s } <- connect "/var/run/acpid.socket"
forever $ readStream s
where
readStream s = do
out <- S.read s
mapM_ sendACPIEvent $ parseLine =<< out
2020-03-28 18:38:38 -04:00
handleACPI :: String -> X ()
handleACPI tag = do
let acpiTag = toEnum <$> readMaybe tag :: Maybe ACPIEvent
forM_ acpiTag $ \case
Power -> runPowerPrompt
Sleep -> runSuspendPrompt
LidClose -> do
status <- io isDischarging
forM_ status $ \s -> runScreenLock >> when s runSuspend