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