module Monky.Examples.Wifi
( getWifiHandle
, WifiHandle
, WifiFormat(..)
)
where
import Formatting
import Data.Word (Word32, Word8)
import Data.Int (Int32)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Maybe (fromMaybe)
import Monky.Modules
import Monky.Examples.Utility
import Monky.Wifi
#if MIN_VERSION_base(4,8,0)
#else
import Control.Applicative ((<$>))
#endif
data WifiHandle = WH SSIDSocket Interface (WifiStats -> Text) Text
data WifiFormat
= FormatChannel
| FormatRates
| FormatName
| FormatFreq
| FormatSignal
| FormatText Text
getFun :: WifiFormat -> WifiStats -> Text
getFun FormatChannel = sformat int . wifiChannel
getFun FormatRates = flip convertUnitSI "B" . maximum . wifiRates
getFun FormatName = T.pack . wifiName
getFun FormatFreq = sformat int . wifiFreq
getFun FormatSignal = sformat int . doStrength . wifiSig
getFun (FormatText str) = const str
getFunction :: [WifiFormat] -> WifiStats -> Text
getFunction xs = T.concat . (\a -> map (($ a) . getFun) xs)
doMBM :: Word32 -> Word8
doMBM e =
let noiseFloor = 90
signalMax = 20
work :: Int32 = fromIntegral e
clamped :: Float = min signalMax $ max noiseFloor $ fromIntegral $ work `div` 100
in floor (100 70 * ((signalMax clamped) / (signalMax noiseFloor)))
doStrength :: Signal -> Word8
doStrength (SigMBM mbm) = doMBM mbm
doStrength (SigUNSPEC unspec) = unspec
getWifiHandle
:: [WifiFormat]
-> Text
-> String
-> IO WifiHandle
getWifiHandle f d n = do
let fun = getFunction f
s <- getSSIDSocket
i <- fromMaybe (error ("Could not find interface: " ++ n)) <$> getInterface s n
return (WH s i fun d)
getEventOutput :: WifiHandle -> IO [MonkyOut]
getEventOutput (WH s i f d) = do
new <- gotReadable s i
case new of
(WifiConnect x) -> return [MonkyPlain $ f x]
WifiNone -> return []
WifiDisconnect -> return [MonkyPlain d]
instance EvtModule WifiHandle where
startEvtLoop h@(WH s _ _ _) r = do
r =<< getOutput h
prepareEvents s
loopFd h (getWifiFd s) r getEventOutput
instance PollModule WifiHandle where
getOutput (WH s i f d) = do
ret <- getCurrentWifiStats s i
return [MonkyPlain $ maybe d f ret]