Skip to content

Commit

Permalink
usb mouse: Reuse the report buffer.
Browse files Browse the repository at this point in the history
Blocks until any existing report has been sent, to avoid losing any
reports.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
  • Loading branch information
projectgus committed Apr 16, 2024
1 parent 9d3da52 commit 90ce5f2
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions micropython/usb/usb-device-mouse/usb/device/mouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# MIT license; Copyright (c) 2023-2024 Angus Gratton
from micropython import const
import struct
import machine

from usb.device.hid import HIDInterface

Expand All @@ -20,6 +21,7 @@ def __init__(self, interface_str="MicroPython Mouse"):
self._l = False # Left button
self._m = False # Middle button
self._r = False # Right button
self._buf = bytearray(3)

def send_report(self, dx=0, dy=0):
b = 0
Expand All @@ -29,16 +31,20 @@ def send_report(self, dx=0, dy=0):
b |= 1 << 1
if self._m:
b |= 1 << 2
# Note: This allocates the bytes object 'report' each time a report is
# sent.

# Wait for any pending report to be sent to the host
# before updating contents of _buf.
#
# However, at the moment the HIDInterface class doesn't keep track of each
# transfer after it's submitted. So reusing a bytearray() creates a risk
# of a race condition if a new report transfer is submitted using the
# same buffer, before the previous one has completed.
report = struct.pack("Bbb", b, dx, dy)
# This loop can be removed if you don't care about possibly missing a
# transient report, the final report buffer contents will always be the
# last one sent to the host (it just might lose one of the ones in the
# middle).
while self.busy():
machine.idle()

struct.pack_into("Bbb", self._buf, 0, b, dx, dy)

return super().send_report(report)
return super().send_report(self._buf)

def click_left(self, down=True):
self._l = down
Expand Down

0 comments on commit 90ce5f2

Please sign in to comment.