3 import StdDebug, StdMisc
4 from StdFunc import flip
9 from Text import class Text(startsWith,concat,split,join), instance Text String
11 from Data.Func import $
14 import System.Directory
16 import iTasks.UI.Definition
18 import iTasks._Framework.TaskState
19 import iTasks._Framework.TaskServer
20 import iTasks._Framework.IWorld
21 import iTasks._Framework.Store
26 derive class iTask Queue, TTYSettings, Parity, BaudRate, ByteSize
27 derive class iTask MTaskMSGRecv, MTaskMSGSend, SerTCP, UserLED
29 :: *Resource | TTYd !*TTY
30 :: Channels :== ([MTaskMSGRecv], [MTaskMSGSend], Bool)
32 :: SerTCP = SerialDevice | TCPDevice
34 deviceConnected :: Maybe String,
38 Start :: *World -> *World
39 Start world = startEngine (mTaskManager
40 >>* [OnAction (Action "Shutdown") (always $ shutDown)]) world
42 bc :: Main (ByteCode () Stmt)
43 bc = sds \x=1 In sds \pinnetje=1 In {main =
50 IF (pinnetje ==. lit 1) (
53 IF (pinnetje ==. lit 2) (
60 bc2 :: UserLED -> Main (ByteCode () Stmt)
61 bc2 d = {main = ledOn d}
63 bc3 :: UserLED -> Main (ByteCode () Stmt)
64 bc3 d = {main = ledOff d}
66 :: MTaskDeviceStatus = {connected :: Bool, name :: String}
67 derive class iTask MTaskDeviceStatus, MTaskDevice
69 mTaskManager :: Task ()
70 mTaskManager = anyTask
72 , whileUnchanged deviceStore viewDevices
73 , addDevice deviceStore
74 , viewChannels deviceStore
75 ] <<@ ApplyLayout layout
76 // ||- whileUnchanged deviceStore (\m->if (isEmpty m)
77 // (viewInformation "No devices yet" [] "" @! ()) (connectDevice m)) @! ()
80 isValue (Value _ _) = True
83 viewmTasks = viewInformation "MTasks" [] ""
85 layout = sequenceLayouts
86 [ arrangeWithSideBar 0 LeftSide 260 True
87 , arrangeSplit Vertical True
88 , layoutSubs (SelectByPath [1, 0]) arrangeWithTabs
91 viewChannels :: (Shared [MTaskDevice]) -> Task ()
92 viewChannels sh = whileUnchanged sh (\d->if (isEmpty d)
93 (viewInformation "No channels yet" [] "")
94 (viewInformation "Channels available" [] "")) @! ()
96 viewDevices :: [MTaskDevice] -> [Task ()]
97 viewDevices [] = viewInformation "No devices yet" [] "" @! ()
98 viewDevices ds = [viewInformation "Device" [] d <<@ Title d.deviceName\\d<-ds]
100 addDevice :: (Shared [MTaskDevice]) -> Task ()
101 addDevice devices = enterInformation "Device type and name" []
102 >>= \(name, ty)->get randomInt
103 >>= \ident->treturn (name +++ toString ident)
104 >>= \realname->let ch = channels realname in case ty of
105 TCPDevice = enterInformation "Hostname and port" []
106 >>= \(host, port)->cont realname name ||- syncNetworkChannel host port ch
107 SerialDevice = accWorld getDevices
108 >>= \dl->(enterChoice "Device" [] dl -&&- updateInformation "Settings" [] zero)
109 >>= \(device, settings)->cont realname name ||- syncSerialChannel device settings ch
111 cont rn nm = (upd (\l->[dev rn nm:l]) devices >>| addDevice devices)
112 dev rn nm = {deviceConnected=Just rn,deviceName=nm}
114 channels :: String -> Shared Channels
115 channels s = sdsFocus s $ memoryStore "" $ Just ([], [], False)
117 getDevices :: !*World -> *(![String], !*World)
118 getDevices w = case readDirectory "/dev" w of
119 (Error (errcode, errmsg), w) = abort errmsg
120 (Ok entries, w) = (map ((+++) "/dev/") (filter isTTY entries), w)
122 isTTY s = not (isEmpty (filter (flip startsWith s) prefixes))
123 prefixes = ["ttyS", "ttyACM", "ttyUSB", "tty.usbserial"]
125 // connectDevice :: [MTaskDevice] -> Task ()
126 // connectDevice [] = treturn ()
127 // connectDevice [d:ds] = (case d.deviceConnected of
128 // (Just sh) = viewSharedInformation "Buffers" [] sh @! ()
129 // Nothing = viewInformation ("Connect " +++ d.deviceName) [] "" >>* [
130 // OnAction (Action "connect") (const $ Just $ connect d)]
131 // ) -|| connectDevice ds
133 deviceviewer :: [MTaskDevice] -> [MTaskDeviceStatus]
134 deviceviewer ds = [{MTaskDeviceStatus | name = d.deviceName,
135 connected = if (isNothing d.deviceConnected) False True}\\d<-ds]
137 deviceStore :: Shared [MTaskDevice]
138 deviceStore = sdsFocus "mTaskDevices" $ memoryStore "" (Just [])
140 // showTabbed :: [MTaskDevice] -> Task ()
141 // showTabbed [] = viewInformation "" [] "No devices yet" @! ()
142 // showTabbed [l:ls] = foldr (\e es->manageDevice e ||- es) (manageDevice l) ls
144 // manageDevice :: MTaskDevice -> Task ()
146 // either viewTCP viewSer md.deviceSettings
148 // (treturn () >>* [OnAction (Action "Connect") (always shutDown)] @! ())
149 // (\b->viewSharedInformation "Buffers" [] b @! ())
150 // md.deviceConnected
151 // <<@ ArrangeVertical
153 mapPar :: (a -> Task a) [a] -> Task ()
154 mapPar f l = foldr1 (\x y->f x ||- y) l <<@ ArrangeWithTabs @! ()
155 allAtOnce t = foldr1 (||-) t @! ()
156 //allAtOnce = (flip (@!) ()) o foldr1 (||-)
159 //mTaskTask :: Task ()
160 //mTaskTask = let (msgs, sdsShares) = makeMsgs 1000 bc in
163 // ||- processMessages ch messageShare sdsShares
164 // ||- forever (enterChoice "Choose led to enable" [] [LED1, LED2, LED3]
165 // >>= \p->sendMsg (fst (makeMsgs 0 (bc2 p))) ch)
166 // ||- forever (enterChoice "Choose led to disable" [] [LED1, LED2, LED3]
167 // >>= \p->sendMsg (fst (makeMsgs 0 (bc3 p))) ch)
168 // ||- viewSharedInformation "channels" [ViewAs lens] ch
169 // ||- viewSharedInformation "messages" [] messageShare
170 // ||- viewSh sdsShares ch
171 // >>* [OnAction ActionFinish (always shutDown)]
173 // messageShare :: Shared [String]
174 // messageShare = sharedStore "mTaskMessagesRecv" []
176 // processMessages ch msgs sdss = forever (watch ch
177 // >>* [OnValue (ifValue (not o isEmpty o fst3) (process ch))])
179 // process :: (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> Task ()
180 // process ch (r,_,_) = upd (appFst3 (const [])) ch >>| process` r
182 // process` = foldr (\r t->updateSDSs sdss msgs r >>| t) (return ())
184 // makeMsgs :: Int (Main (ByteCode () Stmt)) -> ([MTaskMSGSend], [(Int, Shared Int)])
185 // makeMsgs timeout bc
186 // # (msgs, st) = toMessages timeout (toRealByteCode (unMain bc))
187 // = (msgs, map f st.sdss)
189 // f (i,d) = (i, sharedStore ("mTaskSDS-" +++ toString i) (dd d))
190 // dd [x,y] = toInt x*265 + toInt y
192 // updateSDSs :: [(Int, Shared Int)] (Shared [String]) MTaskMSGRecv -> Task ()
193 // updateSDSs [(id, sh):xs] m n=:(MTPub i d)
194 // | id == i = set ((toInt d.[0])*265 + toInt d.[1]) sh @! ()
195 // = updateSDSs xs m n
196 // updateSDSs _ m mtm = case mtm of
197 // MTMessage s = upd (\l->take 5 [s:l]) m @! ()
198 // mta=:(MTTaskAck _) = upd (\l->take 5 [toString mta:l]) m @! ()
199 // //TODO other recv msgs
202 // lens :: ([MTaskMSGRecv], [MTaskMSGSend],Bool) -> ([String], [String])
203 // lens (r,s,_) = (map toString r, map toString s)
205 // viewSh :: [(Int, Shared Int)] (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
206 // viewSh [] ch = return ()
207 // viewSh [(i, sh):xs] ch
208 // # sharename = "SDS-" +++ toString i
210 // viewSharedInformation ("SDS-" +++ toString i) [] sh ||-
212 // enterInformation sharename []
213 // >>* [OnAction ActionOk
214 // (ifValue (\j->j>=1 && j <= 3)
216 // >>= \_->sendMsg (toSDSUpdate i c) ch
221 // ) ||- viewSh xs ch
223 sendMsg :: [MTaskMSGSend] (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
224 sendMsg m ch = upd (\(r,s,ss)->(r,s ++ m,True)) ch @! ()
226 syncSerialChannel :: String TTYSettings (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
227 syncSerialChannel dev opts rw = Task eval
229 eval event evalOpts tree=:(TCInit taskId ts) iworld=:{IWorld|world}
230 = case TTYopen dev opts world of
232 # (err, world) = TTYerror world
233 = (ExceptionResult (exception err), {iworld & world=world})
235 # iworld = {iworld & world=world, resources=Just (TTYd tty)}
236 = case addBackgroundTask 42 (BackgroundTask (serialDeviceBackgroundTask rw)) iworld of
237 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
238 (Ok _, iworld) = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=True} NoChange (TCBasic taskId ts JSONNull False), iworld)
240 eval _ _ tree=:(TCBasic _ ts _ _) iworld
241 = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=False} NoChange tree, iworld)
243 eval event evalOpts tree=:(TCDestroy _) iworld=:{IWorld|resources,world}
244 # (TTYd tty) = fromJust resources
245 # (ok, world) = TTYclose tty world
246 # iworld = {iworld & world=world,resources=Nothing}
247 = case removeBackgroundTask 42 iworld of
248 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
249 (Ok _, iworld) = (DestroyedResult, iworld)
251 serialDeviceBackgroundTask :: (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) !*IWorld -> (MaybeError TaskException (), *IWorld)
252 serialDeviceBackgroundTask rw iworld
253 = case read rw iworld of
254 (Error e, iworld) = (Error $ exception "share couldn't be read", iworld)
255 (Ok (r,s,ss), iworld)
256 # (Just (TTYd tty)) = iworld.resources
257 # tty = writet (map encode s) tty
258 # (ml, tty) = case TTYavailable tty of
259 (False, tty) = ([], tty)
261 # (l, tty) = TTYreadline tty
263 # iworld = {iworld & resources=Just (TTYd tty)}
264 = case write (r++ml,[],False) rw iworld of
265 (Error e, iworld) = (Error $ exception "share couldn't be written", iworld)
266 (Ok _, iworld) = case notify rw iworld of
267 (Error e, iworld) = (Error $ exception "share couldn't be notified", iworld)
268 (Ok _, iworld) = (Ok (), iworld)
270 writet :: [String] -> (*TTY -> *TTY)
272 writet [x:xs] = writet xs o TTYwrite x
275 syncNetworkChannel :: String Int (Shared ([MTaskMSGRecv], [MTaskMSGSend], Bool)) -> Task ()
276 syncNetworkChannel server port channel
277 = tcpconnect server port channel {ConnectionHandlers|onConnect=onConnect,whileConnected=whileConnected,onDisconnect=onDisconnect} @! ()
279 onConnect :: String ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool), [String], Bool)
280 onConnect _ (msgs,send,sendStopped)
281 = (Ok "", Just (msgs,[],sendStopped), map encode send, False)
283 whileConnected :: (Maybe String) String ([MTaskMSGRecv], [MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool), [String], Bool)
284 whileConnected Nothing acc (msgs,send,sendStopped)
285 = (Ok acc, Nothing, [], False)
287 whileConnected (Just newData) acc (msgs,send,sendStopped)
288 | sendStopped = (Ok acc, Just (msgs ++ [decode newData],[],False), map encode send, False)
289 = (Ok acc, Just (msgs ++ [decode newData],[],False), [], False)
291 onDisconnect :: String ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool))
292 onDisconnect l (msgs,send,sendStopped) = (Ok l, Nothing)