[state-based mainloop Evan Martin **20060217053725] { hunk ./MPD.hs 33 -runCommand handle cmd = do - hPutStrLn handle cmd +runCommand conn cmd = do + hPutStrLn conn cmd hunk ./MPD.hs 39 - line <- hGetLine handle + line <- hGetLine conn hunk ./MPD.hs 44 -runCommand_ handle cmd = runCommand handle cmd >> return () +runCommand_ conn cmd = runCommand conn cmd >> return () hunk ./MPD.hs 47 -getVolume handle = do - lines <- runCommand handle "status" +getVolume conn = do + lines <- runCommand conn "status" hunk ./MPD.hs 56 -setVolume handle v = runCommand_ handle ("setvol " ++ show v) +setVolume conn v = runCommand_ conn ("setvol " ++ show v) hunk ./MPD.hs 58 -type ReconnectableConnection = (IORef Handle, (String, Int)) +withReconnect :: Connection -> (String, Int) -> (Connection -> IO ()) -> IO Connection +withReconnect conn addr func = do + func conn >> return conn `catch` \e -> do + -- print $ ioeGetErrorString e + newconn <- MPD.connect addr + func newconn + return newconn + +type ReconnectableConnection = (IORef Connection, (String, Int)) hunk ./MPD.hs 79 - job conn `catch` \e -> do - -- print $ ioeGetErrorString e - newconn <- MPD.connect addr - writeIORef connref newconn - job newconn + newconn <- withReconnect conn addr job + writeIORef connref newconn hunk ./MPDMate.hs 10 +import Data.IORef hunk ./MPDMate.hs 14 -processEvent :: MPD.Connection -> PowerMate.Event -> IO () -processEvent mpd (PowerMate.Button True) = MPD.runCommand_ mpd "pause" -processEvent mpd (PowerMate.Button False) = return () +data State = State { + stConn :: MPD.ReconnectableConnection, + stVolume :: IORef Int +} hunk ./MPDMate.hs 19 -processEvent mpd (PowerMate.Rotate dir) = do +processEvent :: State -> PowerMate.Event -> IO () +processEvent state (PowerMate.Button True) = + MPD.rcDo (stConn state) $ \conn -> MPD.runCommand_ conn "pause" +processEvent state (PowerMate.Button False) = return () + +processEvent state (PowerMate.Rotate dir) = do hunk ./MPDMate.hs 27 - MPD.runCommand_ mpd ("volume " ++ show dir) + MPD.rcDo (stConn state) $ \conn -> MPD.runCommand_ conn ("volume " ++ show dir) hunk ./MPDMate.hs 29 -processEvent mpd PowerMate.Misc = putStrLn "misc" +processEvent state PowerMate.Misc = do + putStrLn "misc" hunk ./MPDMate.hs 35 + vol <- newIORef 0 + let state = State { stConn=conn, stVolume=vol } + hunk ./MPDMate.hs 42 - Just ev -> MPD.rcDo conn (\mpd -> processEvent mpd ev) + Just ev -> processEvent state ev hunk ./MPDMate.hs 51 + --PowerMate.writeStatus handle_pm $ PowerMate.statusInit { PowerMate.brightness=100, PowerMate.pulse_asleep = True } }