SDL: Fixed duplicate controllers showing up on the Steam Controller wireless dongle

From f0b61c69e7fa5f48b2aa20482fa21d0343596028 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Thu, 14 Nov 2024 14:19:16 -0800
Subject: [PATCH] Fixed duplicate controllers showing up on the Steam
 Controller wireless dongle

---
 src/joystick/hidapi/SDL_hidapi_steam.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/src/joystick/hidapi/SDL_hidapi_steam.c b/src/joystick/hidapi/SDL_hidapi_steam.c
index 3db0d7510ad5f..f14b5d229099e 100644
--- a/src/joystick/hidapi/SDL_hidapi_steam.c
+++ b/src/joystick/hidapi/SDL_hidapi_steam.c
@@ -967,6 +967,7 @@ static bool UpdateSteamControllerState(const uint8_t *pData, int nDataSize, Stea
 
 typedef struct
 {
+    bool connected;
     bool report_sensors;
     uint32_t update_rate_in_us;
     Uint64 sensor_timestamp;
@@ -1028,10 +1029,11 @@ static bool HIDAPI_DriverSteam_InitDevice(SDL_HIDAPI_Device *device)
             return SDL_SetError("Failed to send ID_DONGLE_GET_WIRELESS_STATE request");
         }
 
-        // We will enumerate any attached controllers in UpdateDevices()
+        // We will enumerate any attached controllers in UpdateDevice()
         return true;
     } else {
         // Wired and BLE controllers are always connected if HIDAPI can see them
+        ctx->connected = true;
         return HIDAPI_JoystickConnected(device, NULL);
     }
 }
@@ -1242,22 +1244,24 @@ static bool HIDAPI_DriverSteam_UpdateDevice(SDL_HIDAPI_Device *device)
             }
 
             ctx->m_last_state = ctx->m_state;
-        } else if (joystick && D0G_IS_WIRELESS_DISCONNECT(pPacket, nPacketLength)) {
+        } else if (ctx->connected && D0G_IS_WIRELESS_DISCONNECT(pPacket, nPacketLength)) {
             // Controller has disconnected from the wireless dongle
             HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
             joystick = NULL;
-        } else if (!joystick && D0G_IS_WIRELESS_CONNECT(pPacket, nPacketLength)) {
+            ctx->connected = false;
+        } else if (!ctx->connected && D0G_IS_WIRELESS_CONNECT(pPacket, nPacketLength)) {
             // Controller has connected to the wireless dongle
             if (!HIDAPI_JoystickConnected(device, NULL)) {
                 return false;
             }
 
             joystick = SDL_GetJoystickFromID(device->joysticks[0]);
+            ctx->connected = true;
         }
 
         if (r <= 0) {
             // Failed to read from controller
-            if (joystick) {
+            if (ctx->connected) {
                 HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
             }
             return false;