{-# LANGUAGE OverloadedStrings #-} import Control.Applicative((<*)) import Data.Attoparsec(Parser,takeWhile1) import Data.Attoparsec.Char8 (char8, endOfLine, isEndOfLine) import Data.Attoparsec.Enumerator(iterParser) import Data.Enumerator(Iteratee,Enumerator,run_,($$)) import Data.Enumerator.Binary (enumHandle) import System.Environment(getArgs) import System.IO (Handle,stdin) import Data.ByteString.Char8(ByteString,unpack) import Network.HTTP(simpleHTTP,getRequest) import Network.HTTP.Base(urlEncode) import System.Hardware.Serialport(hOpenSerial,defaultSerialSettings,commSpeed,CommSpeed(CS115200)) data Message = Measurement ByteString ByteString deriving (Show) parser :: Parser Message parser = do sensor <- takeWhile1 (/=61) <* char8 '=' value <- takeWhile1 (not . isEndOfLine) <* endOfLine return $! Measurement sensor value parserIteratee :: Handle -> Iteratee ByteString IO (Message) parserIteratee handle = stdinEnumerator $$ iteratee where stdinEnumerator :: Enumerator ByteString IO b stdinEnumerator = enumHandle 1 handle iteratee :: Iteratee ByteString IO (Message) iteratee = iterParser parser work :: Handle -> IO () work port = do (Measurement sensor value) <- run_ (parserIteratee port) let url = "http://localhost:8080/api/value/" ++ (urlEncode $ unpack sensor) ++ "/" ++ (urlEncode $ unpack value) in simpleHTTP (getRequest url) putStrLn $ (unpack sensor) ++ "=" ++ (unpack value) work port main :: IO () main = do args <- getArgs port <- case args of [path] -> hOpenSerial path defaultSerialSettings { commSpeed = CS115200 } _ -> return stdin work port