SDL: Fixed detecting Bluetooth disconnection on Nintendo Switch controllers

From 8aa6922fecc5657d97abb944d127282aaf99d3ef Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Tue, 9 Aug 2022 13:25:52 -0700
Subject: [PATCH] Fixed detecting Bluetooth disconnection on Nintendo Switch
 controllers

---
 src/joystick/hidapi/SDL_hidapi_switch.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/src/joystick/hidapi/SDL_hidapi_switch.c b/src/joystick/hidapi/SDL_hidapi_switch.c
index 99e3c3755a6..29c7dfb3ee9 100644
--- a/src/joystick/hidapi/SDL_hidapi_switch.c
+++ b/src/joystick/hidapi/SDL_hidapi_switch.c
@@ -2034,16 +2034,15 @@ HIDAPI_DriverSwitch_UpdateDevice(SDL_HIDAPI_Device *device)
             switch (ctx->m_rgucReadBuffer[0]) {
             case k_eSwitchInputReportIDs_SimpleControllerState:
                 HandleSimpleControllerState(joystick, ctx, (SwitchSimpleStatePacket_t *)&ctx->m_rgucReadBuffer[1]);
-                ctx->m_unLastInput = now;
                 break;
             case k_eSwitchInputReportIDs_FullControllerState:
                 HandleFullControllerState(joystick, ctx, (SwitchStatePacket_t *)&ctx->m_rgucReadBuffer[1]);
-                ctx->m_unLastInput = now;
                 break;
             default:
                 break;
             }
         }
+        ctx->m_unLastInput = now;
     }
 
     if (!ctx->m_bInputOnly && !ctx->m_bUsingBluetooth &&
@@ -2053,6 +2052,12 @@ HIDAPI_DriverSwitch_UpdateDevice(SDL_HIDAPI_Device *device)
             /* Steam may have put the controller back into non-reporting mode */
             WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_ForceUSB, NULL, 0, SDL_FALSE);
         }
+    } else if (ctx->m_bUsingBluetooth) {
+        const Uint32 INPUT_WAIT_TIMEOUT_MS = 1000;
+        if (SDL_TICKS_PASSED(now, ctx->m_unLastInput + INPUT_WAIT_TIMEOUT_MS)) {
+            /* Bluetooth may have disconnected, try reopening the controller */
+            size = -1;
+        }
     }
 
     if (ctx->m_bRumblePending || ctx->m_bRumbleZeroPending) {