{-# LANGUAGE RecordWildCards #-}
module Network.UI.Kafka.Joystick (
joystickLoop
) where
import Control.Monad (guard)
import Data.ByteString.Lazy.Char8 (hGet)
import Data.Maybe (catMaybes)
import Network.UI.Kafka (ExitAction, LoopAction, TopicConnection, Sensor, producerLoop)
import Network.UI.Kafka.Types (Button(..), Event(..), Toggle(..))
import System.Hardware.Linux.Joystick (Joystick(..), byteLength, interpretJoystick, maxValue)
import System.IO (IOMode(ReadMode), hClose, openFile)
joystickLoop :: FilePath
-> TopicConnection
-> Sensor
-> IO (ExitAction, LoopAction)
joystickLoop path topicConnection sensor =
do
joystick <- openFile path ReadMode
(exit, loop) <-
producerLoop topicConnection sensor
$ translate
. interpretJoystick
<$> hGet joystick byteLength
return
(
do
exit
hClose joystick
, loop
)
translate :: Joystick
-> [Event]
translate Joystick{..} =
catMaybes
[
do
guard button
return
$ ButtonEvent (IndexButton number, if value == 0 then Up else Down)
, do
guard axis
return
$ AnalogEvent number (fromIntegral value / fromIntegral maxValue)
]