summaryrefslogtreecommitdiffhomepage
path: root/Plugins/Monitors/Batt.hs
blob: 6a7a858679b5c7ae0f70c4b471aba5a27031aa94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
-----------------------------------------------------------------------------
-- |
-- Module      :  Plugins.Monitors.Batt
-- Copyright   :  (c) Andrea Rossato
-- License     :  BSD-style (see LICENSE)
-- 
-- Maintainer  :  Andrea Rossato <andrea.rossato@unibz.it>
-- Stability   :  unstable
-- Portability :  unportable
--
-- A battery monitor for Xmobar
--
-----------------------------------------------------------------------------

module Plugins.Monitors.Batt where

import qualified Data.ByteString.Lazy.Char8 as B
import Plugins.Monitors.Common
import System.Posix.Files (fileExist)

data Batt = Batt Float 
          | NA

battConfig :: IO MConfig
battConfig = mkMConfig
       "Batt: <left>" -- template
       ["left"]       -- available replacements

fileB0 :: (String, String)
fileB0 = ("/proc/acpi/battery/BAT0/info", "/proc/acpi/battery/BAT0/state")

fileB1 :: (String, String)
fileB1 = ("/proc/acpi/battery/BAT1/info", "/proc/acpi/battery/BAT1/state")

fileB2 :: (String, String)
fileB2 = ("/proc/acpi/battery/BAT2/info", "/proc/acpi/battery/BAT2/state")

readFileBatt :: (String, String) -> IO (B.ByteString, B.ByteString)
readFileBatt (i,s) = 
    do a <- rf i
       b <- rf s
       return (a,b)
    where rf file = do
            f <- fileExist file
            if f then B.readFile file else return B.empty

parseBATT :: IO Batt
parseBATT =
    do (a0,b0) <- readFileBatt fileB0
       (a1,b1) <- readFileBatt fileB1
       (a2,b2) <- readFileBatt fileB2
       let sp p s = case stringParser p s of
                      [] -> 0
                      x -> read x
           (f0, p0) = (sp (3,2) a0, sp (2,4) b0)
           (f1, p1) = (sp (3,2) a1, sp (2,4) b1)
           (f2, p2) = (sp (3,2) a2, sp (2,4) b2)
           left = (p0 + p1 + p2) / (f0 + f1 + f2) --present / full
       return $ if isNaN left then NA else Batt left

formatBatt :: Float -> Monitor [String] 
formatBatt x =
    do let f s = floatToPercent (s / 100)
       l <- showWithColors f (x * 100)
       return [l]

runBatt :: [String] -> Monitor String
runBatt _ =
    do c <- io $ parseBATT
       case c of
         Batt x -> do l <- formatBatt x
                      parseTemplate l 
         NA -> return "N/A"