summaryrefslogtreecommitdiff
path: root/KikiD/Message.hs
blob: cd3ee7130f2f0734b43b28bcc3775d6f632f48ec (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
{-# LANGUAGE DoAndIfThenElse #-}
module KikiD.Message where

import Data.Serialize as Cereal
import qualified Data.ByteString.Char8 as B
import Data.Monoid
import Text.Read
import Data.Char (ord,chr)
import Control.Monad
import Data.Bytes.Serial as R
import Data.Bytes.Put as Put
import Data.Bytes.Get as Get
import Codec.LineReady
import Control.Monad.Loops

data KikiDMessage = TODO deriving (Show,Read)

instance Serialize KikiDMessage where
    put m = mapM_ (Cereal.putWord8 . fromIntegral . ord) "TO\nO"
                -- putByteString . B.pack $ show m ++ "\n"
    get = do
        t <- Cereal.getWord8
        o <- Cereal.getWord8
        d <- Cereal.getWord8
        o <- Cereal.getWord8
        let s = map (chr . fromIntegral) [t,o,d,o] 
        if "TO\nO" == s
        then return TODO
        else fail ("Could not decode message: " ++ show s)

instance Serial KikiDMessage where
    serialize m = Put.putByteString . toLineReady . Cereal.encode $ m
    deserialize = do 
        xs <- unfoldWhileM (/= '\n') (fmap (chr . fromIntegral) Get.getWord8)
        case (Cereal.decode . fromLineReady $ B.pack xs) of
            Left str -> fail str
            Right x  -> return x