-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpytuyo.py
286 lines (233 loc) · 8.62 KB
/
pytuyo.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
#!/usr/bin/python3
# FIXME : need to handle when device is disconnected, including the ability to
# reset an interface if / when the device is reconnected
import time
import logging as _logging
from collections import deque as _deque
import usb as _usb
_log = _logging.getLogger(__name__)
CMD_TERMINATOR = b'\r'
MSG_TERMINATOR = b'\r'
READ_TIMEOUT_MS = 10
MAX_RXQUEUE_LEN=1024
DATA_MSG='0'
DEVICE_INFO_MSG='1'
STATUS_MSG='9'
class Pytuyo(object):
_USB_CTRL_REQ_WAIT_TIME_S = .5
_UNIT_SCALES = {'mm':(lambda x:x), 'um':(lambda x:round(x*1000))}
_UNITS = 'mm'
@classmethod
def set_unit_scale(cls, scale='um'):
cls._UNITS = scale
def __init__(self, usb_dev):
self._usb_dev = usb_dev
self._epin = None
self._rxqueue = _deque(maxlen=MAX_RXQUEUE_LEN)
self._last_data = None
self.data_cb = None
self.device_info = None
self.device_info_cb = None
self.status_cb = None
self._request_wait_timeout = None
self.setup()
def setup(self):
d = self._usb_dev
if d.is_kernel_driver_active(0):
d.detach_kernel_driver(0)
d.reset()
d.set_configuration(1)
c = d.get_active_configuration()
self._epin = d.get_active_configuration().interfaces()[0].endpoints()[0]
bmRequestType=0x40 # Vendor Host-to-Device
bRequest=0x01
wValue=0xA5A5
wIndex=0
d.ctrl_transfer(bmRequestType, bRequest, wValue, wIndex)
bmRequestType=0xC0 # Vendor Device-to-Host
bRequest=0x02
wValue=0
wIndex=0
length=1
res1 = d.ctrl_transfer(bmRequestType, bRequest, wValue, wIndex, length)
_log.debug("Device Vendor resp: {}".format(res1))
def send_cmd(self, cmd, timeout=1):
end_time = time.time() + timeout
while self._request_wait_timeout is not None:
if time.time() > end_time:
_log.warning("Cannot send mitutuyo cmd - still waiting response")
return
time.sleep(0.1)
try:
self.check_resp()
except Exception as e:
_log.error("Exception checking mituyou response")
_log.error(str(e))
if not isinstance(cmd, bytes):
try:
cmd = cmd.encode()
except Exception as e:
raise Exception('Command bust be either bytes or str')
if cmd[-1] != CMD_TERMINATOR:
cmd+=CMD_TERMINATOR
bmRequestType=0x40 # Vendor Host-to-Device
bRequest=0x03
try:
self._usb_dev.ctrl_transfer(bmRequestType, bRequest, 0, 0, cmd)
except _usb.USBError as e:
_log.error(str(e))
else:
self._request_wait_timeout = time.time() + Pytuyo._USB_CTRL_REQ_WAIT_TIME_S
def request_read(self, timeout=1):
self.send_cmd('1', timeout=timeout)
def request_device_info(self, timeout=1):
self.send_cmd('V', timeout=timeout)
def get_reading(self, timeout=1):
self._last_data = None
self.request_read()
time_end = timeout + time.time()
while self._last_data is None:
if time.time() > time_end:
_log.error("pytuyo timeout waiting for reading")
return None
self.check_resp()
time.sleep(0.05)
return self._last_data
def get_device_info(self, timeout=1):
if self.device_info is not None:
return self.device_info
self.request_device_info()
time_end = timeout + time.time()
while self.device_info is None:
if time.time() > time_end:
_log.error("Timeout error waiting for reading")
return None
self.check_resp()
time.sleep(0.05)
return self.device_info
def _process_data_resp(self, response):
MIN_DATA_LEN=4
if len(response) < MIN_DATA_LEN:
_log.error("Invalid data measurement resp '{}'".format(response))
return
#ignore first two characters - always "1A"
measure_str = response[2:]
try:
val = float(measure_str)
except ValueError as e:
_log.error("Unable to parse measurement '{}' to float".format(measure_str))
return
_log.debug("Received measure data value: {}".format(val))
measure = self._UNIT_SCALES[self._UNITS](val)
self._last_data = measure
if self.data_cb:
self.data_cb(measure)
def _process_device_info_resp(self, response):
_log.debug("Received device info msg : {}".format(response))
self.device_info = response
if self.device_info_cb:
self.device_info_cb(response)
def _process_status_resp(self, response):
_log.debug("Received device status msg : {}".format(response))
if self.status_cb:
self.status_cb(response)
def _rx(self):
if self._epin is None:
raise Exception("Device not setup correctly for reading - no interrupt IN endpoint")
try:
max_rx = self._epin.wMaxPacketSize
resp = self._epin.read(max_rx, READ_TIMEOUT_MS)
except _usb.USBError as e:
if e.errno == 110:
_log.debug("USB timeout waiting for response")
return
elif e.errno == 19:
_log.debug("USB no-device error / disconnected")
return
else:
raise
except _usb.core.USBError as e:
if e.errno == 110:
_log.debug("USB timeout waiting for response")
return
elif e.errno == 19:
_log.debug("USB no-device error / disconnected")
return
else:
raise
if not resp or len(resp) == 0:
return
self._rxqueue.extend(resp)
def check_resp(self):
try:
self._rx()
except Exception as e:
_log.error("Exception checking mituyou response")
_log.error(str(e))
return
if len(self._rxqueue) == 0:
eor_idx = -1
else:
rxdata = bytes(self._rxqueue)
eor_idx = rxdata.find(MSG_TERMINATOR)
if eor_idx == -1:
""" message terminator not received yet"""
if self._request_wait_timeout is not None and time.time() > self._request_wait_timeout:
_log.error("Timeout error waiting for a response")
self._request_wait_timeout = None
return
resp = rxdata[:eor_idx]
self._rxqueue.clear()
if len(rxdata) >= eor_idx:
""" add back any data that will not be processed"""
remainder = resp[eor_idx+1:]
self._rxqueue.extend(remainder)
self._request_wait_timeout = None
resp = resp.decode()
msg_c = resp[0]
if msg_c == DATA_MSG:
self._process_data_resp(resp[1:])
elif msg_c == DEVICE_INFO_MSG:
self._process_device_info_resp(resp[1:])
elif msg_c == STATUS_MSG:
self._process_status_resp(resp[1:])
else:
_log.error("Ignoring unexpected device resp {}".format(resp))
return resp
if __name__ == '__main__':
import sys
import time
import argparse
def make_parser():
""" create the argument parser """
parser = argparse.ArgumentParser(description="Interact with Mitutoyo USB-ITN with pyusb")
parser.add_argument('-i', '--request-device-info', type=bool, default=True,
help='request device info')
parser.add_argument('-n', '--read-count', type=int, default=1,
help='Read count. -1 for inf')
parser.add_argument('-t', '--read-interval', type=float, default=1,
help='Read interval in seconds')
return parser
_logging.basicConfig(level=_logging.INFO)
parser = make_parser()
args = parser.parse_args()
d = _usb.core.find(idVendor=0x0fe7, idProduct=0x4001)
if d is None:
print("Could not find USB-ITN (idVendor=0x0fe7, idProduct=0x4001)")
sys.exit(1)
p = Pytuyo(d)
p.data_cb = lambda v: print("M:{}".format(v))
p.device_info_cb = lambda v: print("Device Info: {}".format(v))
p.status_cb = lambda v: print("Device Status: {}".format(v))
if args.request_device_info:
p.request_device_info()
p.check_resp()
n = args.read_count
while True:
p.request_read()
while not p.check_resp():
pass
n = n - 1
if n == 0:
sys.exit(0)
time.sleep(args.read_interval)