-
Notifications
You must be signed in to change notification settings - Fork 42
/
__init__.py
266 lines (216 loc) · 8.18 KB
/
__init__.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
import os
import ctypes
import atexit
import enum
__all__ = ['HIDException', 'DeviceInfo', 'Device', 'enumerate', 'BusType']
hidapi = None
library_paths = (
'libhidapi-hidraw.so',
'libhidapi-hidraw.so.0',
'libhidapi-libusb.so',
'libhidapi-libusb.so.0',
'libhidapi-iohidmanager.so',
'libhidapi-iohidmanager.so.0',
'libhidapi.dylib',
'hidapi.dll',
'libhidapi-0.dll'
)
for lib in library_paths:
try:
hidapi = ctypes.cdll.LoadLibrary(lib)
break
except OSError:
pass
else:
error = "Unable to load any of the following libraries:{}"\
.format(' '.join(library_paths))
raise ImportError(error)
hidapi.hid_init()
atexit.register(hidapi.hid_exit)
class HIDException(Exception):
pass
class APIVersion(ctypes.Structure):
_fields_ = [
('major', ctypes.c_int),
('minor', ctypes.c_int),
('patch', ctypes.c_int),
]
try:
hidapi.hid_version.argtypes = []
hidapi.hid_version.restype = ctypes.POINTER(APIVersion)
version = hidapi.hid_version()
version = (
version.contents.major,
version.contents.minor,
version.contents.patch,
)
except AttributeError:
#
# hid_version API was added in
# https://github.com/libusb/hidapi/commit/8f72236099290345928e646d2f2c48f0187ac4af
# so if it is missing we are dealing with hidapi 0.8.0 or older
#
version = (0, 8, 0)
if version >= (0, 13, 0):
bus_type = [
('bus_type', ctypes.c_int),
]
else:
bus_type = []
class BusType(enum.Enum):
UNKNOWN = 0x00
USB = 0x01
BLUETOOTH = 0x02
I2C = 0x03
SPI = 0x04
class DeviceInfo(ctypes.Structure):
def as_dict(self):
ret = {}
for name, type in self._fields_:
if name == 'next':
continue
ret[name] = getattr(self, name, None)
if name == 'bus_type':
ret[name] = BusType(ret[name])
return ret
DeviceInfo._fields_ = [
('path', ctypes.c_char_p),
('vendor_id', ctypes.c_ushort),
('product_id', ctypes.c_ushort),
('serial_number', ctypes.c_wchar_p),
('release_number', ctypes.c_ushort),
('manufacturer_string', ctypes.c_wchar_p),
('product_string', ctypes.c_wchar_p),
('usage_page', ctypes.c_ushort),
('usage', ctypes.c_ushort),
('interface_number', ctypes.c_int),
('next', ctypes.POINTER(DeviceInfo)),
] + bus_type
hidapi.hid_init.argtypes = []
hidapi.hid_init.restype = ctypes.c_int
hidapi.hid_exit.argtypes = []
hidapi.hid_exit.restype = ctypes.c_int
hidapi.hid_enumerate.argtypes = [ctypes.c_ushort, ctypes.c_ushort]
hidapi.hid_enumerate.restype = ctypes.POINTER(DeviceInfo)
hidapi.hid_free_enumeration.argtypes = [ctypes.POINTER(DeviceInfo)]
hidapi.hid_free_enumeration.restype = None
hidapi.hid_open.argtypes = [ctypes.c_ushort, ctypes.c_ushort, ctypes.c_wchar_p]
hidapi.hid_open.restype = ctypes.c_void_p
hidapi.hid_open_path.argtypes = [ctypes.c_char_p]
hidapi.hid_open_path.restype = ctypes.c_void_p
hidapi.hid_write.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
hidapi.hid_write.restype = ctypes.c_int
hidapi.hid_read_timeout.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_int]
hidapi.hid_read_timeout.restype = ctypes.c_int
hidapi.hid_read.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
hidapi.hid_read.restype = ctypes.c_int
hidapi.hid_get_input_report.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
hidapi.hid_get_input_report.restype = ctypes.c_int
hidapi.hid_set_nonblocking.argtypes = [ctypes.c_void_p, ctypes.c_int]
hidapi.hid_set_nonblocking.restype = ctypes.c_int
hidapi.hid_send_feature_report.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]
hidapi.hid_send_feature_report.restype = ctypes.c_int
hidapi.hid_get_feature_report.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
hidapi.hid_get_feature_report.restype = ctypes.c_int
hidapi.hid_close.argtypes = [ctypes.c_void_p]
hidapi.hid_close.restype = None
hidapi.hid_get_manufacturer_string.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_size_t]
hidapi.hid_get_manufacturer_string.restype = ctypes.c_int
hidapi.hid_get_product_string.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_size_t]
hidapi.hid_get_product_string.restype = ctypes.c_int
hidapi.hid_get_serial_number_string.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_size_t]
hidapi.hid_get_serial_number_string.restype = ctypes.c_int
hidapi.hid_get_indexed_string.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_wchar_p, ctypes.c_size_t]
hidapi.hid_get_indexed_string.restype = ctypes.c_int
hidapi.hid_error.argtypes = [ctypes.c_void_p]
hidapi.hid_error.restype = ctypes.c_wchar_p
def enumerate(vid=0, pid=0):
ret = []
info = hidapi.hid_enumerate(vid, pid)
c = info
while c:
ret.append(c.contents.as_dict())
c = c.contents.next
hidapi.hid_free_enumeration(info)
return ret
class Device(object):
def __init__(self, vid=None, pid=None, serial=None, path=None):
if path:
self.__dev = hidapi.hid_open_path(path)
elif serial:
serial = ctypes.create_unicode_buffer(serial)
self.__dev = hidapi.hid_open(vid, pid, serial)
elif vid and pid:
self.__dev = hidapi.hid_open(vid, pid, None)
else:
raise ValueError('specify vid/pid or path')
if not self.__dev:
raise HIDException('unable to open device')
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.close()
def __hidcall(self, function, *args, **kwargs):
if not self.__dev:
raise HIDException('device closed')
ret = function(*args, **kwargs)
if ret == -1:
err = hidapi.hid_error(self.__dev)
raise HIDException(err)
return ret
def __readstring(self, function, max_length=255):
buf = ctypes.create_unicode_buffer(max_length)
self.__hidcall(function, self.__dev, buf, max_length)
return buf.value
def write(self, data):
return self.__hidcall(hidapi.hid_write, self.__dev, data, len(data))
def read(self, size, timeout=None):
data = ctypes.create_string_buffer(size)
if timeout is None:
size = self.__hidcall(hidapi.hid_read, self.__dev, data, size)
else:
size = self.__hidcall(
hidapi.hid_read_timeout, self.__dev, data, size, timeout)
return data.raw[:size]
def get_input_report(self, report_id, size):
data = ctypes.create_string_buffer(size)
# Pass the id of the report to be read.
data[0] = bytearray((report_id,))
size = self.__hidcall(
hidapi.hid_get_input_report, self.__dev, data, size)
return data.raw[:size]
def send_feature_report(self, data):
return self.__hidcall(hidapi.hid_send_feature_report,
self.__dev, data, len(data))
def get_feature_report(self, report_id, size):
data = ctypes.create_string_buffer(size)
# Pass the id of the report to be read.
data[0] = bytearray((report_id,))
size = self.__hidcall(
hidapi.hid_get_feature_report, self.__dev, data, size)
return data.raw[:size]
def close(self):
if self.__dev:
hidapi.hid_close(self.__dev)
self.__dev = None
@property
def nonblocking(self):
return getattr(self, '_nonblocking', 0)
@nonblocking.setter
def nonblocking(self, value):
self.__hidcall(hidapi.hid_set_nonblocking, self.__dev, value)
setattr(self, '_nonblocking', value)
@property
def manufacturer(self):
return self.__readstring(hidapi.hid_get_manufacturer_string)
@property
def product(self):
return self.__readstring(hidapi.hid_get_product_string)
@property
def serial(self):
return self.__readstring(hidapi.hid_get_serial_number_string)
def get_indexed_string(self, index, max_length=255):
buf = ctypes.create_unicode_buffer(max_length)
self.__hidcall(hidapi.hid_get_indexed_string,
self.__dev, index, buf, max_length)
return buf.value