{-# LANGUAGE LambdaCase #-}
module STLink.Driver
( inCommand
, outCommand
, withAutoBoard
, withBoard
, STLink(STLink)
)
where
import Control.Monad.Except
import qualified Data.ByteString as BS
import STLink.Detection
import System.USB
eguard :: Monad m => e -> Bool -> ExceptT e m ()
eguard e True = throwError e
eguard _ False = pure ()
inCommand
:: DeviceHandle -> BS.ByteString -> Size -> ExceptT String IO BS.ByteString
inCommand h c s = do
(size, sendStatus) <- liftIO $ writeBulk h (EndpointAddress 1 Out) c 1000
eguard "sent command truncated" $ size /= BS.length c
eguard "send timed out" $ sendStatus /= Completed
(d, recStatus) <- liftIO $ readBulk h (EndpointAddress 1 In) s 1000
eguard "response truncated" $ s /= BS.length d
eguard "receive timed out" $ recStatus /= Completed
pure d
outCommand
:: DeviceHandle -> BS.ByteString -> BS.ByteString -> ExceptT String IO ()
outCommand h c d = do
(sendSize, sendStatus) <- liftIO $ writeBulk h (EndpointAddress 1 Out) c 1000
eguard "sent command truncated" $ sendSize /= BS.length c
eguard "send command timed out" $ sendStatus /= Completed
(recSize, recStatus) <- liftIO $ writeBulk h (EndpointAddress 1 Out) d 1000
eguard "sent data truncated" $ recSize /= BS.length d
void $ eguard "send data timed out" $ recStatus /= Completed
newtype STLink a = STLink
{ runSTLink :: DeviceHandle -> ExceptT String IO a
}
instance Functor STLink where
fmap f (STLink m) = STLink $ fmap f . m
instance Applicative STLink where
pure x = STLink $ const (pure x)
(STLink f) <*> (STLink m) = STLink $ \h -> f h <*> m h
instance Monad STLink where
(STLink m) >>= f = STLink $ \h -> m h >>= ($ h) . runSTLink . f
instance MonadIO STLink where
liftIO m = STLink $ const (liftIO m)
withAutoBoard :: STLink a -> IO (Maybe a)
withAutoBoard s = pickBoard >>= maybe (pure Nothing) (`withBoard` s)
withBoard :: Device -> STLink a -> IO (Maybe a)
withBoard d s = withDeviceHandle d $ \h ->
withClaimedInterface h 0
$ runExceptT (runSTLink s h)
>>= \case
Left e -> do
liftIO . putStrLn $ "stlink driver error: " ++ e
pure Nothing
Right a -> pure $ Just a