Skip to content

Commit c1e05b7

Browse files
committed
Add user-defined USB receive callback
Allows the user to respond to received USB packet data immediately after it has been parsed by the library.
1 parent 3fc8959 commit c1e05b7

3 files changed

Lines changed: 20 additions & 0 deletions

File tree

keywords.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ getRumbleRight KEYWORD2
4747

4848
getLEDPatternID KEYWORD2
4949

50+
setReceiveCallback KEYWORD2
51+
5052
# USB I/O
5153
connected KEYWORD2
5254
send KEYWORD2

src/XInput.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,10 @@ uint8_t XInputGamepad::getLEDPatternID() const {
317317
return (uint8_t)ledPattern;
318318
}
319319

320+
void XInputGamepad::setReceiveCallback(RecvCallbackType cback) {
321+
recvCallback = cback;
322+
}
323+
320324
boolean XInputGamepad::connected() {
321325
#ifdef USB_XINPUT
322326
return XInputUSB::connected();
@@ -359,6 +363,12 @@ size_t XInputGamepad::receive() {
359363
else if (PacketType == (uint8_t) XInputReceiveType::LEDs) {
360364
parseLED(rx[2]);
361365
}
366+
367+
// User-defined receive callback
368+
if (recvCallback != nullptr) {
369+
recvCallback(PacketType);
370+
}
371+
362372
return bytesRecv;
363373
#else
364374
return 0;
@@ -446,6 +456,9 @@ void XInputGamepad::reset() {
446456
// Reset rescale ranges
447457
setTriggerRange(XInputMap_Trigger::range.min, XInputMap_Trigger::range.max);
448458
setJoystickRange(XInputMap_Joystick::range.min, XInputMap_Joystick::range.max);
459+
460+
// Clear user-set receive callback
461+
recvCallback = nullptr;
449462
}
450463

451464
void XInputGamepad::printDebug(Print &output) const {

src/XInput.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,10 @@ class XInputGamepad {
108108
uint8_t getLEDPatternID() const; // Returns LED pattern ID #
109109
XInputLEDPattern getLEDPattern() const; // Returns LED pattern type
110110

111+
// Received Data Callback
112+
using RecvCallbackType = void(*)(uint8_t packetType);
113+
void setReceiveCallback(RecvCallbackType);
114+
111115
// USB IO
112116
boolean connected();
113117
size_t send();
@@ -131,6 +135,7 @@ class XInputGamepad {
131135
uint8_t tx[20]; // USB transmit data
132136
boolean newData; // Flag for tx data changed
133137

138+
RecvCallbackType recvCallback;
134139
uint8_t player; // Gamepad player #, buffered
135140
uint8_t rumble[2]; // Rumble motor data in, buffered
136141
XInputLEDPattern ledPattern; // LED pattern data in, buffered

0 commit comments

Comments
 (0)