forked from n6il/pyDriveWire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dwio.py
341 lines (292 loc) · 9.31 KB
/
dwio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# !/usr/local/bin/python
import threading
import Queue
# from collections import deque
from time import sleep
class QPC:
def __init__(self, init=0):
self.counter = init
self.lock = threading.Lock()
def add(self, i):
self.lock.acquire()
self.counter += i
r = self.counter
self.lock.release()
return r
def sub(self, i):
self.lock.acquire()
if i > self.counter:
self.counter = 0
else:
self.counter -= i
r = self.counter
self.lock.release()
return r
def get(self):
self.lock.acquire()
r = self.counter
self.lock.release()
return r
def close(self):
self.lock.acquire()
self.counter = -1
r = self.counter
self.lock.release()
return r
class DWIO:
def __init__(self, rwf=None, inf=None, outf=None, threaded=False, debug=False):
self.abort = False
if rwf:
inf = outf = rwf
self.inf = inf
self.outf = outf
self.threaded = threaded
if self.threaded:
self.rt = threading.Thread(target=self._readHandler, args=())
self.rt.daemon = True
else:
self.rt = None
self.rq = Queue.Queue()
self.rb = QPC()
self.rbuf = ''
if self.threaded:
self.wt = threading.Thread(target=self._writeHandler, args=())
self.wt.daemon = True
else:
self.wt = None
self.wq = Queue.Queue()
self.connected = False
self.debug = debug
def _print(self, msg):
if self.debug:
print(msg)
def run(self, read=True, write=True):
if not self.threaded:
return
self._print("%s: Starting threads..." % self)
self.rt.start()
self.wt.start()
def isConnected(self):
return self.connected
def outWaiting(self):
return self._outWaiting()
def _outWaiting(self):
if self.rt and self.rt._Thread__stopped and self.rq.empty():
self.rb.close()
n = min(214, self.rb.get())
# print "outWaiting",n
return n
def readline(self, ifs='\n'):
return self.read(readLine=True, ifs=ifs)
def read(self, rlen=None, timeout=None, readLine=False, ifs='\n'):
rdata = ''
pos = -1
_t = timeout
if not _t:
_t = 1
if self.threaded and not self.abort and self.rt and not self.rt.is_alive(
) and not self.rt._Thread__stopped:
# Start the background reader thread only
# when someone asks to start reading from it
self.rt.start()
if self.rt and self.rt._Thread__stopped and self.rq.empty():
self.rb.close()
while not self.rq.empty() or not self.abort:
d = ''
if self.rbuf:
d = self.rbuf
self.rbuf = ''
else:
try:
d = self.rq.get(True, _t)
except Exception as e:
if timeout:
print str(e)
return ''
pass
available = len(d)
required = available
# print rlen, len(rdata), available, len(self.rbuf)
if not available:
# print "waiting2"
continue
if rlen:
required = min(rlen - len(rdata), available)
if readLine:
pos = d.find(ifs)
if pos >= 0:
required = pos + 1
rdata += d[:required]
if (required < available):
self.rbuf = d[required:]
if readLine:
if pos >= 0:
break
else:
continue
if not rlen and self.rq.empty():
break
if len(rdata) == rlen:
break
# print "reading: %d (%s)" %(len(rdata),rdata if ord(rdata)>32 and ord(rdata)<128 else '.')
if self.rt and self.rt._Thread__stopped:
self.rb.close()
self.rb.sub(len(rdata))
return rdata
def write(self, data):
# print "write"
if self.abort:
print "w: abort"
return 0
if self.threaded and not self.abort and self.wt and not self.wt.is_alive(
) and not self.wt._Thread__stopped:
# Start the background reader thread only
# when someone asks to start reading from it
self.wt.start()
if self.wt and self.wt._Thread__stopped:
return 0
self.wq.put(data)
return len(data)
def _close(self):
pass
def close(self):
self._print("%s: Closing connection" % self)
self.abort = True
self.rb.close()
self._close()
# if self.wt and self.wt.is_alive() and not self.wt._Thread__stopped:
if self.rt:
self.rt.abort = True
self._print("%s: Shutting down async read thread: %s" % (self, self.rt))
if self.rt.is_alive():
self.rt.join()
self.rt = None
# if self.wt and self.wt.is_alive() and not self.wt._Thread__stopped:
if self.wt:
self._print("%s: Shutting down async write thread: %s" % (self, self.wt))
self.wt.abort = True
if self.wt.is_alive():
self.wt.join()
self.wt = None
def cleanup(self):
self._cleanup()
def _cleanup(self):
pass
def _readHandler(self):
self._print("%s: Starting _readHandler..." % self)
while not self.abort:
try:
d = self._read()
except Exception as e:
print(str(e))
break
if d:
# print "put: (%s)" % d
self.rb.add(len(d))
self.rq.put(d)
self._print("%s: Exiting _readHandler..." % self)
def _read(self, rlen=None):
data = ''
ri = []
try:
(ri, _, _) = select.select([inf.fileno()], [], [], 1)
except BaseException:
raise
if any(ri):
data = self.inf.read(rlen)
return data
def _writeHandler(self):
self._print("%s: Starting _writeHandler..." % self)
while not self.abort:
d = ''
try:
d = self.wq.get(True, 1)
except Exception as e:
pass
# print str(e)
if d:
# "wh: %d" % len(d)
self._write(d)
self._print("%s: Exiting _writeHandler..." % self)
def _write(self, data):
# print "dwio._write %s" % self
return self.outf.write(data)
class DWIO2:
def __init__(self, rwf=None, inf=None, outf=None, blocking=False):
self.Abort = False
self.rqueue = deque()
if rwf:
inf = outf = rwf
self.inf = inf
self.outf = outf
self.blocking = blocking
if not self.blocking:
self.rt = threading.Thread(target=self._readHandler, args=())
self.rt.daemon = True
def write(self, data):
# print "write %d" % len(data)
return self._write(data)
def readline(self, ifs='\n'):
return self.read(readLine=True, ifs=ifs)
def read(self, rlen=None, readLine=False, ifs='\n'):
rdata = ''
pos = -1
# print "dwio read %d" % rlen
if not self.blocking and not self.rt.is_alive():
# Start the background reader thread only
# when someone asks to start reading from it
self.rt.start()
while True:
if self.blocking:
self.rqueue.appendleft(self._read(rlen))
if len(self.rqueue):
d = self.rqueue.pop()
available = len(d)
required = available
if rlen:
required = min(rlen - len(rdata), available)
if readLine:
pos = d.find(ifs)
if pos >= 0:
required = pos + 1
rdata += d[:required]
if (required < available):
self.rqueue.append(d[required:])
if readLine:
if pos >= 0:
break
else:
continue
if not rlen and not len(self.rqueue):
break
if len(rdata) == rlen:
break
return rdata
def close(self):
self.Abort = True
self.rt.join()
def _readHandler(self):
while True and not self.Abort:
d = self._read()
if d:
self.rqueue.appendleft(d)
def _read(self, rlen=None):
return self.inf.read(rlen)
def _write(self, data):
return self.outf.write(data)
class DWIOStdIo(DWIO):
def __init__(self):
DWIO.__init__(self, blocking=True)
def _read(self, count=None):
return raw_input() + '\n'
def _write(self, data):
sys.stdout.write(data)
if __name__ == '__main__':
import sys
# f=open("fifo")
# dw=DWIO(f)
dw = DWIOStdIo()
while True:
dw.write("> ")
dw.write(dw.readline())
# vim: ts=4 sw=4 sts=4 expandtab