fix(scale): 子设备断线时从聚合器移除数据,修复列表不消失的问题

- ScaleWebSocketClient 新增 onDeviceDisconnected 回调,在 onFailure/onClosed 时触发
- ScaleServiceManager 绑定回调,断线时调用 aggregator.removeDevice() 清除缓存
- 重连成功后数据重新推送,UI 列表自动恢复
This commit is contained in:
2026-04-16 13:52:11 +08:00
parent 7fd2f02b87
commit cba5bda757
2 changed files with 6 additions and 0 deletions
@@ -100,6 +100,7 @@ object ScaleServiceManager {
// WebSocket 客户端
val client = ScaleWebSocketClient().also {
it.onScaleData = { data -> aggregator?.onRemoteScaleData(data) }
it.onDeviceDisconnected = { remoteId -> aggregator?.removeDevice(remoteId) }
}
wsClient = client
@@ -49,6 +49,9 @@ class ScaleWebSocketClient {
/** 收到秤数据时的回调,在子线程调用 */
var onScaleData: ((data: ScaleData) -> Unit)? = null
/** 设备断线时的回调(连接失败或关闭),在子线程调用 */
var onDeviceDisconnected: ((deviceId: String) -> Unit)? = null
/**
* 连接到指定子设备
* @param deviceId 子设备 ID
@@ -85,12 +88,14 @@ class ScaleWebSocketClient {
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
Log.w(TAG, "连接子设备失败: $deviceId, ${t.message}")
connections.remove(deviceId)
onDeviceDisconnected?.invoke(deviceId)
scheduleReconnect(deviceId, host, port)
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
Log.d(TAG, "子设备连接已关闭: $deviceId, reason=$reason")
connections.remove(deviceId)
onDeviceDisconnected?.invoke(deviceId)
scheduleReconnect(deviceId, host, port)
}
})