_Common.icl 1.55 KB
Newer Older
1
implementation module iTasks.Extensions.Device._Common
2 3 4 5 6 7 8 9 10 11
import iTasks
from Text import class Text, instance Text String
import qualified Text as T

:: DeviceRequestState  = { buffer :: String, result :: String }

derive class iTask DeviceRequestState

deviceRequest :: String (String -> Bool) -> Task String
deviceRequest request close
12
	= tcpconnect "127.0.0.1" 20097 Nothing (constShare ())
13 14
		{ ConnectionHandlers
		| onConnect      = onConnect
15 16
		, onData	 = onData
		, onShareChange  = onShareChange
17
		, onDisconnect   = onDisconnect
Mart Lubbers's avatar
Mart Lubbers committed
18
		, onDestroy= \s->(Ok s, [])
19
		} 
Mart Lubbers's avatar
Mart Lubbers committed
20
	>>- \{DeviceRequestState|result} -> return result            
21
where
Haye Böhm's avatar
Haye Böhm committed
22 23
	onConnect :: ConnectionId String () -> (MaybeErrorString DeviceRequestState, Maybe (), [String], Bool)
	onConnect connId host _
24 25 26 27 28 29
		= ( Ok { buffer = "", result = "" }
		  , Nothing
      	  , [request +++ "\n"]
      	  , False
      	  )

30 31
	onData :: String DeviceRequestState () -> (MaybeErrorString DeviceRequestState, Maybe (), [String], Bool)
	onData newData state=:{buffer} _
32 33 34 35 36 37 38 39 40 41 42 43
		#! buffer = buffer +++ newData
		# splitpoint = 'T'.indexOf "\n" buffer
		| splitpoint <> -1 		
			# result = 'T'.subString 0 splitpoint buffer
			# incomplete = 'T'.dropChars (splitpoint + 1) buffer
			= (Ok {state & buffer = incomplete
			  , result = result}
			  , Nothing
			  , []
			  , close result
			  )
		= (Ok {state & buffer = buffer}, Nothing, [], False)
44 45

	onShareChange state _
46 47 48 49 50
		= (Ok state, Nothing, [], False)

	onDisconnect :: DeviceRequestState () -> (MaybeErrorString DeviceRequestState, Maybe ())
	onDisconnect state _
		= (Ok state, Nothing)