738f8c2a11e559f4e7b88e324b2e5830d0b751aa
[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 qualified Data.Map as DM
12
13 from Data.Func import $
14 import Data.Tuple
15 import Data.List
16 import System.Directory
17
18 import iTasks.UI.Definition
19
20 import iTasks._Framework.TaskState
21 import iTasks._Framework.TaskServer
22 import iTasks._Framework.IWorld
23 import iTasks._Framework.Store
24
25
26 import TTY
27
28 derive class iTask Queue, TTYSettings, Parity, BaudRate, ByteSize
29 derive class iTask MTaskMSGRecv, MTaskMSGSend, SerTCP, UserLED
30
31 :: *Resource | TTYd !*TTY
32 :: Channels :== ([MTaskMSGRecv], [MTaskMSGSend], Bool)
33
34 :: SerTCP = SerialDevice | TCPDevice
35 :: MTaskDevice = {
36 deviceConnected :: Maybe String,
37 deviceName :: String,
38 deviceTasks :: [(String, Int)]
39 }
40 :: MTaskShare = {
41 identifier :: Int,
42 realShare :: String
43 }
44
45 Start :: *World -> *World
46 Start world = startEngine (mTaskManager
47 >>* [OnAction (Action "Shutdown") (always $ shutDown)]) world
48
49 memoryShare :: String a -> Shared a | iTask a
50 memoryShare s d = sdsFocus s $ memoryStore "" $ Just d
51
52 deviceStore :: Shared [MTaskDevice]
53 deviceStore = memoryShare "mTaskDevices" []
54
55 sdsStore :: Shared [MTaskShare]
56 sdsStore = memoryShare "mTaskShares" []
57
58 bcStateStore :: Shared BCState
59 bcStateStore = memoryShare "mTaskBCState" zero
60
61 mTaskTaskStore :: Shared [String]
62 mTaskTaskStore = memoryShare "mTaskTasks" ["ledder", "ledon", "ledoff"]
63
64 bc :: Main (ByteCode () Stmt)
65 bc = sds \x=1 In sds \pinnetje=1 In {main =
66 IF (digitalRead D3) (
67 x =. x +. lit 1 :.
68 pub x
69 ) (
70 noOp
71 ) :.
72 IF (pinnetje ==. lit 1) (
73 ledOn LED1
74 ) (
75 IF (pinnetje ==. lit 2) (
76 ledOn LED2
77 ) (
78 ledOn LED3
79 )
80 )}
81
82 bc2 :: UserLED -> Main (ByteCode () Stmt)
83 bc2 d = {main = ledOn d}
84
85 bc3 :: UserLED -> Main (ByteCode () Stmt)
86 bc3 d = {main = ledOff d}
87
88 :: MTaskDeviceStatus = {connected :: Bool, name :: String, tasks :: [(String, Int)]}
89 derive class iTask MTaskDeviceStatus, MTaskDevice, MTaskShare, BCState
90
91 mTaskManager :: Task ()
92 mTaskManager = anyTask
93 [ viewmTasks @! ()
94 , viewShares
95 , whileUnchanged deviceStore viewDevices
96 ] <<@ ApplyLayout layout
97 where
98 isValue (Value _ _) = True
99 isValue _ = False
100
101 viewmTasks = listmTasks
102 >&^ \sh->whileUnchanged sh $ \mi->case mi of
103 Nothing = viewInformation "No task selected" [] ()
104 Just mTaskTask = get deviceStore
105 >>= \devices->case devices of
106 [] = viewInformation "No devices yet" [] ()
107 ds = sendmTask mTaskTask ds @! ()
108 where
109 listmTasks :: Task String
110 listmTasks = enterChoiceWithShared "Available mTasks" [ChooseFromList id] mTaskTaskStore
111
112 sendmTask mTaskId ds = enterChoice "Choose Device" [ChooseFromDropdown (\t->t.deviceName)] ds <<@ Title mTaskId
113 >>* [OnAction (Action "Send") (withValue $ sendToDevice mTaskId)]
114
115 sendToDevice mTask device = Just $ viewInformation "" [] device
116
117
118
119 layout = sequenceLayouts
120 [ arrangeWithSideBar 0 LeftSide 260 True
121 , arrangeSplit Vertical True
122 ]
123
124 viewShares :: Task ()
125 viewShares = forever $
126 enterChoiceWithShared "Shares" [ChooseFromList sdsvw] sdsShare
127 >>* [OnValue $ withValue $ Just o updateShare]
128 >>* [OnAction (Action "Back") (const $ Just $ treturn ())]
129 where
130 sdsvw (k, v) = concat ["SDS ", toString k, ": ", toString v]
131 updateShare (k, v) = (viewInformation "Key" [] k
132 ||- updateInformation "Value" [] v)
133
134
135 viewDevices :: [MTaskDevice] -> Task ()
136 viewDevices ds = anyTask [
137 addDevice deviceStore <<@ Title "Add new device" @! ():
138 [viewDevice d <<@ Title d.deviceName\\d<-ds]]
139 <<@ ArrangeWithTabs @! ()
140
141 viewDevice :: MTaskDevice -> Task ()
142 viewDevice d = (viewInformation "Device settings" [] d
143 ||- (case d.deviceConnected of
144 Just s = viewSharedInformation "Channels" [] (channels d.deviceName) @! ()
145 Nothing = viewInformation "No channels yet" [] "" @! ()
146 )) <<@ ArrangeHorizontal
147
148 channels :: String -> Shared Channels
149 channels s = sdsFocus s $ memoryStore "" $ Just ([], [], False)
150
151 sdsShare :: Shared [(Int, Int)]
152 sdsShare = sdsFocus "mTaskSDSs" $ memoryStore "" $ Just [(1, 1)]
153
154 addDevice :: (Shared [MTaskDevice]) -> Task ()
155 addDevice devices = enterInformation "Device type and name" []
156 >>= \(name, ty)->get randomInt @ ((+++) name o toString)
157 >>= \realname->let ch = channels realname in case ty of
158 TCPDevice = enterInformation "Hostname and port" []
159 >>= \(host, port)->cont realname name ||- syncNetworkChannel host port ch
160 SerialDevice = accWorld getDevices
161 >>= \dl->(enterChoice "Device" [] dl -&&- updateInformation "Settings" [] zero)
162 >>= \(device, settings)->cont realname name ||- syncSerialChannel device settings ch
163 where
164 cont rn nm = (upd (\l->[dev rn nm:l]) devices >>| addDevice devices)
165 dev rn nm = {deviceConnected=Just rn,deviceName=nm,deviceTasks=[]}
166
167 getDevices :: !*World -> *(![String], !*World)
168 getDevices w = case readDirectory "/dev" w of
169 (Error (errcode, errmsg), w) = abort errmsg
170 (Ok entries, w) = (map ((+++) "/dev/") (filter isTTY entries), w)
171
172 isTTY s = not (isEmpty (filter (flip startsWith s) prefixes))
173 prefixes = ["ttyS", "ttyACM", "ttyUSB", "tty.usbserial"]
174
175 // connectDevice :: [MTaskDevice] -> Task ()
176 // connectDevice [] = treturn ()
177 // connectDevice [d:ds] = (case d.deviceConnected of
178 // (Just sh) = viewSharedInformation "Buffers" [] sh @! ()
179 // Nothing = viewInformation ("Connect " +++ d.deviceName) [] "" >>* [
180 // OnAction (Action "connect") (const $ Just $ connect d)]
181 // ) -|| connectDevice ds
182
183 deviceviewer :: [MTaskDevice] -> [MTaskDeviceStatus]
184 deviceviewer ds = [{MTaskDeviceStatus | name = d.deviceName,
185 connected = if (isNothing d.deviceConnected) False True,
186 tasks = d.deviceTasks}\\d<-ds]
187
188 // showTabbed :: [MTaskDevice] -> Task ()
189 // showTabbed [] = viewInformation "" [] "No devices yet" @! ()
190 // showTabbed [l:ls] = foldr (\e es->manageDevice e ||- es) (manageDevice l) ls
191 //
192 // manageDevice :: MTaskDevice -> Task ()
193 // manageDevice md =
194 // either viewTCP viewSer md.deviceSettings
195 // ||- maybe
196 // (treturn () >>* [OnAction (Action "Connect") (always shutDown)] @! ())
197 // (\b->viewSharedInformation "Buffers" [] b @! ())
198 // md.deviceConnected
199 // <<@ ArrangeVertical
200
201 mapPar :: (a -> Task a) [a] -> Task ()
202 mapPar f l = foldr1 (\x y->f x ||- y) l <<@ ArrangeWithTabs @! ()
203 allAtOnce t = foldr1 (||-) t @! ()
204 //allAtOnce = (flip (@!) ()) o foldr1 (||-)
205
206
207 //mTaskTask :: Task ()
208 //mTaskTask = let (msgs, sdsShares) = makeMsgs 1000 bc in
209 // withDevice \ch->
210 // sendMsg msgs ch
211 // ||- processMessages ch messageShare sdsShares
212 // ||- forever (enterChoice "Choose led to enable" [] [LED1, LED2, LED3]
213 // >>= \p->sendMsg (fst (makeMsgs 0 (bc2 p))) ch)
214 // ||- forever (enterChoice "Choose led to disable" [] [LED1, LED2, LED3]
215 // >>= \p->sendMsg (fst (makeMsgs 0 (bc3 p))) ch)
216 // ||- viewSharedInformation "channels" [ViewAs lens] ch
217 // ||- viewSharedInformation "messages" [] messageShare
218 // ||- viewSh sdsShares ch
219 // >>* [OnAction ActionFinish (always shutDown)]
220 // where
221 // messageShare :: Shared [String]
222 // messageShare = sharedStore "mTaskMessagesRecv" []
223 //
224 // processMessages ch msgs sdss = forever (watch ch
225 // >>* [OnValue (ifValue (not o isEmpty o fst3) (process ch))])
226 // where
227 // process :: (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> Task ()
228 // process ch (r,_,_) = upd (appFst3 (const [])) ch >>| process` r
229 // where
230 // process` = foldr (\r t->updateSDSs sdss msgs r >>| t) (return ())
231 //
232 // makeMsgs :: Int (Main (ByteCode () Stmt)) -> ([MTaskMSGSend], [(Int, Shared Int)])
233 // makeMsgs timeout bc
234 // # (msgs, st) = toMessages timeout (toRealByteCode (unMain bc))
235 // = (msgs, map f st.sdss)
236 // where
237 // f (i,d) = (i, sharedStore ("mTaskSDS-" +++ toString i) (dd d))
238 // dd [x,y] = toInt x*265 + toInt y
239 //
240 // updateSDSs :: [(Int, Shared Int)] (Shared [String]) MTaskMSGRecv -> Task ()
241 // updateSDSs [(id, sh):xs] m n=:(MTPub i d)
242 // | id == i = set ((toInt d.[0])*265 + toInt d.[1]) sh @! ()
243 // = updateSDSs xs m n
244 // updateSDSs _ m mtm = case mtm of
245 // MTMessage s = upd (\l->take 5 [s:l]) m @! ()
246 // mta=:(MTTaskAck _) = upd (\l->take 5 [toString mta:l]) m @! ()
247 // //TODO other recv msgs
248 // _ = return ()
249 //
250 // lens :: ([MTaskMSGRecv], [MTaskMSGSend],Bool) -> ([String], [String])
251 // lens (r,s,_) = (map toString r, map toString s)
252 //
253 // viewSh :: [(Int, Shared Int)] (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
254 // viewSh [] ch = return ()
255 // viewSh [(i, sh):xs] ch
256 // # sharename = "SDS-" +++ toString i
257 // = (
258 // viewSharedInformation ("SDS-" +++ toString i) [] sh ||-
259 // forever (
260 // enterInformation sharename []
261 // >>* [OnAction ActionOk
262 // (ifValue (\j->j>=1 && j <= 3)
263 // (\c->set c sh
264 // >>= \_->sendMsg (toSDSUpdate i c) ch
265 // @! ()
266 // )
267 // )]
268 // )
269 // ) ||- viewSh xs ch
270
271 sendMsg :: [MTaskMSGSend] (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
272 sendMsg m ch = upd (\(r,s,ss)->(r,s ++ m,True)) ch @! ()
273
274 syncSerialChannel :: String TTYSettings (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
275 syncSerialChannel dev opts rw = Task eval
276 where
277 eval event evalOpts tree=:(TCInit taskId ts) iworld=:{IWorld|world}
278 = case TTYopen dev opts world of
279 (False, _, world)
280 # (err, world) = TTYerror world
281 = (ExceptionResult (exception err), {iworld & world=world})
282 (True, tty, world)
283 # iworld = {iworld & world=world, resources=Just (TTYd tty)}
284 = case addBackgroundTask 42 (BackgroundTask (serialDeviceBackgroundTask rw)) iworld of
285 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
286 (Ok _, iworld) = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=True} NoChange (TCBasic taskId ts JSONNull False), iworld)
287
288 eval _ _ tree=:(TCBasic _ ts _ _) iworld
289 = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=False} NoChange tree, iworld)
290
291 eval event evalOpts tree=:(TCDestroy _) iworld=:{IWorld|resources,world}
292 # (TTYd tty) = fromJust resources
293 # (ok, world) = TTYclose tty world
294 # iworld = {iworld & world=world,resources=Nothing}
295 = case removeBackgroundTask 42 iworld of
296 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
297 (Ok _, iworld) = (DestroyedResult, iworld)
298
299 serialDeviceBackgroundTask :: (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) !*IWorld -> (MaybeError TaskException (), *IWorld)
300 serialDeviceBackgroundTask rw iworld
301 = case read rw iworld of
302 (Error e, iworld) = (Error $ exception "share couldn't be read", iworld)
303 (Ok (r,s,ss), iworld)
304 # (Just (TTYd tty)) = iworld.resources
305 # tty = writet (map encode s) tty
306 # (ml, tty) = case TTYavailable tty of
307 (False, tty) = ([], tty)
308 (_, tty)
309 # (l, tty) = TTYreadline tty
310 = ([decode l], tty)
311 # iworld = {iworld & resources=Just (TTYd tty)}
312 = case write (r++ml,[],False) rw iworld of
313 (Error e, iworld) = (Error $ exception "share couldn't be written", iworld)
314 (Ok _, iworld) = case notify rw iworld of
315 (Error e, iworld) = (Error $ exception "share couldn't be notified", iworld)
316 (Ok _, iworld) = (Ok (), iworld)
317 where
318 writet :: [String] -> (*TTY -> *TTY)
319 writet [] = id
320 writet [x:xs] = writet xs o TTYwrite x
321
322
323 syncNetworkChannel :: String Int (Shared ([MTaskMSGRecv], [MTaskMSGSend], Bool)) -> Task ()
324 syncNetworkChannel server port channel
325 = tcpconnect server port channel {ConnectionHandlers|onConnect=onConnect,whileConnected=whileConnected,onDisconnect=onDisconnect} @! ()
326 where
327 onConnect :: String ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool), [String], Bool)
328 onConnect _ (msgs,send,sendStopped)
329 = (Ok "", Just (msgs,[],sendStopped), map encode send, False)
330
331 whileConnected :: (Maybe String) String ([MTaskMSGRecv], [MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool), [String], Bool)
332 whileConnected Nothing acc (msgs,send,sendStopped)
333 = (Ok acc, Nothing, [], False)
334
335 whileConnected (Just newData) acc (msgs,send,sendStopped)
336 | sendStopped = (Ok acc, Just (msgs ++ [decode newData],[],False), map encode send, False)
337 = (Ok acc, Just (msgs ++ [decode newData],[],False), [], False)
338
339 onDisconnect :: String ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool))
340 onDisconnect l (msgs,send,sendStopped) = (Ok l, Nothing)