1012 lines
37 KiB
C#
Raw Normal View History

using System.Collections;
using System.Collections.Generic;
using Kill.Managers;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Threading.Tasks;
using Kill.Network;
using Kill.UI.Components;
using Kill.Bluetooth;
using Kill.Bluetooth.Protocol;
using Kill.Core;
namespace Kill.UI.Pages
{
public class HomePageCtrl : MonoBehaviour
{
public static HomePageCtrl Instance { get; private set; }
public GameObject noDevicePage;
public GameObject normalPage;
// 存储待执行的UI更新操作
private List<Action> pendingUIUpdates = new List<Action>();
public Button selectDeviceButton;
public GameObject selectDevicePage;
// 设备列表数据 (使用 Kill.Managers.DeviceInfo)
public List<Kill.Managers.DeviceInfo> OwnedDevices { get; private set; } = new List<Kill.Managers.DeviceInfo>();
public List<Kill.Managers.DeviceInfo> SharedDevices { get; private set; } = new List<Kill.Managers.DeviceInfo>();
public Kill.Managers.DeviceInfo selectedDevice;
bool hasBluetooth = false;
bool hasWifi = false;
// UI 组件引用
public HomePageDeviceState deviceState;
public HomePageDeviceCtrl deviceCtrl;
public HomePageSchedule deviceSchedule;
public Button scheduleSettingButton;
public GameObject scheduleSettingPrefab;
// 状态初始化相关
private bool isDeviceStateInitializing = false; // 是否正在初始化设备状态
private int pendingStatusCount = 0; // 待接收的状态数量
2026-05-18 08:42:33 +08:00
private int TOTAL_STATUS_COUNT = 6; // 总共需要查询的状态数量
private float statusQueryTimeout = 15f; // 状态查询超时时间(秒)
private Coroutine statusQueryTimeoutCoroutine; // 超时协程
// 串行查询相关
private Queue<Action> statusQueryQueue = new Queue<Action>(); // 状态查询队列
private bool isQueryingStatus = false; // 是否正在查询状态
// 工作模式设置后查询相关
private bool isWaitingForWorkModeQuery = false; // 是否正在等待工作模式查询响应
void Awake()
{
Instance = this;
}
async Task Start()
{
// 订阅蓝牙事件
SubscribeBluetoothEvents();
// 获取设备列表
await FetchDeviceList();
Init();
}
void OnDestroy()
{
UnsubscribeBluetoothEvents();
}
#region
private void SubscribeBluetoothEvents()
{
if (BluetoothManager.Instance != null)
{
BluetoothManager.Instance.OnConnectedSuccess += OnBluetoothConnected;
BluetoothManager.Instance.OnDisconnected += OnBluetoothDisconnected;
BluetoothManager.Instance.OnError += OnBluetoothError;
}
if (BLECommunicationManager.Instance != null)
{
// 订阅用户登录结果事件
BLECommunicationManager.Instance.OnUserLoginResult += OnUserLoginResult;
// 订阅设备状态事件
BLECommunicationManager.Instance.OnWorkModeSettingReceived += OnWorkModeReceived;
2026-05-18 08:42:33 +08:00
BLECommunicationManager.Instance.OnDeviceLockControlReceived+=OnLockReceived;
BLECommunicationManager.Instance.OnScheduleTaskListReceived += OnScheduleTaskListReceived;
BLECommunicationManager.Instance.OnAngleControlReceived += OnAngleControlReceived;
BLECommunicationManager.Instance.OnDistanceControlReceived += OnDistanceControlReceived;
BLECommunicationManager.Instance.OnFillLightControlReceived += OnFillLightControlReceived;
//BLECommunicationManager.Instance.OnMillimeterWaveSettingReceived += OnMillimeterWaveReceived;
BLECommunicationManager.Instance.OnVisualDetectionSettingReceived += OnVisualDetectionReceived;
}
}
private void UnsubscribeBluetoothEvents()
{
if (BluetoothManager.Instance != null)
{
BluetoothManager.Instance.OnConnectedSuccess -= OnBluetoothConnected;
BluetoothManager.Instance.OnDisconnected -= OnBluetoothDisconnected;
BluetoothManager.Instance.OnError -= OnBluetoothError;
}
if (BLECommunicationManager.Instance != null)
{
// 取消订阅用户登录结果事件
BLECommunicationManager.Instance.OnUserLoginResult -= OnUserLoginResult;
2026-05-18 08:42:33 +08:00
BLECommunicationManager.Instance.OnDeviceLockControlReceived-=OnLockReceived;
BLECommunicationManager.Instance.OnWorkModeSettingReceived -= OnWorkModeReceived;
BLECommunicationManager.Instance.OnScheduleTaskListReceived -= OnScheduleTaskListReceived;
BLECommunicationManager.Instance.OnAngleControlReceived -= OnAngleControlReceived;
BLECommunicationManager.Instance.OnDistanceControlReceived -= OnDistanceControlReceived;
BLECommunicationManager.Instance.OnFillLightControlReceived -= OnFillLightControlReceived;
// BLECommunicationManager.Instance.OnMillimeterWaveSettingReceived -= OnMillimeterWaveReceived;
BLECommunicationManager.Instance.OnVisualDetectionSettingReceived -= OnVisualDetectionReceived;
}
}
#endregion
#region
// 标记是否已完成蓝牙用户登录
private bool isBluetoothUserLoggedIn = false;
private void OnBluetoothConnected()
{
Debug.Log("[HomePageCtrl] 蓝牙连接成功");
hasBluetooth = true;
// 更新连接状态UI
pendingUIUpdates.Add(() =>
{
deviceState?.UpdateDeviceState(hasBluetooth, hasWifi);
2026-05-18 08:42:33 +08:00
// 先进行蓝牙用户登录,登录成功后再获取设备状态
StartCoroutine(BluetoothUserLoginThenQueryStatus());
});
2026-05-18 08:42:33 +08:00
}
/// <summary>
/// 蓝牙用户登录,登录成功后查询设备状态
/// </summary>
private IEnumerator BluetoothUserLoginThenQueryStatus()
{
2026-05-18 08:42:33 +08:00
LoadingUI.Show();
yield return new WaitForSeconds(0.5f);
// 获取用户ID
string username = DataManager.Instance?.userInfo?.id;
if (string.IsNullOrEmpty(username))
{
Debug.LogError("[HomePageCtrl] 蓝牙用户登录失败:用户未登录");
yield break;
}
Debug.Log($"[HomePageCtrl] 开始进行蓝牙用户登录,用户名: {username}");
isBluetoothUserLoggedIn = false;
// 调用蓝牙用户登录
BLECommunicationManager.Instance?.UserLogin(username, (response) =>
{
if (response.IsSuccess)
{
Debug.Log("[HomePageCtrl] 蓝牙用户登录成功");
isBluetoothUserLoggedIn = true;
}
else
{
Debug.LogError($"[HomePageCtrl] 蓝牙用户登录失败: {response.Status}");
}
});
// 等待登录结果最多3秒
float timeout = 3f;
float elapsed = 0f;
while (!isBluetoothUserLoggedIn && elapsed < timeout)
{
yield return new WaitForSeconds(0.1f);
elapsed += 0.1f;
}
if (isBluetoothUserLoggedIn)
{
2026-05-18 08:42:33 +08:00
Debug.Log("[HomePageCtrl] 蓝牙用户登录成功,获取锁定状态");
BLECommunicationManager.Instance.ReadDeviceLockControl();
}
else
{
2026-05-18 08:42:33 +08:00
Debug.LogWarning("[HomePageCtrl] 蓝牙用户登录超时3s重试");
yield return new WaitForSeconds(3);
StartCoroutine(BluetoothUserLoginThenQueryStatus());
}
}
/// <summary>
/// 用户登录结果回调
/// </summary>
private void OnUserLoginResult(UserLoginResponse response)
{
Debug.Log($"[HomePageCtrl] 收到用户登录结果: {response.Status}");
// 登录结果在 UserLogin 回调中处理,这里仅作日志记录
}
/// <summary>
/// 开始设备状态初始化
/// </summary>
private void StartDeviceStateInitialization()
{
isDeviceStateInitializing = true;
pendingStatusCount = TOTAL_STATUS_COUNT;
// 显示Loading阻止操作
LoadingUI.Show();
// 启动超时检测
if (statusQueryTimeoutCoroutine != null)
{
StopCoroutine(statusQueryTimeoutCoroutine);
}
statusQueryTimeoutCoroutine = StartCoroutine(StatusQueryTimeoutCoroutine());
Debug.Log($"[HomePageCtrl] 开始设备状态初始化,待接收状态数: {pendingStatusCount}");
}
/// <summary>
/// 状态查询超时协程
/// </summary>
private IEnumerator StatusQueryTimeoutCoroutine()
{
yield return new WaitForSeconds(statusQueryTimeout);
if (isDeviceStateInitializing)
{
Debug.LogWarning($"[HomePageCtrl] 设备状态查询超时,已接收 {TOTAL_STATUS_COUNT - pendingStatusCount}/{TOTAL_STATUS_COUNT} 个状态");
FinishDeviceStateInitialization();
}
}
/// <summary>
/// 完成设备状态初始化
/// </summary>
private void FinishDeviceStateInitialization()
{
isDeviceStateInitializing = false;
pendingStatusCount = 0;
// 隐藏Loading
LoadingUI.Hide();
// 停止超时协程
if (statusQueryTimeoutCoroutine != null)
{
StopCoroutine(statusQueryTimeoutCoroutine);
statusQueryTimeoutCoroutine = null;
}
Debug.Log("[HomePageCtrl] 设备状态初始化完成");
}
/// <summary>
/// 接收一个状态,减少待接收计数
/// </summary>
private void ReceiveStatus()
{
if (!isDeviceStateInitializing) return;
pendingStatusCount--;
Debug.Log($"[HomePageCtrl] 接收到状态,剩余: {pendingStatusCount}/{TOTAL_STATUS_COUNT}");
// 所有状态都接收完成
if (pendingStatusCount <= 0)
{
FinishDeviceStateInitialization();
}
}
private void OnBluetoothDisconnected(string address)
{
Debug.Log("[HomePageCtrl] 蓝牙断开连接");
hasBluetooth = false;
isBluetoothUserLoggedIn = false;
isQueryingStatus = false;
statusQueryQueue?.Clear();
UIManager.Instance?.ClearBackAction();
UIManager.Instance.OpenPage(UIManager.PageName.homePage, null, true);
}
private void OnBluetoothError(string error)
{
Debug.LogError($"[HomePageCtrl] 蓝牙错误: {error}");
}
/// <summary>
/// 延迟查询设备状态
/// </summary>
private IEnumerator QueryDeviceStatusDelayed()
{
// 等待 500ms 确保连接稳定
2026-05-18 08:42:33 +08:00
yield return new WaitForSeconds(0.1f);
// 开始设备状态初始化显示Loading
StartDeviceStateInitialization();
// 串行查询设备状态
StartCoroutine(QueryAllDeviceStatusSequential());
}
/// <summary>
/// 串行查询所有设备状态(收到返回后再发送下一个)
/// </summary>
private IEnumerator QueryAllDeviceStatusSequential()
{
Debug.Log("[HomePageCtrl] 开始串行查询设备状态...");
// 清空队列
statusQueryQueue.Clear();
isQueryingStatus = true;
// 将查询请求加入队列
statusQueryQueue.Enqueue(() => { Debug.Log("[HomePageCtrl] 查询: 工作模式"); BLECommunicationManager.Instance?.ReadWorkMode(); });
statusQueryQueue.Enqueue(() => { Debug.Log("[HomePageCtrl] 查询: 定时任务"); BLECommunicationManager.Instance?.ReadScheduleTasks(); });
statusQueryQueue.Enqueue(() => { Debug.Log("[HomePageCtrl] 查询: 角度控制"); BLECommunicationManager.Instance?.ReadAngleControl(); });
statusQueryQueue.Enqueue(() => { Debug.Log("[HomePageCtrl] 查询: 距离控制"); BLECommunicationManager.Instance?.ReadDistanceControl(); });
statusQueryQueue.Enqueue(() => { Debug.Log("[HomePageCtrl] 查询: 补光灯控制"); BLECommunicationManager.Instance?.ReadFillLightControl(); });
statusQueryQueue.Enqueue(() => { Debug.Log("[HomePageCtrl] 查询: 视觉检测"); BLECommunicationManager.Instance?.ReadVisualDetectionSetting(); });
// 依次执行查询
while (statusQueryQueue.Count > 0 && isQueryingStatus)
{
int pendingCountBefore = pendingStatusCount;
var query = statusQueryQueue.Dequeue();
query?.Invoke();
// 等待 200ms 确保请求发送完成
yield return new WaitForSeconds(0.2f);
// 等待响应最多2秒
float waitTime = 0f;
float maxWaitTime = 2f;
while (waitTime < maxWaitTime)
{
// 检查是否已接收到状态(通过 pendingStatusCount 减少来判断)
if (pendingStatusCount < pendingCountBefore)
{
Debug.Log($"[HomePageCtrl] 收到响应,继续下一个查询");
break;
}
yield return new WaitForSeconds(0.05f);
waitTime += 0.05f;
}
}
isQueryingStatus = false;
2026-05-18 08:42:33 +08:00
moreSettingButton.interactable = true;
Debug.Log("[HomePageCtrl] 串行查询设备状态完成");
}
/// <summary>
/// 查询所有设备状态(旧方法,已废弃)
/// </summary>
private void QueryAllDeviceStatus()
{
Debug.Log("[HomePageCtrl] 开始查询设备状态...");
// 查询工作模式
BLECommunicationManager.Instance?.ReadWorkMode();
// 查询硬件状态
BLECommunicationManager.Instance?.ReadHardwareStatus();
// 查询定时任务
BLECommunicationManager.Instance?.ReadScheduleTasks();
// 查询角度控制
BLECommunicationManager.Instance?.ReadAngleControl();
// 查询距离控制
BLECommunicationManager.Instance?.ReadDistanceControl();
// 查询补光灯控制
BLECommunicationManager.Instance?.ReadFillLightControl();
// 查询毫米波雷达设置
BLECommunicationManager.Instance?.ReadMillimeterWaveSetting();
// 查询视觉检测设置
BLECommunicationManager.Instance?.ReadVisualDetectionSetting();
}
#endregion
#region
// 当前工作模式
private WorkMode currentWorkMode = WorkMode.Standby;
/// <summary>
/// 设置工作模式
/// </summary>
/// <param name="mode">0:待机 1:扫描 2:消杀</param>
public void SetWorkMode(int mode)
{
// 检查是否与当前模式相同
if ((int)currentWorkMode == mode)
{
Debug.Log($"[HomePageCtrl] 目标模式 {mode} 与当前模式相同,不执行切换");
return;
}
// 检查蓝牙连接
if (!BluetoothManager.Instance.IsConnected)
{
Debug.LogWarning("[HomePageCtrl] 蓝牙未连接,无法切换工作模式");
LoadingUI.Hide();
return;
}
// 显示 Loading
LoadingUI.Show();
// 构建工作模式设置
WorkModeSetting setting = new WorkModeSetting
{
Mode = (WorkMode)mode
};
Debug.Log($"[HomePageCtrl] 正在设置工作模式: {setting.Mode}");
// 发送设置命令
BLECommunicationManager.Instance?.WriteWorkMode(setting, (success) =>
{
Loom.QueueOnMainThread(() =>
{
if (success)
{
Debug.Log($"[HomePageCtrl] 工作模式设置成功: {setting.Mode}");
// 更新当前模式
currentWorkMode = setting.Mode;
// 更新 UI
pendingUIUpdates.Add(() =>
{
deviceCtrl?.InitWrokMode(mode);
});
// 等待响应处理完成后再查询工作模式确认
StartCoroutine(QueryWorkModeAfterSet());
}
else
{
Debug.LogError("[HomePageCtrl] 工作模式设置失败");
LoadingUI.Hide();
}
});
});
2026-05-18 08:42:33 +08:00
}
2026-05-18 08:42:33 +08:00
/// <summary>
/// 设置工作模式后查询确认(等待响应处理完成)
/// </summary>
private IEnumerator QueryWorkModeAfterSet()
{
// 等待一帧确保响应处理完成
yield return null;
// 再等待 300ms 确保设备处理完成
yield return new WaitForSeconds(0.3f);
Debug.Log("[HomePageCtrl] 重新查询工作模式确认...");
BLECommunicationManager.Instance?.ReadWorkMode();
// 等待查询响应完成后再隐藏 Loading
StartCoroutine(HideLoadingAfterQueryWorkMode());
}
/// <summary>
/// 查询工作模式响应后隐藏 Loading
/// </summary>
private IEnumerator HideLoadingAfterQueryWorkMode()
{
isWaitingForWorkModeQuery = true;
// 等待最多 2 秒接收工作模式响应
float timeout = 2f;
float elapsed = 0f;
while (elapsed < timeout)
{
// 如果标志被重置,说明收到了响应
if (!isWaitingForWorkModeQuery)
{
Debug.Log("[HomePageCtrl] 收到工作模式查询响应,隐藏 Loading");
break;
}
yield return new WaitForSeconds(0.05f);
elapsed += 0.05f;
}
isWaitingForWorkModeQuery = false;
LoadingUI.Hide();
}
2026-05-18 08:42:33 +08:00
private void OnLockReceived(DeviceLockControl setting)
{
Debug.Log($"[HomePageCtrl] 锁定状态: {setting.IsLocked}");
pendingUIUpdates.Add(() =>
{
LoadingUI.Hide();
if(setting.IsLocked)
{
deviceCtrl.InitDeviceControl(false);
BLECommunicationManager.Instance.ReadScheduleTasks();
}
else
{
deviceCtrl.InitDeviceControl(true);
StartCoroutine(QueryDeviceStatusDelayed());
}
});
}
private void OnWorkModeReceived(WorkModeSetting setting)
{
Debug.Log($"[HomePageCtrl] 收到工作模式: {setting.Mode}");
ReceiveStatus();
// 更新当前工作模式
currentWorkMode = setting.Mode;
// 如果是工作模式设置后的查询响应,重置等待标志
if (isWaitingForWorkModeQuery)
{
isWaitingForWorkModeQuery = false;
Debug.Log("[HomePageCtrl] 工作模式查询响应已处理");
}
pendingUIUpdates.Add(() =>
{
deviceCtrl?.InitWrokMode((int)setting.Mode);
});
}
private void OnScheduleTaskListReceived(ScheduleTaskListResponse response)
{
// 如果设置页面正在处理,跳过主页处理
if (ScheduleSettingPage.IsSettingPageActive())
{
Debug.Log("[HomePageCtrl] 设置页面正在处理定时任务列表,跳过主页更新");
return;
}
if (response.IsSuccess)
{
Debug.Log($"[HomePageCtrl] 收到定时任务列表: {response.Tasks.Length} 个任务");
ReceiveStatus();
pendingUIUpdates.Add(() =>
{
deviceSchedule?.Init(response.Tasks);
});
}
else
{
ReceiveStatus();
}
scheduleSettingButton.interactable=true;
}
private void OnAngleControlReceived(AngleControl control)
{
// 如果设置页面正在处理,跳过主页处理
if (FovSettingPage.IsSettingPageActive())
{
Debug.Log("[HomePageCtrl] 设置页面正在处理角度控制,跳过主页更新");
return;
}
Debug.Log($"[HomePageCtrl] 收到角度控制: {control.ActualAngle}°");
ReceiveStatus();
pendingUIUpdates.Add(() =>
{
// 使用实际角度值
int fov = (int)control.ActualAngle;
deviceCtrl?.InitFovText(fov);
});
}
/// <summary>
/// 刷新角度控制设置供FovSettingPage调用
/// </summary>
public void RefreshAngleControl()
{
Debug.Log("[HomePageCtrl] 刷新角度控制设置");
BLECommunicationManager.Instance?.ReadAngleControl();
}
private void OnDistanceControlReceived(DistanceControl control)
{
// 如果设置页面正在处理,跳过主页处理
if (LensSettingPage.IsSettingPageActive())
{
Debug.Log("[HomePageCtrl] 设置页面正在处理距离控制,跳过主页更新");
return;
}
// 单位是 0.1m,需要除以 10 转换为实际米数
float detectionDistance = control.DetectionDistance / 10f;
float aimDistance = control.AimDistance / 10f;
Debug.Log($"[HomePageCtrl] 收到距离控制: 检测={detectionDistance}m, 瞄准={aimDistance}m");
ReceiveStatus();
pendingUIUpdates.Add(() =>
{
// 使用检测距离,单位 0.1m 转实际米数保留1位小数
deviceCtrl?.InitLensText(detectionDistance, DataManager.Instance.userInfo.unit_system); // 0 = 米
});
}
/// <summary>
/// 刷新lens设置
/// </summary>
public void RefreshLensControl()
{
Debug.Log("[HomePageCtrl] 刷新距离控制设置");
BLECommunicationManager.Instance?.ReadDistanceControl();
}
private void OnFillLightControlReceived(FillLightControl control)
{
// 如果设置页面正在处理,跳过主页处理
if (LightSettingPage.IsSettingPageActive())
{
Debug.Log("[HomePageCtrl] 设置页面正在处理补光灯控制,跳过主页更新");
return;
}
Debug.Log($"[HomePageCtrl] 收到补光灯控制: {control.Enable}");
ReceiveStatus();
pendingUIUpdates.Add(() =>
{
deviceCtrl?.InitLightText(control.Enable);
});
}
public void RefreshLightControl()
{
Debug.Log("[HomePageCtrl] 刷新补光灯控制设置");
BLECommunicationManager.Instance?.ReadFillLightControl();
}
// private void OnMillimeterWaveReceived(MillimeterWaveSetting setting)
// {
// Debug.Log($"[HomePageCtrl] 收到毫米波设置: {setting.Enable}");
// ReceiveStatus();
// pendingUIUpdates.Add(() =>
// {
// // 更新安全状态 - 毫米波
// // 注意:需要结合 VisualDetectionSetting 一起判断
// });
// }
private void OnVisualDetectionReceived(VisualDetectionSetting setting)
{
// 如果设置页面正在处理,跳过主页处理
if (SafetySettingPage.IsSettingPageActive())
{
Debug.Log("[HomePageCtrl] 设置页面正在处理视觉检测设置,跳过主页更新");
return;
}
Debug.Log($"[HomePageCtrl] 收到视觉检测设置: {setting.Enable}");
ReceiveStatus();
pendingUIUpdates.Add(() =>
{
deviceCtrl?.InitSafeText(setting.Enable);
});
}
#endregion
public void Init()
{
if (DataManager.Instance.userInfo.device_count == 0)
{
noDevicePage.SetActive(true);
normalPage.SetActive(false);
selectedDevice = null;
selectDeviceButton.gameObject.SetActive(false);
return;
}
else
{
noDevicePage.SetActive(false);
normalPage.SetActive(true);
}
if (DataManager.Instance.selectedDeviceMac == "")
{
selectedDevice = OwnedDevices[0];
DataManager.Instance.selectedDeviceMac = selectedDevice.device_sn;
DataManager.Instance.SavaSelectedDeviceMac(selectedDevice.device_sn);
}
else
{
selectedDevice = OwnedDevices.Find(x => x.device_sn == DataManager.Instance.selectedDeviceMac);
if (selectedDevice == null)
{
selectedDevice = SharedDevices.Find(x => x.device_sn == DataManager.Instance.selectedDeviceMac);
if (selectedDevice == null)
{
selectedDevice = OwnedDevices[0];
DataManager.Instance.selectedDeviceMac = selectedDevice.device_sn;
DataManager.Instance.SavaSelectedDeviceMac(selectedDevice.device_sn);
}
}
}
hasBluetooth = BluetoothManager.Instance.ChangeAimMac(selectedDevice.device_sn);
selectDeviceButton.GetComponentInChildren<Text>().text = selectedDevice.device_name;
selectDeviceButton.gameObject.SetActive(true);
// 先初始化所有 UI 为未连接状态
ResetAllDeviceUI();
InitDeviceState();
// 如果蓝牙已连接,立即查询状态
if (hasBluetooth)
{
deviceState?.UpdateDeviceState(hasBluetooth, hasWifi);
deviceCtrl?.InitDeviceControl(true);
// 开始设备状态初始化显示Loading
StartDeviceStateInitialization();
StartCoroutine(QueryAllDeviceStatusSequential());
scheduleSettingButton.interactable = true;
2026-05-18 08:42:33 +08:00
moreSettingButton.interactable = true;
}
else
{
deviceCtrl?.InitDeviceControl(false);
scheduleSettingButton.interactable = false;
2026-05-18 08:42:33 +08:00
moreSettingButton.interactable = false;
}
}
/// <summary>
/// 重置所有设备 UI 为未连接状态
/// </summary>
private void ResetAllDeviceUI()
{
Debug.Log("[HomePageCtrl] 重置所有 UI 为未连接状态");
// 重置工作模式为未连接
deviceCtrl?.InitWrokMode(-1);
// 重置 FOV
deviceCtrl?.InitFovText(0);
// 重置距离
deviceCtrl?.InitLensText(0f, 0);
// 重置补光灯
deviceCtrl?.InitLightText(false);
// 重置安全状态
deviceCtrl?.InitSafeText(false);
// 重置定时任务显示
deviceSchedule?.DisplayNoSchedule();
scheduleSettingButton.onClick.RemoveAllListeners();
scheduleSettingButton.onClick.AddListener(() =>
{
ShowScheduleSettingPage();
});
scheduleSettingButton.interactable = false;
2026-05-18 08:42:33 +08:00
moreSettingButton.interactable = false;
}
/// <summary>
/// 获取用户设备列表
/// </summary>
public async Task FetchDeviceList()
{
LoadingUI.Show();
try
{
Debug.Log("[HomePageCtrl] 开始获取设备列表...");
// 构建带 user_id 参数的 URL
string userId = DataManager.Instance?.userInfo?.id;
if (string.IsNullOrEmpty(userId))
{
Debug.LogError("[HomePageCtrl] 获取设备列表失败: 用户未登录");
LoadingUI.Hide();
return;
}
string url = $"/api/v1/device/user/list?user_id={userId}";
var response = await NetworkCtrl.Instance.Get<DeviceListResponse>(url);
LoadingUI.Hide();
ResponseCodeHandler.HandleResponse(response,
onSuccess: (data) =>
{
// 更新设备列表
OwnedDevices = data.data.owned_devices ?? new List<Kill.Managers.DeviceInfo>();
2026-05-18 08:42:33 +08:00
foreach(var device in OwnedDevices)
{
device.owner_id=DataManager.Instance.userInfo.id;
}
SharedDevices = data.data.shared_devices ?? new List<Kill.Managers.DeviceInfo>();
Debug.Log($"[HomePageCtrl] 获取设备列表成功: 自有设备={OwnedDevices.Count}, 共享设备={SharedDevices.Count}");
DataManager.Instance.userInfo.device_count = OwnedDevices.Count + SharedDevices.Count;
},
onError: null
);
}
catch (Exception ex)
{
LoadingUI.Hide();
Debug.LogError($"[HomePageCtrl] 获取设备列表异常: {ex.Message}");
}
}
void Update()
{
// 执行所有挂起的UI更新
if (pendingUIUpdates.Count > 0)
{
foreach (var update in pendingUIUpdates)
{
update?.Invoke();
}
pendingUIUpdates.Clear();
}
}
public void ConnectDevice()
{
if (!CheckSafetylearning())
{
UIManager.Instance.OpenPage(UIManager.PageName.safetylearningPage);
return;
}
UIManager.Instance.OpenPage(UIManager.PageName.connectDevicePage);
}
public bool CheckSafetylearning()
{
bool isPassed = false;
isPassed = DataManager.Instance.userInfo.exam_completed;
return isPassed;
}
public void InitDeviceState()
{
// 初始化设备状态UI
deviceState?.UpdateDeviceState(hasBluetooth, hasWifi);
}
public void ShowDeviceList()
{
selectDevicePage.SetActive(true);
selectDevicePage.GetComponent<HomePageDevicePage>().InitDeviceList(OwnedDevices, SharedDevices, selectedDevice);
UIManager.Instance.RegisterBackAction(() =>
{
selectDevicePage.GetComponent<HomePageDevicePage>().ClosePage();
});
}
public GameObject fovSettingPagePrefab;
public void ShowFovSettingPage()
{
if (fovSettingPagePrefab == null)
{
Debug.LogError("[HomePageCtrl] 未设置FOV设置页面预制体");
return;
}
GameObject fovSettingPage = Instantiate(fovSettingPagePrefab, transform);
fovSettingPage.SetActive(true);
UIManager.Instance.RegisterBackAction(() =>
{
fovSettingPage.GetComponent<FovSettingPage>().OnCancelButtonClick();
});
}
public GameObject lensSettingPagePrefab;
public void ShowLensSettingPage()
{
if (lensSettingPagePrefab == null)
{
Debug.LogError("[HomePageCtrl] 未设置lens设置页面预制体");
return;
}
GameObject lensSettingPage = Instantiate(lensSettingPagePrefab, transform);
lensSettingPage.SetActive(true);
UIManager.Instance.RegisterBackAction(() =>
{
lensSettingPage.GetComponent<LensSettingPage>().OnCancelButtonClick();
});
}
public GameObject lightSettingPagePrefab;
public void ShowLightSettingPage()
{
if (lightSettingPagePrefab == null)
{
Debug.LogError("[HomePageCtrl] 未设置light设置页面预制体");
return;
}
GameObject lightSettingPage = Instantiate(lightSettingPagePrefab, transform);
lightSettingPage.SetActive(true);
UIManager.Instance.RegisterBackAction(() =>
{
lightSettingPage.GetComponent<LightSettingPage>().ClosePage();
});
}
public GameObject safetySettingPagePrefab;
public void ShowSafetySettingPage()
{
if (safetySettingPagePrefab == null)
{
Debug.LogError("[HomePageCtrl] 未设置safetySettingPage预制体");
return;
}
GameObject safetySettingPage = Instantiate(safetySettingPagePrefab, transform);
safetySettingPage.SetActive(true);
UIManager.Instance.RegisterBackAction(() =>
{
safetySettingPage.GetComponent<SafetySettingPage>().ClosePage();
});
}
public void ShowScheduleSettingPage()
{
if (scheduleSettingPrefab == null)
{
Debug.LogError("[HomePageCtrl] 未设置scheduleSettingPage预制体");
return;
}
GameObject scheduleSettingPage = Instantiate(scheduleSettingPrefab, transform);
scheduleSettingPage.SetActive(true);
// 注册页面关闭回调,更新主页定时任务显示
var schedulePage = scheduleSettingPage.GetComponent<ScheduleSettingPage>();
if (schedulePage != null)
{
schedulePage.OnPageClosed = () =>
{
// 重新读取定时任务更新主页显示
BLECommunicationManager.Instance?.ReadScheduleTasks();
};
}
UIManager.Instance.RegisterBackAction(() =>
{
scheduleSettingPage.GetComponent<ScheduleSettingPage>().ClosePage();
});
}
2026-05-18 08:42:33 +08:00
public Button moreSettingButton;
public void EnterMoreSettingPage()
{
DataManager.Instance.selectedDevice=selectedDevice;
UIManager.Instance.OpenPage(UIManager.PageName.deviceInfoPage);
}
public void SetLock(bool ison)
{
if(hasBluetooth)
{
BLECommunicationManager.Instance.WriteDeviceLockControl(!ison, (success) =>
{
Loom.QueueOnMainThread(() =>
{
if(ison)
{
DeviceLockControl deviceLockControl=new DeviceLockControl();
deviceLockControl.IsLocked=false;
OnLockReceived(deviceLockControl);
}
else
{
deviceCtrl.InitDeviceControl(false);
LoadingUI.Hide();
}
});
});
}
else
{
LoadingUI.Hide();
ToastUI.Show("100081");
}
}
}
}