3 import StdDebug, StdMisc
4 from StdFunc import flip
9 from Text import class Text(startsWith,concat,split,join), instance Text String
12 import System.Directory
14 import iTasks.UI.Definition
16 import iTasks._Framework.TaskState
17 import iTasks._Framework.TaskServer
18 import iTasks._Framework.IWorld
19 import iTasks._Framework.Store
23 derive class iTask Queue, TTYSettings, Parity, BaudRate, ByteSize
24 derive class iTask MTaskMSGRecv, MTaskMSGSend
26 :: *Resource | TTYd !*TTY
28 Start :: *World -> *World
29 Start world = startEngine (withShared ([], False, [], False) mTaskTask) world
30 //Start world = startEngine mTaskTask world
32 deviceSelectorNetwork :: Task (Int, String)
33 deviceSelectorNetwork = enterInformation "Port Number?" []
34 -&&- enterInformation "Network address" []
36 deviceSelectorSerial :: Task (String, TTYSettings)
37 deviceSelectorSerial = accWorld getDevices
38 >>= \dl->(enterChoice "Device" [] dl -&&- deviceSettings)
40 deviceSettings = updateInformation "Settings" [] zero
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)
47 isTTY s = not (isEmpty (filter (flip startsWith s) prefixes))
48 prefixes = ["ttyS", "ttyACM", "ttyUSB", "tty.usbserial"]
50 derive class iTask SerTCP
51 :: SerTCP = Serial | TCP
53 mTaskTask :: (Shared ([MTaskMSGRecv],Bool,[MTaskMSGSend],Bool)) -> Task ()
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
60 sendMsg msgs ch >>= \_->(
61 consumeNetworkStream (processSDSs sdsShares messageShare) ch ||-
62 viewSharedInformation "channels" [ViewWith lens] ch ||-
63 viewSharedInformation "messages" [] messageShare ||-
66 ) >>* [OnAction ActionFinish (always shutDown)]
68 messageShare :: Shared [String]
69 messageShare = sharedStore "mTaskMessagesRecv" []
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
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 @! ()
82 lens :: ([MTaskMSGRecv],Bool,[MTaskMSGSend],Bool) -> ([String], [String])
83 lens (r,_,s,_) = (f r, map toString s)
87 f [x:xs] = [toString x:f xs]
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
94 viewSharedInformation ("SDS-" +++ toString i) [] sh ||-
96 enterInformation sharename []
97 >>* [OnAction ActionOk
98 (ifValue (\j->j>=1 && j <= 3)
100 >>= \_->sendMsg (toSDSUpdate i c) ch
107 sdsShares = makeShares st
108 (msgs, st) = toMessages 1000 (toRealByteCode (unMain bc))
110 bc :: Main (ByteCode () Stmt)
111 bc = sds \x=1 In sds \pinnetje=1 In {main =
112 IF (digitalRead D3 ==. lit True) (
118 IF (pinnetje ==. lit 1) (
119 digitalWrite D0 (lit True) :.
120 digitalWrite D1 (lit False) :.
121 digitalWrite D2 (lit False)
123 IF (pinnetje ==. lit 2) (
124 digitalWrite D0 (lit False) :.
125 digitalWrite D1 (lit True) :.
126 digitalWrite D2 (lit False)
128 digitalWrite D0 (lit False) :.
129 digitalWrite D1 (lit False) :.
130 digitalWrite D2 (lit True)
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}]
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
145 // s i = "mTaskSDS-" +++ toString i
146 // dd [x,y] = (toInt x)*265+(toInt y)
149 sendMsg :: [MTaskMSGSend] (Shared ([MTaskMSGRecv],Bool,[MTaskMSGSend],Bool)) -> Task ()
150 sendMsg m ch = upd (\(r,rs,s,ss)->(r,rs,s ++ m,ss)) ch @! ()
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
155 eval event evalOpts tree=:(TCInit taskId ts) iworld=:{IWorld|world}
156 = case TTYopen dev opts world of
158 # (err, world) = TTYerror world
159 = (ExceptionResult (exception err), {iworld & world=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)
166 eval _ _ tree=:(TCBasic _ ts _ _) iworld
167 = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=False} NoRep tree, iworld)
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)
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)
187 # (l, tty) = TTYreadline 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
196 writet :: [String] !*TTY -> *TTY
198 writet [x:xs] t = writet xs (TTYwrite x t)
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} @! ()
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))
216 = (Ok acc,write,map encodeFun send,False)
218 onDisconnect l (received,receiveStopped,send,sendStopped)
219 = (Ok l,Just (received,True,send,sendStopped))
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) @! ()
225 ifProcess (received,receiveStopped,_,_)
226 = receiveStopped || (not (isEmpty received))
228 process (received,receiveStopped,_,_)
230 >>| if (isEmpty received) (return ()) (processTask received)
233 empty :: ([m],Bool,[n],Bool) -> ([m],Bool,[n],Bool)
234 empty (_,rs,s,ss) = ([],rs,s,ss)