-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArduinoUsb.py
More file actions
69 lines (50 loc) · 2.31 KB
/
ArduinoUsb.py
File metadata and controls
69 lines (50 loc) · 2.31 KB
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
'''
Цей шмат кода був взяти з сайту stackoverflow.com
'''
import usb
def getStringDescriptor(device, index):
response = device.ctrl_transfer(usb.util.ENDPOINT_IN,
usb.legacy.REQ_GET_DESCRIPTOR,
(usb.util.DESC_TYPE_STRING << 8) | index,
0, # language id
255) # length
return response[2:].tostring().decode('utf-16')
REQUEST_TYPE_SEND = usb.util.build_request_type(usb.util.CTRL_OUT,
usb.util.CTRL_TYPE_CLASS,
usb.util.CTRL_RECIPIENT_DEVICE)
REQUEST_TYPE_RECEIVE = usb.util.build_request_type(usb.util.CTRL_IN,
usb.util.CTRL_TYPE_CLASS,
usb.util.CTRL_RECIPIENT_DEVICE)
USBRQ_HID_GET_REPORT = 0x01
USBRQ_HID_SET_REPORT = 0x09
USB_HID_REPORT_TYPE_FEATURE = 0x03
class ArduinoUsbDevice(object):
def __init__(self, idVendor, idProduct):
self.idVendor = idVendor
self.idProduct = idProduct
self.device = usb.core.find(idVendor=self.idVendor,
idProduct=self.idProduct)
if not self.device:
raise Exception("Device not found")
def write(self, byte):
self._transfer(REQUEST_TYPE_SEND, USBRQ_HID_SET_REPORT,
byte,
[]) # ignored
def read(self):
response = self._transfer(REQUEST_TYPE_RECEIVE, USBRQ_HID_GET_REPORT,
0, # ignored
1) # length
if not response:
raise Exception("No Data")
return response[0]
def _transfer(self, request_type, request, index, value):
return self.device.ctrl_transfer(request_type, request,
(USB_HID_REPORT_TYPE_FEATURE << 8) | 0,
index,
value)
@property
def productName(self):
return getStringDescriptor(self.device, self.device.iProduct)
@property
def manufacturer(self):
return getStringDescriptor(self.device, self.device.iManufacturer)