adapt to new iTasks layout
[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 from Data.Func import $
12 import Data.Tuple
13 import System.Directory
14
15 import iTasks.UI.Definition
16
17 import iTasks._Framework.TaskState
18 import iTasks._Framework.TaskServer
19 import iTasks._Framework.IWorld
20 import iTasks._Framework.Store
21
22 import TTY
23
24 derive class iTask Queue, TTYSettings, Parity, BaudRate, ByteSize
25 derive class iTask MTaskMSGRecv, MTaskMSGSend, SerTCP, UserLED
26
27 :: SerTCP = Serial | TCP
28 :: *Resource | TTYd !*TTY
29
30 Start :: *World -> *World
31 Start world = startEngine mTaskTask world
32 //Start world = startEngine mTaskTask world
33
34 bc :: Main (ByteCode () Stmt)
35 bc = sds \x=1 In sds \pinnetje=1 In {main =
36 IF (digitalRead D3) (
37 x =. x +. lit 1 :.
38 pub x
39 ) (
40 noOp
41 ) :.
42 IF (pinnetje ==. lit 1) (
43 ledOn LED1
44 ) (
45 IF (pinnetje ==. lit 2) (
46 ledOn LED2
47 ) (
48 ledOn LED3
49 )
50 )}
51
52 bc2 :: UserLED -> Main (ByteCode () Stmt)
53 bc2 d = {main = ledOn d}
54
55 bc3 :: UserLED -> Main (ByteCode () Stmt)
56 bc3 d = {main = ledOff d}
57
58
59 withDevice :: ((Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task a) -> Task a | iTask a
60 withDevice t = withShared ([], [], False) \ch->
61 enterInformation "Type" []
62 >>= \ty->case ty of
63 TCP = (enterInformation "Host" [] -&&- enterInformation "Port" [])
64 >>= \(port,host)->t ch -|| syncNetworkChannel host port ch
65 Serial = accWorld getDevices
66 >>= \dl->(enterChoice "Device" [] dl -&&- updateInformation "Settings" [] zero)
67 >>= \(dev,set)->t ch -|| syncSerialChannel dev set ch
68 where
69 getDevices :: !*World -> *(![String], !*World)
70 getDevices w = case readDirectory "/dev" w of
71 (Error (errcode, errmsg), w) = abort errmsg
72 (Ok entries, w) = (map ((+++) "/dev/") (filter isTTY entries), w)
73 where
74 isTTY s = not (isEmpty (filter (flip startsWith s) prefixes))
75 prefixes = ["ttyS", "ttyACM", "ttyUSB", "tty.usbserial"]
76
77 mTaskTask :: Task ()
78 mTaskTask = let (msgs, sdsShares) = makeMsgs 1000 bc in
79 withDevice \ch->
80 sendMsg msgs ch
81 ||- processMessages ch messageShare sdsShares
82 ||- forever (enterChoice "Choose led to enable" [] [LED1, LED2, LED3]
83 >>= \p->sendMsg (fst (makeMsgs 0 (bc2 p))) ch)
84 ||- forever (enterChoice "Choose led to disable" [] [LED1, LED2, LED3]
85 >>= \p->sendMsg (fst (makeMsgs 0 (bc3 p))) ch)
86 ||- viewSharedInformation "channels" [ViewAs lens] ch
87 ||- viewSharedInformation "messages" [] messageShare
88 ||- viewSh sdsShares ch
89 >>* [OnAction ActionFinish (always shutDown)]
90 where
91 messageShare :: Shared [String]
92 messageShare = sharedStore "mTaskMessagesRecv" []
93
94 processMessages ch msgs sdss = forever (watch ch
95 >>* [OnValue (ifValue (not o isEmpty o fst3) (process ch))])
96 where
97 process :: (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> Task ()
98 process ch (r,_,_) = upd (appFst3 (const [])) ch >>| process` r
99 where
100 process` = foldr (\r t->updateSDSs sdss msgs r >>| t) (return ())
101
102 makeMsgs :: Int (Main (ByteCode () Stmt)) -> ([MTaskMSGSend], [(Int, Shared Int)])
103 makeMsgs timeout bc
104 # (msgs, st) = toMessages timeout (toRealByteCode (unMain bc))
105 = (msgs, map f st.sdss)
106 where
107 f (i,d) = (i, sharedStore ("mTaskSDS-" +++ toString i) (dd d))
108 dd [x,y] = toInt x*265 + toInt y
109
110 updateSDSs :: [(Int, Shared Int)] (Shared [String]) MTaskMSGRecv -> Task ()
111 updateSDSs [(id, sh):xs] m n=:(MTPub i d)
112 | id == i = set ((toInt d.[0])*265 + toInt d.[1]) sh @! ()
113 = updateSDSs xs m n
114 updateSDSs _ m mtm = case mtm of
115 MTMessage s = upd (\l->take 5 [s:l]) m @! ()
116 mta=:(MTTaskAdded _) = upd (\l->take 5 [toString mta:l]) m @! ()
117 _ = return ()
118
119 lens :: ([MTaskMSGRecv], [MTaskMSGSend],Bool) -> ([String], [String])
120 lens (r,s,_) = (map toString r, map toString s)
121
122 viewSh :: [(Int, Shared Int)] (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
123 viewSh [] ch = return ()
124 viewSh [(i, sh):xs] ch
125 # sharename = "SDS-" +++ toString i
126 = (
127 viewSharedInformation ("SDS-" +++ toString i) [] sh ||-
128 forever (
129 enterInformation sharename []
130 >>* [OnAction ActionOk
131 (ifValue (\j->j>=1 && j <= 3)
132 (\c->set c sh
133 >>= \_->sendMsg (toSDSUpdate i c) ch
134 @! ()
135 )
136 )]
137 )
138 ) ||- viewSh xs ch
139
140 sendMsg :: [MTaskMSGSend] (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
141 sendMsg m ch = upd (\(r,s,ss)->(r,s ++ m,True)) ch @! ()
142
143 syncSerialChannel :: String TTYSettings (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) -> Task ()
144 syncSerialChannel dev opts rw = Task eval
145 where
146 eval event evalOpts tree=:(TCInit taskId ts) iworld=:{IWorld|world}
147 = case TTYopen dev opts world of
148 (False, _, world)
149 # (err, world) = TTYerror world
150 = (ExceptionResult (exception err), {iworld & world=world})
151 (True, tty, world)
152 # iworld = {iworld & world=world, resources=Just (TTYd tty)}
153 = case addBackgroundTask 42 (BackgroundTask (serialDeviceBackgroundTask rw)) iworld of
154 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
155 (Ok _, iworld) = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=True} NoChange (TCBasic taskId ts JSONNull False), iworld)
156
157 eval _ _ tree=:(TCBasic _ ts _ _) iworld
158 = (ValueResult NoValue {TaskEvalInfo|lastEvent=ts,removedTasks=[],refreshSensitive=False} NoChange tree, iworld)
159
160 eval event evalOpts tree=:(TCDestroy _) iworld=:{IWorld|resources,world}
161 # (TTYd tty) = fromJust resources
162 # (ok, world) = TTYclose tty world
163 # iworld = {iworld & world=world,resources=Nothing}
164 = case removeBackgroundTask 42 iworld of
165 (Error e, iworld) = (ExceptionResult (exception "h"), iworld)
166 (Ok _, iworld) = (DestroyedResult, iworld)
167
168 serialDeviceBackgroundTask :: (Shared ([MTaskMSGRecv],[MTaskMSGSend],Bool)) !*IWorld -> (MaybeError TaskException (), *IWorld)
169 serialDeviceBackgroundTask rw iworld
170 = case read rw iworld of
171 (Error e, iworld) = (Error $ exception "share couldn't be read", iworld)
172 (Ok (r,s,ss), iworld)
173 # (Just (TTYd tty)) = iworld.resources
174 # tty = writet (map encode s) tty
175 # (ml, tty) = case TTYavailable tty of
176 (False, tty) = ([], tty)
177 (_, tty)
178 # (l, tty) = TTYreadline tty
179 = ([decode l], tty)
180 # iworld = {iworld & resources=Just (TTYd tty)}
181 = case write (r++ml,[],False) rw iworld of
182 (Error e, iworld) = (Error $ exception "share couldn't be written", iworld)
183 (Ok _, iworld) = case notify rw iworld of
184 (Error e, iworld) = (Error $ exception "share couldn't be notified", iworld)
185 (Ok _, iworld) = (Ok (), iworld)
186 where
187 writet :: [String] -> (*TTY -> *TTY)
188 writet [] = id
189 writet [x:xs] = writet xs o TTYwrite x
190
191
192 syncNetworkChannel :: String Int (Shared ([MTaskMSGRecv], [MTaskMSGSend], Bool)) -> Task ()
193 syncNetworkChannel server port channel
194 = tcpconnect server port channel {ConnectionHandlers|onConnect=onConnect,whileConnected=whileConnected,onDisconnect=onDisconnect} @! ()
195 where
196 onConnect :: String ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool), [String], Bool)
197 onConnect _ (msgs,send,sendStopped)
198 = (Ok "", Just (msgs,[],sendStopped), map encode send, False)
199
200 whileConnected :: (Maybe String) String ([MTaskMSGRecv], [MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool), [String], Bool)
201 whileConnected Nothing acc (msgs,send,sendStopped)
202 = (Ok acc, Nothing, [], False)
203 // = (Ok acc, Just (msgs,[],sendStopped), map encode send, False)
204
205 whileConnected (Just newData) acc (msgs,send,sendStopped)
206 | sendStopped = (Ok acc, Just (msgs ++ [decode newData],[],False), map encode send, False)
207 = (Ok acc, Just (msgs ++ [decode newData],[],False), [], False)
208
209 onDisconnect :: String ([MTaskMSGRecv],[MTaskMSGSend],Bool) -> (MaybeErrorString String, Maybe ([MTaskMSGRecv],[MTaskMSGSend],Bool))
210 onDisconnect l (msgs,send,sendStopped) = (Ok l, Nothing)