From 0095654649ed54341104eb5c2ad78dc391475f7f Mon Sep 17 00:00:00 2001 From: NoahCornell Date: Mon, 18 Aug 2025 10:20:44 -0500 Subject: [PATCH] sonos: Fix websocket reconnect task There is a race condition when a sonos connection calls close on itself. It immediately calls on_close which will spawn a task to reconnect. The reconnect task checks if the connection is running which depends on the socket being closed and cleaned up. Instead, call on_close after the socket has been closed and cleaned up. --- .../sonos/src/api/sonos_websocket_router.lua | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/drivers/SmartThings/sonos/src/api/sonos_websocket_router.lua b/drivers/SmartThings/sonos/src/api/sonos_websocket_router.lua index 73e04efb64..7e15855e89 100644 --- a/drivers/SmartThings/sonos/src/api/sonos_websocket_router.lua +++ b/drivers/SmartThings/sonos/src/api/sonos_websocket_router.lua @@ -44,6 +44,16 @@ cosock.spawn(function() if wss ~= nil then log.trace(string.format("Closing websocket for player %s", unique_key)) wss:close(CloseCode.normal(), "Shutdown requested by client") + local ws_id = wss.id + for _, uuid in ipairs((listener_ids_for_socket[ws_id] or {})) do + local listener = listeners[uuid] + + if listener ~= nil then + listener.on_close(uuid) + end + listeners[uuid] = nil + end + listener_ids_for_socket[ws_id] = nil end websockets[unique_key] = nil end @@ -292,17 +302,7 @@ function SonosWebSocketRouter.close_socket_for_player(target) local ws = websockets[target] if ws ~= nil then - local ws_id = ws.id table.insert(pending_close, target) - for _, uuid in ipairs((listener_ids_for_socket[ws_id] or {})) do - local listener = listeners[uuid] - - if listener ~= nil then - listener.on_close(uuid) - end - listeners[uuid] = nil - end - listener_ids_for_socket[ws_id] = nil return true else return nil, string.format("No currently open connection for %s", target)