Skip to content

Commit

Permalink
Optimize get_report_descriptor
Browse files Browse the repository at this point in the history
- use HID_API_MAX_REPORT_DESCRIPTOR_SIZE from hidapi.h
- avoid dynamic memory allocation (use stack variable)
- replace list.append with direct list creation from memory view
  • Loading branch information
Ihor Dutchak authored and prusnak committed Nov 21, 2024
1 parent 373809e commit 8494ab2
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 20 deletions.
2 changes: 2 additions & 0 deletions chid.pxd
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from libc.stddef cimport wchar_t, size_t

cdef extern from "<hidapi.h>":
const int HID_API_MAX_REPORT_DESCRIPTOR_SIZE

ctypedef struct hid_device:
pass

Expand Down
28 changes: 8 additions & 20 deletions hid.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -330,12 +330,8 @@ cdef class device:
result = hid_send_feature_report(c_hid, cbuff, c_buff_len)
return result

def get_report_descriptor(self, int max_length=4096):
"""Return the report descriptor up to max_length bytes.
If max_length is bigger than the actual descriptor, the full descriptor will be returned.
:param max_length: Maximum number of bytes to read, must be positive
:type max_length: int
def get_report_descriptor(self):
"""Return the HID Report Descriptor for this device.
:return:
:rtype: List[int]
Expand All @@ -345,22 +341,14 @@ cdef class device:
if self._c_hid == NULL:
raise ValueError('not open')

cdef unsigned char* cbuff
cdef size_t c_descriptor_length = max(1, max_length)
cdef unsigned char cbuff[HID_API_MAX_REPORT_DESCRIPTOR_SIZE]
cdef hid_device * c_hid = self._c_hid
cdef int n
result = []
try:
cbuff = <unsigned char *>malloc(max_length)
with nogil:
n = hid_get_report_descriptor(c_hid, cbuff, c_descriptor_length)
if n < 0:
raise IOError('read error')
for i in range(n):
result.append(cbuff[i])
finally:
free(cbuff)
return result
with nogil:
n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff))
if n < 0:
raise IOError('read error')
return list(cbuff[:n])

def get_feature_report(self, int report_num, int max_length):
"""Receive feature report.
Expand Down

0 comments on commit 8494ab2

Please sign in to comment.