demo
[mTask.git] / miTask.icl
1 module miTask
2
3 import StdDebug, StdMisc
4 from StdFunc import flip
5
6 import iTasks
7 import mTask
8
9 from Text import class Text(startsWith,concat,split,join), instance Text String
10
11 import Data.Tuple
12 import System.Directory
13
14 import iTasks.UI.Definition
15
16 import iTasks._Framework.TaskState
17 import iTasks._Framework.TaskServer
18 import iTasks._Framework.IWorld
19 import iTasks._Framework.Store
20
21 import TTY
22
23 derive class iTask Queue, TTYSettings, Parity, BaudRate, ByteSize
24 derive class iTask MTaskMSGRecv, MTaskMSGSend, SerTCP, UserLED
25
26 :: SerTCP = Serial | TCP
27 :: *Resource | TTYd !*TTY
28
29 Start :: *World -> *World
30 Start world = startEngine mTaskTask world
31 //Start world = startEngine mTaskTask world
32
33 bc :: Main (ByteCode () Stmt)
34 bc = sds \x=1 In sds \pinnetje=1 In {main =
35 IF (digitalRead D3) (
36 x =. x +. lit 1 :.
37 pub x
38 ) (
39 noOp
40 ) :.
41 IF (pinnetje ==. lit 1) (
42 ledOn LED1
43 ) (
44 IF (pinnetje ==. lit 2) (
45 ledOn LED2
46 ) (
47 ledOn LED3
48 )
49 )}
50
51 bc2 :: UserLED -> Main (ByteCode () Stmt)
52 bc2 d = {main = ledOn d}
53
54 bc3 :: UserLED -> Main (ByteCode () Stmt)
55 bc3 d = {main = ledOff d}
56
57
58 withDevice :: ((Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task a) -> Task a | iTask a
59 withDevice t = withShared ([], [], False) \ch->
60 enterInformation "Type" []
61 >>= \ty->case ty of
62 TCP = (enterInformation "Host" [] -&&- enterInformation "Port" [])
63 >>= \(port,host)->t ch -|| syncNetworkChannel host port ch
64 Serial = accWorld getDevices
65 >>= \dl->(enterChoice "Device" [] dl -&&- updateInformation "Settings" [] zero)
66 >>= \(dev,set)->t ch -|| syncSerialChannel dev set ch
67 where
68 getDevices :: !*World -> *(![String], !*World)
69 getDevices w = case readDirectory "/dev" w of
70 (Error (errcode, errmsg), w) = abort errmsg
71 (Ok entries, w) = (map ((+++) "/dev/") (filter isTTY entries), w)
72 where
73 isTTY s = not (isEmpty (filter (flip startsWith s) prefixes))
74 prefixes = ["ttyS", "ttyACM", "ttyUSB", "tty.usbserial"]
75
76 mTaskTask :: Task ()
77 mTaskTask = let (msgs, sdsShares) = makeMsgs 1000 bc in
78 withDevice \ch->
79 sendMsg msgs ch
80 ||- processMessages ch messageShare sdsShares
81 ||- forever (enterChoice "Choose led to enable" [] [LED1, LED2, LED3]
82 >>= \p->sendMsg (fst (makeMsgs 0 (bc2 p))) ch)
83 ||- forever (enterChoice "Choose led to disable" [] [LED1, LED2, LED3]
84 >>= \p->sendMsg (fst (makeMsgs 0 (bc3 p))) ch)
85 ||- viewSharedInformation "channels" [ViewWith lens] ch
86 ||- viewSharedInformation "messages" [] messageShare
87 ||- viewSh sdsShares ch
88 >>* [OnAction ActionFinish (always shutDown)]
89 where
90 messageShare :: Shared [String]
91 messageShare = sharedStore "mTaskMessagesRecv" []
92
93 processMessages ch msgs sdss = forever (watch ch
94 >>* [OnValue (ifValue (not o isEmpty o fst3) (process ch))])
95 where
96 process :: (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> Task ()
97 process ch (r,_,_) = upd (appFst3 (const [])) ch >>| process` r
98 where
99 process` = foldr (\r t->updateSDSs sdss msgs r >>| t) (return ())
100
101 makeMsgs :: Int (Main (ByteCode () Stmt)) -> ([MTaskMSGSend], [(Int, Shared Int)])
102 makeMsgs timeout bc
103 # (msgs, st) = toMessages timeout (toRealByteCode (unMain bc))
104 = (msgs, map f st.sdss)
105 where
106 f (i,d) = (i, sharedStore ("mTaskSDS-" +++ toString i) (dd d))
107 dd [x,y] = toInt x*265 + toInt y
108
109 updateSDSs :: [(Int, Shared Int)] (Shared [String]) MTaskMSGRecv -> Task ()
110 updateSDSs [(id, sh):xs] m n=:(MTPub i d)
111 | id == i = set ((toInt d.[0])*265 + toInt d.[1]) sh @! ()
112 = updateSDSs xs m n
113 updateSDSs _ m mtm = case mtm of
114 MTMessage s = upd (\l->take 5 [s:l]) m @! ()
115 mta=:(MTTaskAdded _) = upd (\l->take 5 [toString mta:l]) m @! ()
116 _ = return ()
117
118 lens :: ([MTaskMSGRecv], [MTaskMSGSend],Bool) -> ([String], [String])
119 lens (r,s,_) = (map toString r, map toString s)
120
121 viewSh :: [(Int, Shared Int)] (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
122 viewSh [] ch = return ()
123 viewSh [(i, sh):xs] ch
124 # sharename = "SDS-" +++ toString i
125 = (
126 viewSharedInformation ("SDS-" +++ toString i) [] sh ||-
127 forever (
128 enterInformation sharename []
129 >>* [OnAction ActionOk
130 (ifValue (\j->j>=1 && j <= 3)
131 (\c->set c sh
132 >>= \_->sendMsg (toSDSUpdate i c) ch
133 @! ()
134 )
135 )]
136 )
137 ) ||- viewSh xs ch
138
139 sendMsg :: [MTaskMSGSend] (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
140 sendMsg m ch = upd (\(r,s,ss)->(r,s ++ m,True)) ch @! ()
141
142 syncSerialChannel :: String TTYSettings (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
143 syncSerialChannel dev opts rw = Task eval
144 where
145 eval event evalOpts tree=:(TCInit taskId ts) iworld=:{IWorld|world}
146 = case TTYopen dev opts world of
147 (False, _, world)
148 # (err, world) = TTYerror world
149 = (ExceptionResult (exception err), {iworld & world=world})
150 (True, tty, world)
151 # iworld = {iworld & world=world, resources=Just (TTYd tty)}
152 = case addBackgroundTask 42 (BackgroundTask (serialDeviceBackgroundTask rw)) iworld of
153 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
154 (Ok _, iworld) = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=True} NoRep (TCBasic taskId ts JSONNull False), iworld)
155
156 eval _ _ tree=:(TCBasic _ ts _ _) iworld
157 = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=False} NoRep tree, iworld)
158
159 eval event evalOpts tree=:(TCDestroy _) iworld=:{IWorld|resources,world}
160 # (TTYd tty) = fromJust resources
161 # (ok, world) = TTYclose tty world
162 # iworld = {iworld & world=world,resources=Nothing}
163 = case removeBackgroundTask 42 iworld of
164 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
165 (Ok _, iworld) = (DestroyedResult, iworld)
166
167 serialDeviceBackgroundTask :: (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) !*IWorld -> *IWorld
168 serialDeviceBackgroundTask rw iworld
169 = case read rw iworld of
170 (Error e, iworld) = abort "share couldn't be read"
171 (Ok (r,s,ss), iworld)
172 # (Just (TTYd tty)) = iworld.resources
173 # tty = writet (map encode s) tty
174 # (ml, tty) = case TTYavailable tty of
175 (False, tty) = ([], tty)
176 (_, tty)
177 # (l, tty) = TTYreadline tty
178 = ([decode l], tty)
179 # iworld = {iworld & resources=Just (TTYd tty)}
180 = case write (r++ml,[],False) rw iworld of
181 (Error e, iworld) = abort "share couldn't be written"
182 (Ok _, iworld) = case notify rw iworld of
183 (Error e, iworld) = abort "share couldn't be notified"
184 (Ok _, iworld) = iworld
185 where
186 writet :: [String] -> (*TTY -> *TTY)
187 writet [] = id
188 writet [x:xs] = writet xs o TTYwrite x
189
190
191 syncNetworkChannel :: String Int (Shared ([MTaskMSGRecv], [MTaskMSGSend], Bool)) -> Task ()
192 syncNetworkChannel server port channel
193 = tcpconnect server port channel {ConnectionHandlers|onConnect=onConnect,whileConnected=whileConnected,onDisconnect=onDisconnect} @! ()
194 where
195 onConnect :: String ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool), [String], Bool)
196 onConnect _ (msgs,send,sendStopped)
197 = (Ok "", Just (msgs,[],sendStopped), map encode send, False)
198
199 whileConnected :: (Maybe String) String ([MTaskMSGRecv], [MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool), [String], Bool)
200 whileConnected Nothing acc (msgs,send,sendStopped)
201 = (Ok acc, Nothing, [], False)
202 // = (Ok acc, Just (msgs,[],sendStopped), map encode send, False)
203
204 whileConnected (Just newData) acc (msgs,send,sendStopped)
205 | sendStopped = (Ok acc, Just (msgs ++ [decode newData],[],False), map encode send, False)
206 = (Ok acc, Just (msgs ++ [decode newData],[],False), [], False)
207
208 onDisconnect :: String ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool))
209 onDisconnect l (msgs,send,sendStopped) = (Ok l, Nothing)