summaryrefslogtreecommitdiff
path: root/datasources/serialparser.hs
blob: 24686f58cbe918069669878dd5a8e65a0f6ef891 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
{-# 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