killapp/Assets/Scripts/UI/Pages/HomePage/LensSettingPage.cs
“虞渠成” 412184ef1b wifi适配
2026-06-17 15:42:55 +08:00

717 lines
24 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
/// <summary>
/// 可见激光开关 0关 1开
/// </summary>
public Button vllButton;
/// <summary>
/// 可见激光开关图标 0关 1开
/// </summary>
public Sprite[] vllButtonSprites;
public Button confirmButton;
public Button cancelButton;
public Button switchUnitButton;
/// <summary>
/// 0 米未选中 1 米已选中 2 英尺未选中 3 英尺已选中
/// </summary>
public GameObject[] unitStateIcons;
/// <summary>
/// 0 米 1 英尺
/// </summary>
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; // 原始可见激光状态
/// <summary>
/// 0米选择器 1英尺选择器
/// </summary>
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();
}
/// <summary>
/// 绑定按钮点击事件
/// </summary>
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;
}
}
}
/// <summary>
/// 初始化Lens设置页面
/// </summary>
public void InitLensSettingPage()
{
Debug.Log("[LensSettingPage] 初始化Lens设置页面");
// 注册蓝牙回调(顶替主页)
RegisterBluetoothCallbacks();
// 更新单位显示
UpdateUnitUI();
// 读取当前距离控制和可见激光设置
ReadLensAndVllSettings();
}
/// <summary>
/// 注册蓝牙回调(顶替主页)
/// </summary>
private void RegisterBluetoothCallbacks()
{
if (BLECommunicationManager.Instance != null)
{
// 设置标志位,表示设置页面正在处理
_isSettingPageActive = true;
// 订阅事件
BLECommunicationManager.Instance.OnDistanceControlReceived += OnDistanceControlReceived;
BLECommunicationManager.Instance.OnVisibleLaserControlReceived += OnVisibleLaserControlReceived;
Debug.Log("[LensSettingPage] 蓝牙回调已注册");
}
}
/// <summary>
/// 注销蓝牙回调(恢复主页)
/// </summary>
private void UnregisterBluetoothCallbacks()
{
if (BLECommunicationManager.Instance != null)
{
// 取消订阅事件
BLECommunicationManager.Instance.OnDistanceControlReceived -= OnDistanceControlReceived;
BLECommunicationManager.Instance.OnVisibleLaserControlReceived -= OnVisibleLaserControlReceived;
// 清除标志位
_isSettingPageActive = false;
Debug.Log("[LensSettingPage] 蓝牙回调已注销");
}
}
/// <summary>
/// 距离控制接收回调
/// </summary>
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();
});
}
/// <summary>
/// 可见激光控制接收回调
/// </summary>
private void OnVisibleLaserControlReceived(VisibleLaserControl control)
{
Loom.QueueOnMainThread(() =>
{
// 只有当前设置页面激活时才处理
if (!_isSettingPageActive) return;
LoadingUI.Hide();
// 获取可见激光开关状态
vllEnabled = control.Enable;
originalVllEnabled = vllEnabled;
Debug.Log($"[LensSettingPage] 读取可见激光: {vllEnabled}");
// 更新UI显示
UpdateUI();
});
}
/// <summary>
/// 检查是否有设置页面正在处理回调
/// </summary>
public static bool IsSettingPageActive()
{
return _isSettingPageActive;
}
/// <summary>
/// 读取距离控制和可见激光设置
/// </summary>
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();
}
/// <summary>
/// 更新UI显示
/// </summary>
private void UpdateUI()
{
// 更新距离文本
UpdateLensText();
// 更新lens图标位置
UpdateLensIconPosition();
// 更新可见激光开关图标
UpdateVllButton();
// 更新选择器值
UpdateSlideSelectorValue();
}
/// <summary>
/// 更新距离文本显示
/// </summary>
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";
}
}
/// <summary>
/// 更新lens图标位置
/// </summary>
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;
}
/// <summary>
/// 更新滑动选择器的值
/// </summary>
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();
}
}
}
/// <summary>
/// 更新单位UI显示
/// </summary>
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);
}
}
/// <summary>
/// 更新可见激光开关按钮
/// </summary>
private void UpdateVllButton()
{
if (vllButton == null || vllButtonSprites == null || vllButtonSprites.Length < 2)
return;
Image buttonImage = vllButton.GetComponent<Image>();
if (buttonImage != null)
{
buttonImage.sprite = vllEnabled ? vllButtonSprites[1] : vllButtonSprites[0];
}
}
/// <summary>
/// 滑动选择器值改变回调(滑动过程中实时更新)
/// </summary>
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();
}
/// <summary>
/// 滑动选择器选中值回调(滑动结束后)
/// </summary>
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();
}
});
});
}
}
/// <summary>
/// 可见激光开关按钮点击事件
/// </summary>
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] 可见激光设置失败");
}
});
});
}
}
/// <summary>
/// 切换单位按钮点击事件
/// </summary>
private void OnSwitchUnitButtonClick()
{
// 切换单位
nowUnit = (nowUnit == 0) ? 1 : 0;
// 保存单位设置
DataManager.Instance.userInfo.unit_system = nowUnit;
// 更新UI
UpdateUnitUI();
UpdateLensText();
UpdateSlideSelectorValue();
Debug.Log($"[LensSettingPage] 切换单位: {(nowUnit == 0 ? "" : "")}");
}
/// <summary>
/// 确认按钮点击事件
/// </summary>
private async void OnConfirmButtonClick()
{
Debug.Log($"[LensSettingPage] 确认设置,当前距离={selectedLensValue}m");
// 同步单位设置到服务器
await UpdateUnitSystemToServer();
// 通知主页刷新
NotifyHomePageRefresh();
// 关闭页面
ClosePage();
}
/// <summary>
/// 同步单位设置到服务器
/// </summary>
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<NoDataResponse>("/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}");
}
}
/// <summary>
/// 取消按钮点击事件 - 恢复原始数值
/// </summary>
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();
});
});
}
}
/// <summary>
/// 通知主页刷新
/// </summary>
private void NotifyHomePageRefresh()
{
// 通知主页刷新距离显示
HomePageCtrl.Instance?.RefreshLensControl();
}
/// <summary>
/// 关闭页面
/// </summary>
private void ClosePage()
{
LoadingUI.Hide();
// 注销蓝牙回调(恢复主页)
UnregisterBluetoothCallbacks();
// 通知主页刷新
NotifyHomePageRefresh();
Destroy(gameObject);
// 清除UIManager返回事件
UIManager.Instance?.ClearBackAction();
}
}
}