Skip to content

Commit 90ce5f2

Browse files
committed
usb mouse: Reuse the report buffer.
Blocks until any existing report has been sent, to avoid losing any reports. Signed-off-by: Angus Gratton <angus@redyak.com.au>
1 parent 9d3da52 commit 90ce5f2

File tree

1 file changed

+14
-8
lines changed
  • micropython/usb/usb-device-mouse/usb/device

1 file changed

+14
-8
lines changed

micropython/usb/usb-device-mouse/usb/device/mouse.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# MIT license; Copyright (c) 2023-2024 Angus Gratton
44
from micropython import const
55
import struct
6+
import machine
67

78
from usb.device.hid import HIDInterface
89

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

2426
def send_report(self, dx=0, dy=0):
2527
b = 0
@@ -29,16 +31,20 @@ def send_report(self, dx=0, dy=0):
2931
b |= 1 << 1
3032
if self._m:
3133
b |= 1 << 2
32-
# Note: This allocates the bytes object 'report' each time a report is
33-
# sent.
34+
35+
# Wait for any pending report to be sent to the host
36+
# before updating contents of _buf.
3437
#
35-
# However, at the moment the HIDInterface class doesn't keep track of each
36-
# transfer after it's submitted. So reusing a bytearray() creates a risk
37-
# of a race condition if a new report transfer is submitted using the
38-
# same buffer, before the previous one has completed.
39-
report = struct.pack("Bbb", b, dx, dy)
38+
# This loop can be removed if you don't care about possibly missing a
39+
# transient report, the final report buffer contents will always be the
40+
# last one sent to the host (it just might lose one of the ones in the
41+
# middle).
42+
while self.busy():
43+
machine.idle()
44+
45+
struct.pack_into("Bbb", self._buf, 0, b, dx, dy)
4046

41-
return super().send_report(report)
47+
return super().send_report(self._buf)
4248

4349
def click_left(self, down=True):
4450
self._l = down

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy