update'
[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
25
26 :: *Resource | TTYd !*TTY
27
28 Start :: *World -> *World
29 Start world = startEngine (withShared ([], False, [], False) mTaskTask) world
30 //Start world = startEngine mTaskTask world
31 //
32 deviceSelectorNetwork :: Task (Int, String)
33 deviceSelectorNetwork = enterInformation "Port Number?" []
34 -&&- enterInformation "Network address" []
35
36 deviceSelectorSerial :: Task (String, TTYSettings)
37 deviceSelectorSerial = accWorld getDevices
38 >>= \dl->(enterChoice "Device" [] dl -&&- deviceSettings)
39 where
40 deviceSettings = updateInformation "Settings" [] zero
41
42 getDevices :: !*World -> *(![String], !*World)
43 getDevices w = case readDirectory "/dev" w of
44 (Error (errcode, errmsg), w) = abort errmsg
45 (Ok entries, w) = (map ((+++) "/dev/") (filter isTTY entries), w)
46 where
47 isTTY s = not (isEmpty (filter (flip startsWith s) prefixes))
48 prefixes = ["ttyS", "ttyACM", "ttyUSB", "tty.usbserial"]
49
50 derive class iTask SerTCP
51 :: SerTCP = Serial | TCP
52
53 mTaskTask :: (Shared ([MTaskMSGRecv],Bool,[MTaskMSGSend],Bool)) -> Task ()
54 mTaskTask ch =
55 (enterInformation "Choose" [] >>= \st->case st of
56 Serial = deviceSelectorSerial >>= \(s,set)->syncSerialChannel s set decode encode ch
57 TCP = deviceSelectorNetwork >>= \(p,h)->syncNetworkChannel h p "\n" decode encode ch
58 ) ||-
59 (
60 sendMsg msgs ch >>= \_->(
61 consumeNetworkStream (processSDSs sdsShares messageShare) ch ||-
62 viewSharedInformation "channels" [ViewWith lens] ch ||-
63 viewSharedInformation "messages" [] messageShare ||-
64 viewSh sdsShares ch
65 )
66 ) >>* [OnAction ActionFinish (always shutDown)]
67 where
68 messageShare :: Shared [String]
69 messageShare = sharedStore "mTaskMessagesRecv" []
70
71 processSDSs :: [(Int, Shared Int)] (Shared [String]) [MTaskMSGRecv] -> Task ()
72 processSDSs _ _ [] = return ()
73 processSDSs s y [x:xs] = updateSDSs s y x >>= \_->processSDSs s y xs
74
75 updateSDSs :: [(Int, Shared Int)] (Shared [String]) MTaskMSGRecv -> Task ()
76 updateSDSs _ m (MTMessage s) = upd (\l->take 20 [s:l]) m @! ()
77 updateSDSs _ _ MTEmpty = return ()
78 updateSDSs [(id, sh):xs] m n=:(MTPub i d)
79 | id == i = set ((toInt d.[0])*265 + toInt d.[1]) sh @! ()
80 = updateSDSs xs m n
81
82 lens :: ([MTaskMSGRecv],Bool,[MTaskMSGSend],Bool) -> ([String], [String])
83 lens (r,_,s,_) = (f r, map toString s)
84 where
85 f [] = []
86 f [MTEmpty:xs] = f xs
87 f [x:xs] = [toString x:f xs]
88
89 viewSh :: [(Int, Shared Int)] (Shared ([MTaskMSGRecv],Bool,[MTaskMSGSend],Bool)) -> Task ()
90 viewSh [] ch = return ()
91 viewSh [(i, sh):xs] ch
92 # sharename = "SDS-" +++ toString i
93 = (
94 viewSharedInformation ("SDS-" +++ toString i) [] sh ||-
95 forever (
96 enterInformation sharename []
97 >>* [OnAction ActionOk
98 (ifValue (\j->j>=1 && j <= 3)
99 (\c->set c sh
100 >>= \_->sendMsg (toSDSUpdate i c) ch
101 @! ()
102 )
103 )]
104 )
105 ) ||- viewSh xs ch
106
107 sdsShares = makeShares st
108 (msgs, st) = toMessages 1000 (toRealByteCode (unMain bc))
109
110 bc :: Main (ByteCode () Stmt)
111 bc = sds \x=1 In sds \pinnetje=1 In {main =
112 IF (digitalRead D3 ==. lit True) (
113 x =. x +. lit 1 :.
114 pub x
115 ) (
116 noOp
117 ) :.
118 IF (pinnetje ==. lit 1) (
119 digitalWrite D0 (lit True) :.
120 digitalWrite D1 (lit False) :.
121 digitalWrite D2 (lit False)
122 ) (
123 IF (pinnetje ==. lit 2) (
124 digitalWrite D0 (lit False) :.
125 digitalWrite D1 (lit True) :.
126 digitalWrite D2 (lit False)
127 ) (
128 digitalWrite D0 (lit False) :.
129 digitalWrite D1 (lit False) :.
130 digitalWrite D2 (lit True)
131 )
132 )}
133
134 makeShares :: BCState -> [(Int, Shared Int)]
135 makeShares {sdss=[]} = []
136 makeShares s=:{sdss=[(i,d):xs]} =
137 [(i, sharedStore ("mTaskSDS-" +++ toString i) 1):makeShares {s & sdss=xs}]
138
139 //makeBytecode :: Int (Main (ByteCode () Stmt)) -> ([MTaskMSGSend], [(Int, Shared Int)])
140 //makeBytecode timeout bc
141 //# (msgs, st) = toMessages timeout (toRealByteCode (unMain bc))
142 //# shares = map (\(i,d)->(i, sharedStore (s i) (dd d))) st.sdss
143 //= (msgs, shares)
144 // where
145 // s i = "mTaskSDS-" +++ toString i
146 // dd [x,y] = (toInt x)*265+(toInt y)
147
148
149 sendMsg :: [MTaskMSGSend] (Shared ([MTaskMSGRecv],Bool,[MTaskMSGSend],Bool)) -> Task ()
150 sendMsg m ch = upd (\(r,rs,s,ss)->(r,rs,s ++ m,ss)) ch @! ()
151
152 syncSerialChannel :: String TTYSettings (String -> m) (n -> String) (Shared ([m],Bool,[n],Bool)) -> Task () | iTask m & iTask n
153 syncSerialChannel dev opts decodeFun encodeFun rw = Task eval
154 where
155 eval event evalOpts tree=:(TCInit taskId ts) iworld=:{IWorld|world}
156 = case TTYopen dev opts world of
157 (False, _, world)
158 # (err, world) = TTYerror world
159 = (ExceptionResult (exception err), {iworld & world=world})
160 (True, tty, world)
161 # iworld = {iworld & world=world, resources=Just (TTYd tty)}
162 = case addBackgroundTask 42 (BackgroundTask (serialDeviceBackgroundTask rw decodeFun encodeFun)) iworld of
163 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
164 (Ok _, iworld) = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=True} NoRep (TCBasic taskId ts JSONNull False), iworld)
165
166 eval _ _ tree=:(TCBasic _ ts _ _) iworld
167 = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=False} NoRep tree, iworld)
168
169 eval event evalOpts tree=:(TCDestroy _) iworld=:{IWorld|resources,world}
170 # (TTYd tty) = fromJust resources
171 # (ok, world) = TTYclose tty world
172 # iworld = {iworld & world=world,resources=Nothing}
173 = case removeBackgroundTask 42 iworld of
174 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
175 (Ok _, iworld) = (DestroyedResult, iworld)
176
177 serialDeviceBackgroundTask :: (Shared ([m],Bool,[n],Bool)) (String -> m) (n -> String) !*IWorld -> *IWorld
178 serialDeviceBackgroundTask rw de en iworld
179 = case read rw iworld of
180 (Error e, iworld) = abort "share couldn't be read"
181 (Ok (r,rs,s,ss), iworld)
182 # (Just (TTYd tty)) = iworld.resources
183 # tty = writet (map en s) tty
184 # (ml, tty) = case TTYavailable tty of
185 (False, tty) = ([], tty)
186 (_, tty)
187 # (l, tty) = TTYreadline tty
188 = ([de l], tty)
189 # iworld = {iworld & resources=Just (TTYd tty)}
190 = case write (r++ml,rs,[],ss) rw iworld of
191 (Error e, iworld) = abort "share couldn't be written"
192 (Ok _, iworld) = case notify rw iworld of
193 (Error e, iworld) = abort "share couldn't be notified"
194 (Ok _, iworld) = iworld
195 where
196 writet :: [String] !*TTY -> *TTY
197 writet [] t = t
198 writet [x:xs] t = writet xs (TTYwrite x t)
199
200
201 syncNetworkChannel :: String Int String (String -> m) (n -> String) (Shared ([m],Bool,[n],Bool)) -> Task () | iTask m & iTask n
202 syncNetworkChannel server port msgSeparator decodeFun encodeFun channel
203 = tcpconnect server port channel {ConnectionHandlers|onConnect=onConnect,whileConnected=whileConnected,onDisconnect=onDisconnect} @! ()
204 where
205 onConnect _ (received,receiveStopped,send,sendStopped)
206 = (Ok "",if (not (isEmpty send)) (Just (received,False,[],sendStopped)) Nothing, map encodeFun send,False)
207 whileConnected Nothing acc (received,receiveStopped,send,sendStopped)
208 | not (trace_tn "whilec nothing") = undef
209 = (Ok acc, Nothing, [], False)
210 whileConnected (Just newData) acc (received,receiveStopped,send,sendStopped)
211 | not (trace_tn "whilec just") = undef
212 # [acc:msgs] = reverse (split msgSeparator (concat [acc,newData]))
213 # write = if (not (isEmpty msgs && isEmpty send))
214 (Just (received ++ map decodeFun (reverse msgs),receiveStopped,[],sendStopped))
215 Nothing
216 = (Ok acc,write,map encodeFun send,False)
217
218 onDisconnect l (received,receiveStopped,send,sendStopped)
219 = (Ok l,Just (received,True,send,sendStopped))
220
221 consumeNetworkStream :: ([m] -> Task ()) (Shared ([m],Bool,[n],Bool)) -> Task () | iTask m & iTask n
222 consumeNetworkStream processTask channel
223 = ((watch channel >>* [OnValue (ifValue ifProcess process)]) <! id) @! ()
224 where
225 ifProcess (received,receiveStopped,_,_)
226 = receiveStopped || (not (isEmpty received))
227
228 process (received,receiveStopped,_,_)
229 = upd empty channel
230 >>| if (isEmpty received) (return ()) (processTask received)
231 @! receiveStopped
232
233 empty :: ([m],Bool,[n],Bool) -> ([m],Bool,[n],Bool)
234 empty (_,rs,s,ss) = ([],rs,s,ss)