using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using Kill.Bluetooth; using Kill.Bluetooth.Protocol; using Kill.Core; using Kill.Managers; using Kill.Network; using Kill.UI.Components; using UnityEngine; using UnityEngine.UI; namespace Kill.UI.Pages { public class LensSettingPage : MonoBehaviour { public Text lensText; public Image lensIcon; public RectTransform lensIconRectTransform; /// /// 可见激光开关 0关 1开 /// public Button vllButton; /// /// 可见激光开关图标 0关 1开 /// public Sprite[] vllButtonSprites; public Button confirmButton; public Button cancelButton; public Button switchUnitButton; /// /// 0 米未选中 1 米已选中 2 英尺未选中 3 英尺已选中 /// public GameObject[] unitStateIcons; /// /// 0 米 1 英尺 /// private int nowUnit = 0; // 当前设置值 private float currentLensValue = 3f; // 当前距离(m) private float selectedLensValue = 3f; // 选中的距离(m) private bool vllEnabled = false; // 可见激光开关状态 // 进入设置前的原始值(用于取消恢复) private float originalLensValue = 3f; // 原始距离(m) private bool originalVllEnabled = false; // 原始可见激光状态 /// /// 0米选择器 1英尺选择器 /// public SlideSelector[] slideSelectors; // 静态标志:是否有设置页面正在处理回调 private static bool _isSettingPageActive = false; // 常量定义 private const float MIN_LENS_Y = 231f; // 最小Y值对应2m private const float MAX_LENS_Y = 281f; // 最大Y值对应6m private const float MIN_LENS_VALUE = 2f; // 最小距离2m private const float MAX_LENS_VALUE = 6f; // 最大距离6m void Start() { // 绑定按钮点击事件 BindButtonEvents(); nowUnit = DataManager.Instance.userInfo.unit_system; InitLensSettingPage(); } /// /// 绑定按钮点击事件 /// private void BindButtonEvents() { // 绑定可见激光开关按钮 if (vllButton != null) { vllButton.onClick.RemoveAllListeners(); vllButton.onClick.AddListener(OnVllButtonClick); } // 绑定确认按钮 if (confirmButton != null) { confirmButton.onClick.RemoveAllListeners(); confirmButton.onClick.AddListener(OnConfirmButtonClick); } // 绑定取消按钮 if (cancelButton != null) { cancelButton.onClick.RemoveAllListeners(); cancelButton.onClick.AddListener(OnCancelButtonClick); } // 绑定切换单位按钮 if (switchUnitButton != null) { switchUnitButton.onClick.RemoveAllListeners(); switchUnitButton.onClick.AddListener(OnSwitchUnitButtonClick); } // 绑定滑动选择器事件 if (slideSelectors != null && slideSelectors.Length >= 2) { if (slideSelectors[0] != null) { slideSelectors[0].OnValueChanged -= OnLensValueChanged; slideSelectors[0].OnValueChanged += OnLensValueChanged; slideSelectors[0].OnValueSelected -= OnLensValueSelected; slideSelectors[0].OnValueSelected += OnLensValueSelected; } if (slideSelectors[1] != null) { slideSelectors[1].OnValueChanged -= OnLensValueChanged; slideSelectors[1].OnValueChanged += OnLensValueChanged; slideSelectors[1].OnValueSelected -= OnLensValueSelected; slideSelectors[1].OnValueSelected += OnLensValueSelected; } } } /// /// 初始化Lens设置页面 /// public void InitLensSettingPage() { Debug.Log("[LensSettingPage] 初始化Lens设置页面"); // 注册蓝牙回调(顶替主页) RegisterBluetoothCallbacks(); // 更新单位显示 UpdateUnitUI(); // 读取当前距离控制和可见激光设置 ReadLensAndVllSettings(); } /// /// 注册蓝牙回调(顶替主页) /// private void RegisterBluetoothCallbacks() { if (BLECommunicationManager.Instance != null) { // 设置标志位,表示设置页面正在处理 _isSettingPageActive = true; // 订阅事件 BLECommunicationManager.Instance.OnDistanceControlReceived += OnDistanceControlReceived; BLECommunicationManager.Instance.OnVisibleLaserControlReceived += OnVisibleLaserControlReceived; Debug.Log("[LensSettingPage] 蓝牙回调已注册"); } } /// /// 注销蓝牙回调(恢复主页) /// private void UnregisterBluetoothCallbacks() { if (BLECommunicationManager.Instance != null) { // 取消订阅事件 BLECommunicationManager.Instance.OnDistanceControlReceived -= OnDistanceControlReceived; BLECommunicationManager.Instance.OnVisibleLaserControlReceived -= OnVisibleLaserControlReceived; // 清除标志位 _isSettingPageActive = false; Debug.Log("[LensSettingPage] 蓝牙回调已注销"); } } /// /// 距离控制接收回调 /// private void OnDistanceControlReceived(DistanceControl control) { Loom.QueueOnMainThread(() => { // 只有当前设置页面激活时才处理 if (!_isSettingPageActive) return; // 使用AimDistance作为lens值,单位是0.1米 currentLensValue = control.AimDistance*0.1f; selectedLensValue = currentLensValue; originalLensValue = currentLensValue; Debug.Log($"[LensSettingPage] 读取距离控制: {currentLensValue}m"); BLECommunicationManager.Instance?.ReadVisibleLaserControl(); }); } /// /// 可见激光控制接收回调 /// private void OnVisibleLaserControlReceived(VisibleLaserControl control) { Loom.QueueOnMainThread(() => { // 只有当前设置页面激活时才处理 if (!_isSettingPageActive) return; LoadingUI.Hide(); // 获取可见激光开关状态 vllEnabled = control.Enable; originalVllEnabled = vllEnabled; Debug.Log($"[LensSettingPage] 读取可见激光: {vllEnabled}"); // 更新UI显示 UpdateUI(); }); } /// /// 检查是否有设置页面正在处理回调 /// public static bool IsSettingPageActive() { return _isSettingPageActive; } /// /// 读取距离控制和可见激光设置 /// private void ReadLensAndVllSettings() { if (DataManager.Instance.hasWifi && !DataManager.Instance.hasBluetooth) { LoadSettingsFromConfig(); return; } // 显示Loading LoadingUI.Show(); // 先读取距离控制 BLECommunicationManager.Instance?.ReadDistanceControl(); } private void LoadSettingsFromConfig() { var config = DataManager.Instance.deviceConfig; currentLensValue = (config?.detection_distance ?? 0) * 0.1f; selectedLensValue = currentLensValue; originalLensValue = currentLensValue; vllEnabled = config?.laser_visible_enable ?? false; originalVllEnabled = vllEnabled; UpdateUI(); } /// /// 更新UI显示 /// private void UpdateUI() { // 更新距离文本 UpdateLensText(); // 更新lens图标位置 UpdateLensIconPosition(); // 更新可见激光开关图标 UpdateVllButton(); // 更新选择器值 UpdateSlideSelectorValue(); } /// /// 更新距离文本显示 /// private void UpdateLensText() { if (lensText == null) return; if (nowUnit == 0) { // 米 lensText.text = $"{selectedLensValue:F1}m"; } else { // 英尺 (1m = 3.28084ft) int feet = Mathf.RoundToInt(selectedLensValue * 3.28084f); lensText.text = $"{feet}ft"; } } /// /// 更新lens图标位置 /// private void UpdateLensIconPosition() { if (lensIconRectTransform == null) return; // 将距离值(2-6)映射到Y坐标(231-281) float t = (selectedLensValue - MIN_LENS_VALUE) / (MAX_LENS_VALUE - MIN_LENS_VALUE); float yPos = Mathf.Lerp(MIN_LENS_Y, MAX_LENS_Y, t); Vector2 sizeDelta = lensIconRectTransform.sizeDelta; sizeDelta.y = yPos; lensIconRectTransform.sizeDelta = sizeDelta; } /// /// 更新滑动选择器的值 /// private void UpdateSlideSelectorValue() { if (slideSelectors == null || slideSelectors.Length < 2) return; // 根据当前单位显示对应的选择器 if (nowUnit == 0) { // 米选择器 if (slideSelectors[0] != null) { slideSelectors[0].gameObject.SetActive(true); slideSelectors[0].DefaultValue = selectedLensValue; slideSelectors[0].Initialize(); } if (slideSelectors[1] != null) { slideSelectors[1].gameObject.SetActive(false); } } else { // 英尺选择器 if (slideSelectors[0] != null) { slideSelectors[0].gameObject.SetActive(false); } if (slideSelectors[1] != null) { slideSelectors[1].gameObject.SetActive(true); // 将米转换为英尺显示 int feet = Mathf.RoundToInt(selectedLensValue * 3.28084f); slideSelectors[1].DefaultValue = feet; slideSelectors[1].Initialize(); } } } /// /// 更新单位UI显示 /// private void UpdateUnitUI() { if (unitStateIcons == null || unitStateIcons.Length < 4) return; // 0 米未选中 1 米已选中 2 英尺未选中 3 英尺已选中 for (int i = 0; i < unitStateIcons.Length; i++) { if (unitStateIcons[i] != null) { unitStateIcons[i].SetActive(false); } } if (nowUnit == 0) { // 米选中 if (unitStateIcons[1] != null) unitStateIcons[1].SetActive(true); if (unitStateIcons[2] != null) unitStateIcons[2].SetActive(true); } else { // 英尺选中 if (unitStateIcons[3] != null) unitStateIcons[3].SetActive(true); if (unitStateIcons[0] != null) unitStateIcons[0].SetActive(true); } } /// /// 更新可见激光开关按钮 /// private void UpdateVllButton() { if (vllButton == null || vllButtonSprites == null || vllButtonSprites.Length < 2) return; Image buttonImage = vllButton.GetComponent(); if (buttonImage != null) { buttonImage.sprite = vllEnabled ? vllButtonSprites[1] : vllButtonSprites[0]; } } /// /// 滑动选择器值改变回调(滑动过程中实时更新) /// private void OnLensValueChanged(float value) { // 根据当前单位转换值 if (nowUnit == 0) { // 米 selectedLensValue = value; } else { // 英尺转米 selectedLensValue = value / 3.28084f; } // 限制范围 selectedLensValue = Mathf.Clamp(selectedLensValue, MIN_LENS_VALUE, MAX_LENS_VALUE); // 实时更新UI UpdateLensText(); UpdateLensIconPosition(); } /// /// 滑动选择器选中值回调(滑动结束后) /// private async void OnLensValueSelected(float value) { Debug.Log($"[LensSettingPage] 选中距离值: {value}"); // 发送距离设置到设备 await SendLensSettingToDeviceAsync(); } private async Task SendLensSettingToDeviceAsync() { // 设置检测距离和瞄准距离为同一个值 ushort distanceValue = (ushort)Mathf.RoundToInt(selectedLensValue*10); DistanceControl distanceControl = new DistanceControl { DetectionDistance = distanceValue, AimDistance = distanceValue // 单位是0.1米 }; if (DataManager.Instance.hasWifi && !DataManager.Instance.hasBluetooth) { bool success = await HomePageCtrl.Instance.SendBleCommandByWifiAsync( BLEConstants.CMD_DISTANCE_CONTROL, distanceControl.ToBytes()); if (success) { Debug.Log($"[LensSettingPage] 距离设置成功: {selectedLensValue}m"); currentLensValue = selectedLensValue; DataManager.Instance.deviceConfig.detection_distance = (int)(selectedLensValue * 10); } else { Debug.LogError("[LensSettingPage] 距离设置失败"); selectedLensValue = currentLensValue; UpdateUI(); } } else { BLECommunicationManager.Instance?.WriteDistanceControl(distanceControl, (success) => { Loom.QueueOnMainThread(() => { if (success) { Debug.Log($"[LensSettingPage] 距离设置成功: {selectedLensValue}m"); currentLensValue = selectedLensValue; DataManager.Instance.deviceConfig.detection_distance = (int)(selectedLensValue * 10); } else { Debug.LogError("[LensSettingPage] 距离设置失败"); // 设置失败,恢复UI显示 selectedLensValue = currentLensValue; UpdateUI(); } }); }); } } /// /// 可见激光开关按钮点击事件 /// private async void OnVllButtonClick() { bool newVllState = !vllEnabled; Debug.Log($"[LensSettingPage] 可见激光开关: {(newVllState ? "开" : "关")}"); // 发送可见激光设置到设备 VisibleLaserControl vllControl = new VisibleLaserControl { Enable = newVllState }; if (DataManager.Instance.hasWifi && !DataManager.Instance.hasBluetooth) { bool success = await HomePageCtrl.Instance.SendBleCommandByWifiAsync( BLEConstants.CMD_VISIBLE_LASER_CONTROL, vllControl.ToBytes()); if (success) { Debug.Log($"[LensSettingPage] 可见激光设置成功: {(newVllState ? "开" : "关")}"); vllEnabled = newVllState; UpdateVllButton(); DataManager.Instance.deviceConfig.laser_visible_enable = newVllState; } else { Debug.LogError("[LensSettingPage] 可见激光设置失败"); } } else { BLECommunicationManager.Instance?.WriteVisibleLaserControl(vllControl, (success) => { Loom.QueueOnMainThread(() => { if (success) { Debug.Log($"[LensSettingPage] 可见激光设置成功: {(newVllState ? "开" : "关")}"); vllEnabled = newVllState; UpdateVllButton(); DataManager.Instance.deviceConfig.laser_visible_enable = newVllState; } else { Debug.LogError("[LensSettingPage] 可见激光设置失败"); } }); }); } } /// /// 切换单位按钮点击事件 /// private void OnSwitchUnitButtonClick() { // 切换单位 nowUnit = (nowUnit == 0) ? 1 : 0; // 保存单位设置 DataManager.Instance.userInfo.unit_system = nowUnit; // 更新UI UpdateUnitUI(); UpdateLensText(); UpdateSlideSelectorValue(); Debug.Log($"[LensSettingPage] 切换单位: {(nowUnit == 0 ? "米" : "英尺")}"); } /// /// 确认按钮点击事件 /// private async void OnConfirmButtonClick() { Debug.Log($"[LensSettingPage] 确认设置,当前距离={selectedLensValue}m"); // 同步单位设置到服务器 await UpdateUnitSystemToServer(); // 通知主页刷新 NotifyHomePageRefresh(); // 关闭页面 ClosePage(); } /// /// 同步单位设置到服务器 /// private async Task UpdateUnitSystemToServer() { int unitSystem = DataManager.Instance.userInfo.unit_system; Debug.Log($"[LensSettingPage] 同步单位设置到服务器: {unitSystem}"); try { var request = new UnitRequest { unit_system = unitSystem }; var response = await NetworkCtrl.Instance.Put("/api/v1/user/unit-system", request); ResponseCodeHandler.HandleResponse(response, onSuccess: (data) => { Debug.Log(data.code); if (data.code == 200) { Debug.Log("[LensSettingPage] 单位设置同步成功"); } else { Debug.LogError($"[LensSettingPage] 单位设置同步失败: {data.code}"); } } ); } catch (System.Exception ex) { Debug.LogError($"[LensSettingPage] 单位设置同步异常: {ex.Message}"); } } /// /// 取消按钮点击事件 - 恢复原始数值 /// public async void OnCancelButtonClick() { Debug.Log("[LensSettingPage] 取消设置,恢复原始数值"); // 如果数值没有变化,直接关闭页面 if (Mathf.Abs(selectedLensValue - originalLensValue) < 0.01f) { Debug.Log("[LensSettingPage] 数值未变化,直接关闭页面"); NotifyHomePageRefresh(); ClosePage(); return; } // 显示Loading LoadingUI.Show(); // 恢复原始距离值(检测距离和瞄准距离同时恢复) ushort originalValue = (ushort)Mathf.RoundToInt(originalLensValue*10); DistanceControl distanceControl = new DistanceControl { DetectionDistance = originalValue, AimDistance = originalValue }; if (DataManager.Instance.hasWifi && !DataManager.Instance.hasBluetooth) { bool success = await HomePageCtrl.Instance.SendBleCommandByWifiAsync( BLEConstants.CMD_DISTANCE_CONTROL, distanceControl.ToBytes()); if (success) { Debug.Log($"[LensSettingPage] 距离恢复成功: {originalLensValue}m"); currentLensValue = originalLensValue; selectedLensValue = originalLensValue; DataManager.Instance.deviceConfig.detection_distance = (ushort)Mathf.RoundToInt(originalLensValue * 10); } else { Debug.LogError("[LensSettingPage] 距离恢复失败"); } NotifyHomePageRefresh(); ClosePage(); } else { BLECommunicationManager.Instance?.WriteDistanceControl(distanceControl, (success) => { Loom.QueueOnMainThread(() => { LoadingUI.Hide(); if (success) { Debug.Log($"[LensSettingPage] 距离恢复成功: {originalLensValue}m"); currentLensValue = originalLensValue; selectedLensValue = originalLensValue; DataManager.Instance.deviceConfig.detection_distance = (ushort)Mathf.RoundToInt(originalLensValue * 10); } else { Debug.LogError("[LensSettingPage] 距离恢复失败"); } // 通知主页刷新 NotifyHomePageRefresh(); // 关闭页面 ClosePage(); }); }); } } /// /// 通知主页刷新 /// private void NotifyHomePageRefresh() { // 通知主页刷新距离显示 HomePageCtrl.Instance?.RefreshLensControl(); } /// /// 关闭页面 /// private void ClosePage() { LoadingUI.Hide(); // 注销蓝牙回调(恢复主页) UnregisterBluetoothCallbacks(); // 通知主页刷新 NotifyHomePageRefresh(); Destroy(gameObject); // 清除UIManager返回事件 UIManager.Instance?.ClearBackAction(); } } }