4958 lines
174 KiB
C#
4958 lines
174 KiB
C#
using UnityEngine;
|
||
using UnityEngine.UI;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using TMPro;
|
||
using BLEProtocol;
|
||
|
||
/// <summary>
|
||
/// 蓝牙演示UI - 展示如何使用BluetoothManager和BLE通信
|
||
/// </summary>
|
||
public class BluetoothDemoUI : MonoBehaviour
|
||
{
|
||
[Header("UI组件 - 蓝牙连接")]
|
||
public TextMeshProUGUI StatusText; // 状态文本
|
||
public TextMeshProUGUI deviceStatusText;
|
||
|
||
[Header("UI组件 - BLE协议测试")]
|
||
public TextMeshProUGUI revicedText; // 显示收发原始数据
|
||
public Button QueryRegistrationButton; // 查询注册状态按钮
|
||
public Button RegisterDeviceButton; // 注册设备按钮
|
||
public Button UserLoginButton; // 用户登录按钮
|
||
public Button QueryUserListButton; // 查询用户列表按钮
|
||
public Button UnregisterUserButton; // 注销用户按钮
|
||
public Button FingerprintEnableButton; // 指纹使能设置按钮
|
||
public Button FingerprintRecordButton; // 指纹录制按钮
|
||
public TMP_InputField UsernameInput; // 用户名输入
|
||
public Toggle FingerprintEnableToggle; // 指纹使能开关
|
||
|
||
[Header("UI组件 - 设备设置")]
|
||
public TMP_InputField SettingsInputField; // 设置输入/展示框(语言/时间/定时任务共用)
|
||
public Button ReadLanguageButton; // 读取语言按钮
|
||
public Button WriteLanguageButton; // 写入语言按钮
|
||
public Toggle LanguageToggle; // 语言开关(true=中文, false=英文)
|
||
public Button ReadTimeButton; // 读取时间按钮
|
||
public Button WriteTimeButton; // 写入时间按钮
|
||
public Button ReadScheduleButton; // 读取定时任务按钮
|
||
public Button WriteScheduleButton; // 写入定时任务按钮
|
||
|
||
[Header("UI组件 - 外设控制")]
|
||
public TMP_InputField PeripheralInputField; // 外设控制输入/展示框
|
||
public Button ReadLCDSleepButton; // 读取LCD休眠设置按钮
|
||
public Button WriteLCDSleepButton; // 写入LCD休眠设置按钮
|
||
public Button ReadLCDBrightnessButton; // 读取LCD亮度设置按钮
|
||
public Button WriteLCDBrightnessButton; // 写入LCD亮度设置按钮
|
||
public Button ReadRGBButton; // 读取RGB控制按钮
|
||
public Button WriteRGBButton; // 写入RGB控制按钮
|
||
public Button ReadWIFIButton; // 读取WIFI控制按钮
|
||
public Button WriteWIFIButton; // 写入WIFI控制按钮
|
||
public Button ReadBLEButton; // 读取BLE控制按钮
|
||
public Button WriteBLEButton; // 写入BLE控制按钮
|
||
public Button ReadMultimediaButton; // 读取多媒体控制按钮
|
||
public Button WriteMultimediaButton; // 写入多媒体控制按钮
|
||
public Button ReadFillLightButton; // 读取补光灯控制按钮
|
||
public Button WriteFillLightButton; // 写入补光灯控制按钮
|
||
public Button ReadVisibleLaserButton; // 读取可见光激光器控制按钮
|
||
public Button WriteVisibleLaserButton; // 写入可见光激光器控制按钮
|
||
public Button ReadFillLightConnectionButton; // 读取补光灯连接状态按钮
|
||
|
||
[Header("UI组件 - 害虫消灭控制")]
|
||
public TMP_InputField PestControlInputField; // 害虫控制输入/展示框
|
||
public Button ReadAngleButton; // 读取角度控制按钮
|
||
public Button WriteAngleButton; // 写入角度控制按钮
|
||
public Button ReadDistanceButton; // 读取距离控制按钮
|
||
public Button WriteDistanceButton; // 写入距离控制按钮
|
||
|
||
[Header("UI组件 - 安全设置")]
|
||
public TMP_InputField SafetySettingInputField; // 安全设置输入/展示框
|
||
public Button ReadMillimeterWaveButton; // 读取毫米波雷达设置按钮
|
||
public Button WriteMillimeterWaveButton; // 写入毫米波雷达设置按钮
|
||
public Button ReadVisualDetectionButton; // 读取视觉检测设置按钮
|
||
public Button WriteVisualDetectionButton; // 写入视觉检测设置按钮
|
||
public Button ReadAccelerometerSettingButton; // 读取加速度传感器设置按钮
|
||
public Button WriteAccelerometerSettingButton; // 写入加速度传感器设置按钮
|
||
public Button ReadAccelerometerDataButton; // 读取加速度传感器数据按钮
|
||
public Button ReadTemperatureMonitorButton; // 读取温度监控设置按钮
|
||
public Button WriteTemperatureMonitorButton; // 写入温度监控设置按钮
|
||
public Button ReadEnvironmentChangeButton; // 读取环境变化状态按钮 (0x56)
|
||
public Button TriggerLaserTestButton; // 触发激光试射测试按钮 (0x56)
|
||
|
||
[Header("UI组件 - 状态查询")]
|
||
public TMP_InputField StatusQueryInputField; // 状态查询输入/展示框
|
||
public Button ReadWorkModeButton; // 读取工作模式按钮
|
||
public Button WriteWorkModeButton; // 写入工作模式按钮
|
||
public Button ReadHardwareStatusButton; // 读取硬件状态按钮
|
||
public Button ReadDeviceInfoButton; // 读取设备信息按钮
|
||
public Button WriteDeviceInfoButton; // 写入设备信息按钮
|
||
public Button ReadStatisticsButton; // 读取统计数据按钮
|
||
public Button QueryMosquitoDataButton; // 查询蚊虫数据按钮 (0xA4)
|
||
public Button ReadSensorDataButton; // 读取传感器数据按钮
|
||
public Button GetAllMosquitoDataButton; // 获取所有蚊虫数据按钮 (0xA4)
|
||
|
||
[Header("UI组件 - 蚊虫数据显示")]
|
||
public TextMeshProUGUI MosquitoDataDisplay; // 蚊虫数据显示区域
|
||
|
||
[Header("UI组件 - 设备管理")]
|
||
public Button FactoryResetButton; // 恢复出厂设置按钮 (0x60)
|
||
|
||
[Header("UI组件 - OTA升级")]
|
||
public Button OTAQueryVersionButton; // 查询OTA版本按钮 (0x80)
|
||
public Button OTAStartUpgradeButton; // 开始OTA升级按钮 (0x81)
|
||
public Button OTACancelUpgradeButton; // 取消OTA升级按钮 (0x85)
|
||
public Button OTASelectFileButton; // 选择固件文件按钮
|
||
public TextMeshProUGUI OTAInfoText; // OTA信息显示(文件信息、状态、进度)
|
||
|
||
// 选中的固件文件数据
|
||
private byte[] _selectedFirmwareData;
|
||
private string _selectedFirmwarePath;
|
||
|
||
List<GameObject> _deviceObjects = new List<GameObject>();
|
||
private List<MosquitoData> _mosquitoDataList = new List<MosquitoData>(); // 存储接收到的蚊虫数据
|
||
private List<BluetoothDevice> _deviceList = new List<BluetoothDevice>();
|
||
void Awake()
|
||
{
|
||
// 设置目标帧率为 60 FPS
|
||
Application.targetFrameRate = 120;
|
||
|
||
// 禁用垂直同步,允许更高帧率
|
||
QualitySettings.vSyncCount = 0;
|
||
|
||
// 不休眠(保持屏幕常亮)
|
||
Screen.sleepTimeout = SleepTimeout.NeverSleep;
|
||
}
|
||
void Start()
|
||
{
|
||
// 订阅蓝牙管理器事件
|
||
if (BluetoothManager.Instance != null)
|
||
{
|
||
BluetoothManager.Instance.OnInitialized += OnBluetoothInitialized;
|
||
BluetoothManager.Instance.OnDeviceFound += OnDeviceFound;
|
||
BluetoothManager.Instance.OnConnected += OnDeviceConnected;
|
||
BluetoothManager.Instance.OnConnectFailed += OnConnectFailed;
|
||
BluetoothManager.Instance.OnDisconnected += OnDeviceDisconnected;
|
||
BluetoothManager.Instance.OnError += OnBluetoothError;
|
||
BluetoothManager.Instance.OnLog += OnBluetoothLog;
|
||
}
|
||
|
||
// 订阅BLE通信事件
|
||
if (BLECommunicationManager.Instance != null)
|
||
{
|
||
BLECommunicationManager.Instance.OnRegistrationStatusReceived += OnRegistrationStatusReceived;
|
||
BLECommunicationManager.Instance.OnRegisterResult += OnRegisterResult;
|
||
BLECommunicationManager.Instance.OnUserLoginResult += OnUserLoginResult;
|
||
BLECommunicationManager.Instance.OnUserListReceived += OnUserListReceived;
|
||
BLECommunicationManager.Instance.OnUnregisterUserResult += OnUnregisterUserResult;
|
||
BLECommunicationManager.Instance.OnFingerprintEnableResult += OnFingerprintEnableResult;
|
||
BLECommunicationManager.Instance.OnFingerprintRecordResult += OnFingerprintRecordResult;
|
||
BLECommunicationManager.Instance.OnRawDataReceived += OnRawDataReceived;
|
||
BLECommunicationManager.Instance.OnRawDataSent += OnRawDataSent;
|
||
BLECommunicationManager.Instance.OnCommunicationError += OnCommunicationError;
|
||
BLECommunicationManager.Instance.OnLanguageSettingReceived += OnLanguageSettingReceived;
|
||
BLECommunicationManager.Instance.OnTimeSettingReceived += OnTimeSettingReceived;
|
||
BLECommunicationManager.Instance.OnScheduleTaskListReceived += OnScheduleTaskListReceived;
|
||
BLECommunicationManager.Instance.OnLCDSleepSettingReceived += OnLCDSleepSettingReceived;
|
||
BLECommunicationManager.Instance.OnLCDBrightnessSettingReceived += OnLCDBrightnessSettingReceived;
|
||
BLECommunicationManager.Instance.OnRGBControlReceived += OnRGBControlReceived;
|
||
BLECommunicationManager.Instance.OnWIFIControlReceived += OnWIFIControlReceived;
|
||
BLECommunicationManager.Instance.OnBLEControlReceived += OnBLEControlReceived;
|
||
BLECommunicationManager.Instance.OnMultimediaControlReceived += OnMultimediaControlReceived;
|
||
BLECommunicationManager.Instance.OnFillLightControlReceived += OnFillLightControlReceived;
|
||
BLECommunicationManager.Instance.OnFillLightConnectionStatusReceived += OnFillLightConnectionStatusReceived;
|
||
BLECommunicationManager.Instance.OnVisibleLaserControlReceived += OnVisibleLaserControlReceived;
|
||
|
||
// 订阅害虫消灭控制事件
|
||
BLECommunicationManager.Instance.OnAngleControlReceived += OnAngleControlReceived;
|
||
BLECommunicationManager.Instance.OnDistanceControlReceived += OnDistanceControlReceived;
|
||
|
||
// 订阅安全设置事件
|
||
BLECommunicationManager.Instance.OnMillimeterWaveSettingReceived += OnMillimeterWaveSettingReceived;
|
||
BLECommunicationManager.Instance.OnVisualDetectionSettingReceived += OnVisualDetectionSettingReceived;
|
||
BLECommunicationManager.Instance.OnAccelerometerSettingReceived += OnAccelerometerSettingReceived;
|
||
BLECommunicationManager.Instance.OnAccelerometerDataReceived += OnAccelerometerDataReceived;
|
||
BLECommunicationManager.Instance.OnTemperatureMonitorSettingReceived += OnTemperatureMonitorSettingReceived;
|
||
|
||
// 订阅环境检测事件
|
||
BLECommunicationManager.Instance.OnEnvironmentChangeStatusReceived += OnEnvironmentChangeStatusReceived;
|
||
|
||
// 订阅状态查询事件
|
||
BLECommunicationManager.Instance.OnWorkModeSettingReceived += OnWorkModeSettingReceived;
|
||
BLECommunicationManager.Instance.OnHardwareStatusReceived += OnHardwareStatusReceived;
|
||
BLECommunicationManager.Instance.OnDeviceInfoReceived += OnDeviceInfoReceived;
|
||
BLECommunicationManager.Instance.OnStatisticsDataReceived += OnStatisticsDataReceived;
|
||
BLECommunicationManager.Instance.OnSensorDataReceived += OnSensorDataReceived;
|
||
|
||
// 订阅蚊虫数据事件
|
||
BLECommunicationManager.Instance.OnMosquitoDataReceived += OnMosquitoDataReceived;
|
||
}
|
||
|
||
// 绑定BLE测试按钮
|
||
if (QueryRegistrationButton != null)
|
||
QueryRegistrationButton.onClick.AddListener(OnQueryRegistrationClick);
|
||
if (RegisterDeviceButton != null)
|
||
RegisterDeviceButton.onClick.AddListener(OnRegisterDeviceClick);
|
||
if (UserLoginButton != null)
|
||
UserLoginButton.onClick.AddListener(OnUserLoginClick);
|
||
if (QueryUserListButton != null)
|
||
QueryUserListButton.onClick.AddListener(OnQueryUserListClick);
|
||
if (UnregisterUserButton != null)
|
||
UnregisterUserButton.onClick.AddListener(OnUnregisterUserClick);
|
||
if (FingerprintEnableButton != null)
|
||
FingerprintEnableButton.onClick.AddListener(OnFingerprintEnableClick);
|
||
if (FingerprintRecordButton != null)
|
||
FingerprintRecordButton.onClick.AddListener(OnFingerprintRecordClick);
|
||
|
||
// 绑定设备设置按钮
|
||
if (ReadLanguageButton != null)
|
||
ReadLanguageButton.onClick.AddListener(OnReadLanguageClick);
|
||
if (WriteLanguageButton != null)
|
||
WriteLanguageButton.onClick.AddListener(OnWriteLanguageClick);
|
||
if (ReadTimeButton != null)
|
||
ReadTimeButton.onClick.AddListener(OnReadTimeClick);
|
||
if (WriteTimeButton != null)
|
||
WriteTimeButton.onClick.AddListener(OnWriteTimeClick);
|
||
if (ReadScheduleButton != null)
|
||
ReadScheduleButton.onClick.AddListener(OnReadScheduleClick);
|
||
if (WriteScheduleButton != null)
|
||
WriteScheduleButton.onClick.AddListener(OnWriteScheduleClick);
|
||
|
||
// 绑定外设控制按钮
|
||
if (ReadLCDSleepButton != null)
|
||
ReadLCDSleepButton.onClick.AddListener(OnReadLCDSleepClick);
|
||
if (WriteLCDSleepButton != null)
|
||
WriteLCDSleepButton.onClick.AddListener(OnWriteLCDSleepClick);
|
||
if (ReadLCDBrightnessButton != null)
|
||
ReadLCDBrightnessButton.onClick.AddListener(OnReadLCDBrightnessClick);
|
||
if (WriteLCDBrightnessButton != null)
|
||
WriteLCDBrightnessButton.onClick.AddListener(OnWriteLCDBrightnessClick);
|
||
if (ReadRGBButton != null)
|
||
ReadRGBButton.onClick.AddListener(OnReadRGBClick);
|
||
if (WriteRGBButton != null)
|
||
WriteRGBButton.onClick.AddListener(OnWriteRGBClick);
|
||
if (ReadWIFIButton != null)
|
||
ReadWIFIButton.onClick.AddListener(OnReadWIFIClick);
|
||
if (WriteWIFIButton != null)
|
||
WriteWIFIButton.onClick.AddListener(OnWriteWIFIClick);
|
||
if (ReadBLEButton != null)
|
||
ReadBLEButton.onClick.AddListener(OnReadBLEClick);
|
||
if (WriteBLEButton != null)
|
||
WriteBLEButton.onClick.AddListener(OnWriteBLEClick);
|
||
if (ReadMultimediaButton != null)
|
||
ReadMultimediaButton.onClick.AddListener(OnReadMultimediaClick);
|
||
if (WriteMultimediaButton != null)
|
||
WriteMultimediaButton.onClick.AddListener(OnWriteMultimediaClick);
|
||
if (ReadFillLightButton != null)
|
||
ReadFillLightButton.onClick.AddListener(OnReadFillLightClick);
|
||
if (WriteFillLightButton != null)
|
||
WriteFillLightButton.onClick.AddListener(OnWriteFillLightClick);
|
||
if (ReadVisibleLaserButton != null)
|
||
ReadVisibleLaserButton.onClick.AddListener(OnReadVisibleLaserClick);
|
||
if (WriteVisibleLaserButton != null)
|
||
WriteVisibleLaserButton.onClick.AddListener(OnWriteVisibleLaserClick);
|
||
if (ReadFillLightConnectionButton != null)
|
||
ReadFillLightConnectionButton.onClick.AddListener(OnReadFillLightConnectionClick);
|
||
|
||
// 绑定害虫消灭控制按钮
|
||
if (ReadAngleButton != null)
|
||
ReadAngleButton.onClick.AddListener(OnReadAngleClick);
|
||
if (WriteAngleButton != null)
|
||
WriteAngleButton.onClick.AddListener(OnWriteAngleClick);
|
||
if (ReadDistanceButton != null)
|
||
ReadDistanceButton.onClick.AddListener(OnReadDistanceClick);
|
||
if (WriteDistanceButton != null)
|
||
WriteDistanceButton.onClick.AddListener(OnWriteDistanceClick);
|
||
|
||
// 绑定安全设置按钮
|
||
if (ReadMillimeterWaveButton != null)
|
||
ReadMillimeterWaveButton.onClick.AddListener(OnReadMillimeterWaveClick);
|
||
if (WriteMillimeterWaveButton != null)
|
||
WriteMillimeterWaveButton.onClick.AddListener(OnWriteMillimeterWaveClick);
|
||
if (ReadVisualDetectionButton != null)
|
||
ReadVisualDetectionButton.onClick.AddListener(OnReadVisualDetectionClick);
|
||
if (WriteVisualDetectionButton != null)
|
||
WriteVisualDetectionButton.onClick.AddListener(OnWriteVisualDetectionClick);
|
||
if (ReadAccelerometerSettingButton != null)
|
||
ReadAccelerometerSettingButton.onClick.AddListener(OnReadAccelerometerSettingClick);
|
||
if (WriteAccelerometerSettingButton != null)
|
||
WriteAccelerometerSettingButton.onClick.AddListener(OnWriteAccelerometerSettingClick);
|
||
if (ReadAccelerometerDataButton != null)
|
||
ReadAccelerometerDataButton.onClick.AddListener(OnReadAccelerometerDataClick);
|
||
if (ReadTemperatureMonitorButton != null)
|
||
ReadTemperatureMonitorButton.onClick.AddListener(OnReadTemperatureMonitorClick);
|
||
if (WriteTemperatureMonitorButton != null)
|
||
WriteTemperatureMonitorButton.onClick.AddListener(OnWriteTemperatureMonitorClick);
|
||
|
||
// 绑定环境检测按钮
|
||
if (ReadEnvironmentChangeButton != null)
|
||
ReadEnvironmentChangeButton.onClick.AddListener(OnReadEnvironmentChangeClick);
|
||
if (TriggerLaserTestButton != null)
|
||
TriggerLaserTestButton.onClick.AddListener(OnTriggerLaserTestClick);
|
||
|
||
// 绑定状态查询按钮
|
||
if (ReadWorkModeButton != null)
|
||
ReadWorkModeButton.onClick.AddListener(OnReadWorkModeClick);
|
||
if (WriteWorkModeButton != null)
|
||
WriteWorkModeButton.onClick.AddListener(OnWriteWorkModeClick);
|
||
if (ReadHardwareStatusButton != null)
|
||
ReadHardwareStatusButton.onClick.AddListener(OnReadHardwareStatusClick);
|
||
if (ReadDeviceInfoButton != null)
|
||
ReadDeviceInfoButton.onClick.AddListener(OnReadDeviceInfoClick);
|
||
if (WriteDeviceInfoButton != null)
|
||
WriteDeviceInfoButton.onClick.AddListener(OnWriteDeviceInfoClick);
|
||
if (ReadStatisticsButton != null)
|
||
ReadStatisticsButton.onClick.AddListener(OnReadStatisticsClick);
|
||
if (QueryMosquitoDataButton != null)
|
||
QueryMosquitoDataButton.onClick.AddListener(OnQueryMosquitoDataClick);
|
||
if (ReadSensorDataButton != null)
|
||
ReadSensorDataButton.onClick.AddListener(OnReadSensorDataClick);
|
||
|
||
// 绑定蚊虫数据按钮
|
||
if (GetAllMosquitoDataButton != null)
|
||
GetAllMosquitoDataButton.onClick.AddListener(OnGetAllMosquitoDataClick);
|
||
|
||
// 绑定设备管理按钮
|
||
if (FactoryResetButton != null)
|
||
FactoryResetButton.onClick.AddListener(OnFactoryResetClick);
|
||
|
||
// 绑定OTA升级按钮
|
||
if (OTAQueryVersionButton != null)
|
||
OTAQueryVersionButton.onClick.AddListener(OnOTAQueryVersionClick);
|
||
if (OTAStartUpgradeButton != null)
|
||
OTAStartUpgradeButton.onClick.AddListener(OnOTAStartUpgradeClick);
|
||
if (OTACancelUpgradeButton != null)
|
||
OTACancelUpgradeButton.onClick.AddListener(OnOTACancelUpgradeClick);
|
||
if (OTASelectFileButton != null)
|
||
OTASelectFileButton.onClick.AddListener(OnOTASelectFileClick);
|
||
|
||
// 订阅OTA事件
|
||
if (OTAManager.Instance != null)
|
||
{
|
||
OTAManager.Instance.OnVersionInfoReceived += OnOTAVersionInfoReceived;
|
||
OTAManager.Instance.OnTransferProgress += OnOTATransferProgress;
|
||
OTAManager.Instance.OnStateChanged += OnOTAStateChanged;
|
||
OTAManager.Instance.OnError += OnOTAError;
|
||
}
|
||
|
||
UpdateStatus("等待初始化...");
|
||
if (deviceStatusText != null)
|
||
deviceStatusText.text = "未连接";
|
||
OnInitializeClick();
|
||
}
|
||
|
||
void OnDestroy()
|
||
{
|
||
// 取消订阅蓝牙事件
|
||
if (BluetoothManager.Instance != null)
|
||
{
|
||
BluetoothManager.Instance.OnInitialized -= OnBluetoothInitialized;
|
||
BluetoothManager.Instance.OnDeviceFound -= OnDeviceFound;
|
||
BluetoothManager.Instance.OnConnected -= OnDeviceConnected;
|
||
BluetoothManager.Instance.OnConnectFailed -= OnConnectFailed;
|
||
BluetoothManager.Instance.OnDisconnected -= OnDeviceDisconnected;
|
||
BluetoothManager.Instance.OnError -= OnBluetoothError;
|
||
BluetoothManager.Instance.OnLog -= OnBluetoothLog;
|
||
}
|
||
|
||
// 取消订阅BLE事件
|
||
if (BLECommunicationManager.Instance != null)
|
||
{
|
||
BLECommunicationManager.Instance.OnRegistrationStatusReceived -= OnRegistrationStatusReceived;
|
||
BLECommunicationManager.Instance.OnRegisterResult -= OnRegisterResult;
|
||
BLECommunicationManager.Instance.OnUserLoginResult -= OnUserLoginResult;
|
||
BLECommunicationManager.Instance.OnUserListReceived -= OnUserListReceived;
|
||
BLECommunicationManager.Instance.OnUnregisterUserResult -= OnUnregisterUserResult;
|
||
BLECommunicationManager.Instance.OnFingerprintEnableResult -= OnFingerprintEnableResult;
|
||
BLECommunicationManager.Instance.OnFingerprintRecordResult -= OnFingerprintRecordResult;
|
||
BLECommunicationManager.Instance.OnRawDataReceived -= OnRawDataReceived;
|
||
BLECommunicationManager.Instance.OnRawDataSent -= OnRawDataSent;
|
||
BLECommunicationManager.Instance.OnCommunicationError -= OnCommunicationError;
|
||
BLECommunicationManager.Instance.OnLanguageSettingReceived -= OnLanguageSettingReceived;
|
||
BLECommunicationManager.Instance.OnTimeSettingReceived -= OnTimeSettingReceived;
|
||
BLECommunicationManager.Instance.OnScheduleTaskListReceived -= OnScheduleTaskListReceived;
|
||
BLECommunicationManager.Instance.OnLCDSleepSettingReceived -= OnLCDSleepSettingReceived;
|
||
BLECommunicationManager.Instance.OnLCDBrightnessSettingReceived -= OnLCDBrightnessSettingReceived;
|
||
BLECommunicationManager.Instance.OnRGBControlReceived -= OnRGBControlReceived;
|
||
BLECommunicationManager.Instance.OnWIFIControlReceived -= OnWIFIControlReceived;
|
||
BLECommunicationManager.Instance.OnBLEControlReceived -= OnBLEControlReceived;
|
||
BLECommunicationManager.Instance.OnMultimediaControlReceived -= OnMultimediaControlReceived;
|
||
BLECommunicationManager.Instance.OnFillLightControlReceived -= OnFillLightControlReceived;
|
||
BLECommunicationManager.Instance.OnFillLightConnectionStatusReceived -= OnFillLightConnectionStatusReceived;
|
||
BLECommunicationManager.Instance.OnVisibleLaserControlReceived -= OnVisibleLaserControlReceived;
|
||
|
||
// 取消订阅害虫消灭控制事件
|
||
BLECommunicationManager.Instance.OnAngleControlReceived -= OnAngleControlReceived;
|
||
BLECommunicationManager.Instance.OnDistanceControlReceived -= OnDistanceControlReceived;
|
||
|
||
// 取消订阅安全设置事件
|
||
BLECommunicationManager.Instance.OnMillimeterWaveSettingReceived -= OnMillimeterWaveSettingReceived;
|
||
BLECommunicationManager.Instance.OnVisualDetectionSettingReceived -= OnVisualDetectionSettingReceived;
|
||
BLECommunicationManager.Instance.OnAccelerometerSettingReceived -= OnAccelerometerSettingReceived;
|
||
BLECommunicationManager.Instance.OnAccelerometerDataReceived -= OnAccelerometerDataReceived;
|
||
BLECommunicationManager.Instance.OnTemperatureMonitorSettingReceived -= OnTemperatureMonitorSettingReceived;
|
||
|
||
// 取消订阅环境检测事件
|
||
BLECommunicationManager.Instance.OnEnvironmentChangeStatusReceived -= OnEnvironmentChangeStatusReceived;
|
||
|
||
// 取消订阅状态查询事件
|
||
BLECommunicationManager.Instance.OnWorkModeSettingReceived -= OnWorkModeSettingReceived;
|
||
BLECommunicationManager.Instance.OnHardwareStatusReceived -= OnHardwareStatusReceived;
|
||
BLECommunicationManager.Instance.OnDeviceInfoReceived -= OnDeviceInfoReceived;
|
||
BLECommunicationManager.Instance.OnStatisticsDataReceived -= OnStatisticsDataReceived;
|
||
BLECommunicationManager.Instance.OnSensorDataReceived -= OnSensorDataReceived;
|
||
|
||
// 取消订阅蚊虫数据事件
|
||
BLECommunicationManager.Instance.OnMosquitoDataReceived -= OnMosquitoDataReceived;
|
||
}
|
||
|
||
// 取消按钮绑定
|
||
if (QueryRegistrationButton != null)
|
||
QueryRegistrationButton.onClick.RemoveListener(OnQueryRegistrationClick);
|
||
if (RegisterDeviceButton != null)
|
||
RegisterDeviceButton.onClick.RemoveListener(OnRegisterDeviceClick);
|
||
if (UserLoginButton != null)
|
||
UserLoginButton.onClick.RemoveListener(OnUserLoginClick);
|
||
if (QueryUserListButton != null)
|
||
QueryUserListButton.onClick.RemoveListener(OnQueryUserListClick);
|
||
if (UnregisterUserButton != null)
|
||
UnregisterUserButton.onClick.RemoveListener(OnUnregisterUserClick);
|
||
if (FingerprintEnableButton != null)
|
||
FingerprintEnableButton.onClick.RemoveListener(OnFingerprintEnableClick);
|
||
if (FingerprintRecordButton != null)
|
||
FingerprintRecordButton.onClick.RemoveListener(OnFingerprintRecordClick);
|
||
|
||
// 取消设备设置按钮绑定
|
||
if (ReadLanguageButton != null)
|
||
ReadLanguageButton.onClick.RemoveListener(OnReadLanguageClick);
|
||
if (WriteLanguageButton != null)
|
||
WriteLanguageButton.onClick.RemoveListener(OnWriteLanguageClick);
|
||
if (ReadTimeButton != null)
|
||
ReadTimeButton.onClick.RemoveListener(OnReadTimeClick);
|
||
if (WriteTimeButton != null)
|
||
WriteTimeButton.onClick.RemoveListener(OnWriteTimeClick);
|
||
if (ReadScheduleButton != null)
|
||
ReadScheduleButton.onClick.RemoveListener(OnReadScheduleClick);
|
||
if (WriteScheduleButton != null)
|
||
WriteScheduleButton.onClick.RemoveListener(OnWriteScheduleClick);
|
||
|
||
// 取消外设控制按钮绑定
|
||
if (ReadLCDSleepButton != null)
|
||
ReadLCDSleepButton.onClick.RemoveListener(OnReadLCDSleepClick);
|
||
if (WriteLCDSleepButton != null)
|
||
WriteLCDSleepButton.onClick.RemoveListener(OnWriteLCDSleepClick);
|
||
if (ReadLCDBrightnessButton != null)
|
||
ReadLCDBrightnessButton.onClick.RemoveListener(OnReadLCDBrightnessClick);
|
||
if (WriteLCDBrightnessButton != null)
|
||
WriteLCDBrightnessButton.onClick.RemoveListener(OnWriteLCDBrightnessClick);
|
||
if (ReadRGBButton != null)
|
||
ReadRGBButton.onClick.RemoveListener(OnReadRGBClick);
|
||
if (WriteRGBButton != null)
|
||
WriteRGBButton.onClick.RemoveListener(OnWriteRGBClick);
|
||
if (ReadWIFIButton != null)
|
||
ReadWIFIButton.onClick.RemoveListener(OnReadWIFIClick);
|
||
if (WriteWIFIButton != null)
|
||
WriteWIFIButton.onClick.RemoveListener(OnWriteWIFIClick);
|
||
if (ReadBLEButton != null)
|
||
ReadBLEButton.onClick.RemoveListener(OnReadBLEClick);
|
||
if (WriteBLEButton != null)
|
||
WriteBLEButton.onClick.RemoveListener(OnWriteBLEClick);
|
||
if (ReadMultimediaButton != null)
|
||
ReadMultimediaButton.onClick.RemoveListener(OnReadMultimediaClick);
|
||
if (WriteMultimediaButton != null)
|
||
WriteMultimediaButton.onClick.RemoveListener(OnWriteMultimediaClick);
|
||
if (ReadFillLightButton != null)
|
||
ReadFillLightButton.onClick.RemoveListener(OnReadFillLightClick);
|
||
if (WriteFillLightButton != null)
|
||
WriteFillLightButton.onClick.RemoveListener(OnWriteFillLightClick);
|
||
if (ReadVisibleLaserButton != null)
|
||
ReadVisibleLaserButton.onClick.RemoveListener(OnReadVisibleLaserClick);
|
||
if (WriteVisibleLaserButton != null)
|
||
WriteVisibleLaserButton.onClick.RemoveListener(OnWriteVisibleLaserClick);
|
||
if (ReadFillLightConnectionButton != null)
|
||
ReadFillLightConnectionButton.onClick.RemoveListener(OnReadFillLightConnectionClick);
|
||
|
||
// 取消害虫消灭控制按钮绑定
|
||
if (ReadAngleButton != null)
|
||
ReadAngleButton.onClick.RemoveListener(OnReadAngleClick);
|
||
if (WriteAngleButton != null)
|
||
WriteAngleButton.onClick.RemoveListener(OnWriteAngleClick);
|
||
if (ReadDistanceButton != null)
|
||
ReadDistanceButton.onClick.RemoveListener(OnReadDistanceClick);
|
||
if (WriteDistanceButton != null)
|
||
WriteDistanceButton.onClick.RemoveListener(OnWriteDistanceClick);
|
||
|
||
// 取消安全设置按钮绑定
|
||
if (ReadMillimeterWaveButton != null)
|
||
ReadMillimeterWaveButton.onClick.RemoveListener(OnReadMillimeterWaveClick);
|
||
if (WriteMillimeterWaveButton != null)
|
||
WriteMillimeterWaveButton.onClick.RemoveListener(OnWriteMillimeterWaveClick);
|
||
if (ReadVisualDetectionButton != null)
|
||
ReadVisualDetectionButton.onClick.RemoveListener(OnReadVisualDetectionClick);
|
||
if (WriteVisualDetectionButton != null)
|
||
WriteVisualDetectionButton.onClick.RemoveListener(OnWriteVisualDetectionClick);
|
||
if (ReadAccelerometerSettingButton != null)
|
||
ReadAccelerometerSettingButton.onClick.RemoveListener(OnReadAccelerometerSettingClick);
|
||
if (WriteAccelerometerSettingButton != null)
|
||
WriteAccelerometerSettingButton.onClick.RemoveListener(OnWriteAccelerometerSettingClick);
|
||
if (ReadAccelerometerDataButton != null)
|
||
ReadAccelerometerDataButton.onClick.RemoveListener(OnReadAccelerometerDataClick);
|
||
if (ReadTemperatureMonitorButton != null)
|
||
ReadTemperatureMonitorButton.onClick.RemoveListener(OnReadTemperatureMonitorClick);
|
||
if (WriteTemperatureMonitorButton != null)
|
||
WriteTemperatureMonitorButton.onClick.RemoveListener(OnWriteTemperatureMonitorClick);
|
||
|
||
// 取消环境检测按钮绑定
|
||
if (ReadEnvironmentChangeButton != null)
|
||
ReadEnvironmentChangeButton.onClick.RemoveListener(OnReadEnvironmentChangeClick);
|
||
if (TriggerLaserTestButton != null)
|
||
TriggerLaserTestButton.onClick.RemoveListener(OnTriggerLaserTestClick);
|
||
|
||
// 取消状态查询按钮绑定
|
||
if (ReadWorkModeButton != null)
|
||
ReadWorkModeButton.onClick.RemoveListener(OnReadWorkModeClick);
|
||
if (WriteWorkModeButton != null)
|
||
WriteWorkModeButton.onClick.RemoveListener(OnWriteWorkModeClick);
|
||
if (ReadHardwareStatusButton != null)
|
||
ReadHardwareStatusButton.onClick.RemoveListener(OnReadHardwareStatusClick);
|
||
if (ReadDeviceInfoButton != null)
|
||
ReadDeviceInfoButton.onClick.RemoveListener(OnReadDeviceInfoClick);
|
||
if (WriteDeviceInfoButton != null)
|
||
WriteDeviceInfoButton.onClick.RemoveListener(OnWriteDeviceInfoClick);
|
||
if (ReadStatisticsButton != null)
|
||
ReadStatisticsButton.onClick.RemoveListener(OnReadStatisticsClick);
|
||
if (QueryMosquitoDataButton != null)
|
||
QueryMosquitoDataButton.onClick.RemoveListener(OnQueryMosquitoDataClick);
|
||
if (ReadSensorDataButton != null)
|
||
ReadSensorDataButton.onClick.RemoveListener(OnReadSensorDataClick);
|
||
|
||
// 取消蚊虫数据按钮绑定
|
||
if (GetAllMosquitoDataButton != null)
|
||
GetAllMosquitoDataButton.onClick.RemoveListener(OnGetAllMosquitoDataClick);
|
||
|
||
// 取消设备管理按钮绑定
|
||
if (FactoryResetButton != null)
|
||
FactoryResetButton.onClick.RemoveListener(OnFactoryResetClick);
|
||
}
|
||
|
||
#region 蓝牙基础功能
|
||
|
||
/// <summary>
|
||
/// 初始化蓝牙
|
||
/// </summary>
|
||
private void OnInitializeClick()
|
||
{
|
||
if (BluetoothManager.Instance != null)
|
||
{
|
||
BluetoothManager.Instance.Initialize();
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 未找到BluetoothManager实例");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 开始扫描
|
||
/// </summary>
|
||
public void OnScanClick()
|
||
{
|
||
if (BluetoothManager.Instance != null)
|
||
{
|
||
// 清空列表
|
||
_deviceList.Clear();
|
||
if (_deviceObjects != null && _deviceObjects.Count > 0)
|
||
{
|
||
foreach (var item in _deviceObjects)
|
||
{
|
||
Destroy(item);
|
||
}
|
||
_deviceObjects.Clear();
|
||
}
|
||
_deviceObjects = new List<GameObject>();
|
||
BluetoothManager.Instance.StartScan(10f); // 扫描10秒
|
||
UpdateStatus("正在扫描设备...");
|
||
}
|
||
}
|
||
|
||
public GameObject deviceListParent;
|
||
public GameObject devicePrefab;
|
||
|
||
public void AddOneDevice(BluetoothDevice device)
|
||
{
|
||
if (_deviceList.Contains(device))
|
||
return;
|
||
GameObject deviceObject = Instantiate(devicePrefab, deviceListParent.transform);
|
||
deviceObject.GetComponent<DeviceUI>().Init(device);
|
||
_deviceObjects.Add(deviceObject);
|
||
int index = _deviceObjects.IndexOf(deviceObject);
|
||
deviceObject.GetComponent<Button>().onClick.AddListener(() => OnConnectClick(index));
|
||
_deviceList.Add(device);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 停止扫描
|
||
/// </summary>
|
||
public void OnStopScanClick()
|
||
{
|
||
if (BluetoothManager.Instance != null)
|
||
{
|
||
BluetoothManager.Instance.StopScan();
|
||
UpdateStatus("已停止扫描");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 连接设备
|
||
/// </summary>
|
||
private void OnConnectClick(int index)
|
||
{
|
||
if (BluetoothManager.Instance == null) return;
|
||
OnStopScanClick();
|
||
int selectedIndex = index;
|
||
if (selectedIndex >= 0 && selectedIndex < _deviceList.Count)
|
||
{
|
||
var device = _deviceList[selectedIndex];
|
||
UpdateStatus($"正在连接: {device.Name}...");
|
||
BluetoothManager.Instance.Connect(device.Address);
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("请先选择一个设备");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 断开连接
|
||
/// </summary>
|
||
public void OnDisconnectClick()
|
||
{
|
||
UpdateStatus("正在断开连接...");
|
||
|
||
// 直接调用蓝牙管理器的断开(已经包含了完整的断开和重置逻辑)
|
||
if (BluetoothManager.Instance != null)
|
||
{
|
||
BluetoothManager.Instance.Disconnect();
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: BluetoothManager 未初始化");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 重置蓝牙(解决断开后无法扫描的问题)
|
||
/// </summary>
|
||
public void OnResetBluetoothClick()
|
||
{
|
||
UpdateStatus("正在重置蓝牙...");
|
||
|
||
if (BluetoothManager.Instance != null)
|
||
{
|
||
BluetoothManager.Instance.ResetBluetooth();
|
||
UpdateStatus("蓝牙重置完成,请等待初始化完成后重新扫描");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: BluetoothManager 未初始化");
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region BLE协议测试功能
|
||
|
||
/// <summary>
|
||
/// 查询设备注册状态
|
||
/// </summary>
|
||
private void OnQueryRegistrationClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在查询设备注册状态...");
|
||
Log("发送查询注册状态命令 (0x01)");
|
||
|
||
BLECommunicationManager.Instance.QueryRegistrationStatus((status) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string regState = status.IsRegistered ? "已注册" : "未注册";
|
||
|
||
UpdateStatus($"查询完成: {regState}");
|
||
Log($"注册状态: {regState}");
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 注册设备
|
||
/// </summary>
|
||
private void OnRegisterDeviceClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
string username = UsernameInput != null ? UsernameInput.text.Trim() : "";
|
||
|
||
if (string.IsNullOrEmpty(username))
|
||
{
|
||
UpdateStatus("错误: 用户名不能为空");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在注册设备: {username}...");
|
||
Log($"发送注册命令 (0x02)");
|
||
Log($"用户名: {username}");
|
||
|
||
BLECommunicationManager.Instance.RegisterDevice(username, (success, message) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"注册成功: {message}");
|
||
Log($"注册成功!");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus($"注册失败: {message}");
|
||
Log($"注册失败: {message}");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 用户登录
|
||
/// </summary>
|
||
private void OnUserLoginClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
string username = UsernameInput != null ? UsernameInput.text.Trim() : "";
|
||
|
||
if (string.IsNullOrEmpty(username))
|
||
{
|
||
UpdateStatus("错误: 用户名不能为空");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在登录: {username}...");
|
||
Log($"发送用户登录命令 (0x03)");
|
||
Log($"用户名: {username}");
|
||
|
||
BLECommunicationManager.Instance.UserLogin(username, (response) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (response.IsSuccess)
|
||
{
|
||
UpdateStatus($"登录成功: {username}");
|
||
Log($"用户 {username} 登录成功!");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus($"登录失败: {username}, 状态码=0x{response.Status:X2}");
|
||
Log($"用户 {username} 登录失败, 状态码=0x{response.Status:X2}");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 查询用户列表
|
||
/// </summary>
|
||
private void OnQueryUserListClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在查询用户列表...");
|
||
Log("发送查询用户列表命令 (0x07)");
|
||
|
||
BLECommunicationManager.Instance.QueryUserList((response) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (response.IsSuccess)
|
||
{
|
||
string userListStr = $"用户数量: {response.UserCount}\n";
|
||
for (int i = 0; i < response.Users.Length; i++)
|
||
{
|
||
var user = response.Users[i];
|
||
string fpStatus = user.HasFingerprint ? $"有指纹(ID:{user.FingerprintId})" : "无指纹";
|
||
userListStr += $"{i + 1}. {user.Username} - {fpStatus}\n";
|
||
}
|
||
|
||
UpdateStatus($"查询完成: 共 {response.UserCount} 个用户\n{userListStr}");
|
||
Log($"用户列表:\n{userListStr}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("查询用户列表失败");
|
||
Log("查询用户列表失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 注销用户
|
||
/// </summary>
|
||
private void OnUnregisterUserClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
string username = UsernameInput != null ? UsernameInput.text.Trim() : "";
|
||
|
||
if (string.IsNullOrEmpty(username))
|
||
{
|
||
UpdateStatus("错误: 用户名不能为空");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在注销用户: {username}...");
|
||
Log($"发送注销用户命令 (0x08)");
|
||
Log($"用户名: {username}");
|
||
|
||
BLECommunicationManager.Instance.UnregisterUser(username, (response) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (response.IsSuccess)
|
||
{
|
||
UpdateStatus($"注销成功: {username}");
|
||
Log($"用户 {username} 注销成功!");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus($"注销失败: {username}, 状态码=0x{response.Status:X2}");
|
||
Log($"用户 {username} 注销失败, 状态码=0x{response.Status:X2}");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 指纹登录使能设置
|
||
/// </summary>
|
||
private void OnFingerprintEnableClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
string username = UsernameInput != null ? UsernameInput.text.Trim() : "";
|
||
|
||
if (string.IsNullOrEmpty(username))
|
||
{
|
||
UpdateStatus("错误: 用户名不能为空");
|
||
return;
|
||
}
|
||
|
||
bool enable = FingerprintEnableToggle != null ? FingerprintEnableToggle.isOn : true;
|
||
|
||
UpdateStatus($"正在设置指纹使能: {username}, 状态={(enable ? "使能" : "禁用")}...");
|
||
Log($"发送指纹使能设置命令 (0x04)");
|
||
Log($"用户名: {username}, 使能状态: {(enable ? "使能" : "禁用")}");
|
||
|
||
BLECommunicationManager.Instance.SetFingerprintEnable(username, enable, (response) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (response.IsSuccess)
|
||
{
|
||
UpdateStatus($"指纹使能设置成功: {username}, {(enable ? "使能" : "禁用")}");
|
||
Log($"用户 {username} 指纹使能设置成功: {(enable ? "使能" : "禁用")}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus($"指纹使能设置失败: {username}, 状态码=0x{response.Status:X2}");
|
||
Log($"用户 {username} 指纹使能设置失败, 状态码=0x{response.Status:X2}");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 指纹录制请求
|
||
/// </summary>
|
||
private void OnFingerprintRecordClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
string username = UsernameInput != null ? UsernameInput.text.Trim() : "";
|
||
|
||
if (string.IsNullOrEmpty(username))
|
||
{
|
||
UpdateStatus("错误: 用户名不能为空");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在请求指纹录制: {username}...");
|
||
Log($"发送指纹录制请求命令 (0x05)");
|
||
Log($"用户名: {username}");
|
||
|
||
BLECommunicationManager.Instance.StartFingerprintRecord(username, (response) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (response.IsSuccess)
|
||
{
|
||
UpdateStatus($"指纹录制请求成功: {username}");
|
||
Log($"用户 {username} 指纹录制请求成功,请按设备提示录入指纹");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus($"指纹录制请求失败: {username}, 状态码=0x{response.Status:X2}");
|
||
Log($"用户 {username} 指纹录制请求失败, 状态码=0x{response.Status:X2}");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 设备设置功能
|
||
|
||
/// <summary>
|
||
/// 读取语言设置
|
||
/// </summary>
|
||
private void OnReadLanguageClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取语言设置...");
|
||
Log("发送读取语言设置命令 (0x10)");
|
||
|
||
BLECommunicationManager.Instance.ReadLanguageSetting((setting) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string langStr = setting.IsChinese ? "中文" : "英文";
|
||
UpdateStatus($"语言设置: {langStr}");
|
||
Log($"当前语言: {langStr}");
|
||
|
||
// 更新输入框和开关
|
||
if (SettingsInputField != null)
|
||
SettingsInputField.text = langStr;
|
||
if (LanguageToggle != null)
|
||
LanguageToggle.isOn = setting.IsChinese;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入语言设置
|
||
/// </summary>
|
||
private void OnWriteLanguageClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
// 从开关获取语言设置,如果开关未设置则从输入框解析
|
||
bool isChinese;
|
||
if (LanguageToggle != null)
|
||
{
|
||
isChinese = LanguageToggle.isOn;
|
||
}
|
||
else if (SettingsInputField != null)
|
||
{
|
||
string input = SettingsInputField.text.Trim();
|
||
isChinese = input.Contains("中") || input == "1" || input.ToLower() == "chinese";
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 无法获取语言设置");
|
||
return;
|
||
}
|
||
|
||
string langStr = isChinese ? "中文" : "英文";
|
||
UpdateStatus($"正在设置语言: {langStr}...");
|
||
Log($"发送写入语言设置命令 (0x10): {langStr}");
|
||
|
||
BLECommunicationManager.Instance.WriteLanguageSetting(isChinese, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"语言设置成功: {langStr}");
|
||
Log($"语言设置成功: {langStr}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("语言设置失败");
|
||
Log("语言设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取时间设置
|
||
/// </summary>
|
||
private void OnReadTimeClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取时间设置...");
|
||
Log("发送读取时间设置命令 (0x11)");
|
||
|
||
BLECommunicationManager.Instance.ReadTimeSetting((setting) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string timeStr = setting.ToString();
|
||
UpdateStatus($"时间设置: {timeStr}");
|
||
Log($"当前时间: {timeStr}");
|
||
|
||
// 更新输入框
|
||
if (SettingsInputField != null)
|
||
SettingsInputField.text = timeStr;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入时间设置
|
||
/// </summary>
|
||
private void OnWriteTimeClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (SettingsInputField == null || string.IsNullOrEmpty(SettingsInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入时间");
|
||
return;
|
||
}
|
||
|
||
// 解析时间字符串 (格式: yyyy-MM-dd HH:mm:ss)
|
||
if (!TryParseTimeString(SettingsInputField.text.Trim(), out BLEProtocol.TimeSetting timeSetting))
|
||
{
|
||
UpdateStatus("错误: 时间格式不正确,请使用格式: yyyy-MM-dd HH:mm:ss");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在设置时间: {timeSetting}...");
|
||
Log($"发送写入时间设置命令 (0x11): {timeSetting}");
|
||
|
||
BLECommunicationManager.Instance.WriteTimeSetting(timeSetting, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"时间设置成功: {timeSetting}");
|
||
Log($"时间设置成功: {timeSetting}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("时间设置失败");
|
||
Log("时间设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析时间字符串
|
||
/// </summary>
|
||
private bool TryParseTimeString(string timeStr, out BLEProtocol.TimeSetting setting)
|
||
{
|
||
setting = new BLEProtocol.TimeSetting();
|
||
|
||
try
|
||
{
|
||
// 尝试解析格式: yyyy-MM-dd HH:mm:ss
|
||
if (DateTime.TryParseExact(timeStr, "yyyy-MM-dd HH:mm:ss",
|
||
System.Globalization.CultureInfo.InvariantCulture,
|
||
System.Globalization.DateTimeStyles.None, out DateTime dt))
|
||
{
|
||
setting.Year = (byte)(dt.Year - 2000);
|
||
setting.Month = (byte)dt.Month;
|
||
setting.Day = (byte)dt.Day;
|
||
setting.Hour = (byte)dt.Hour;
|
||
setting.Minute = (byte)dt.Minute;
|
||
setting.Second = (byte)dt.Second;
|
||
return true;
|
||
}
|
||
|
||
// 尝试解析格式: yyyy/MM/dd HH:mm:ss
|
||
if (DateTime.TryParseExact(timeStr, "yyyy/MM/dd HH:mm:ss",
|
||
System.Globalization.CultureInfo.InvariantCulture,
|
||
System.Globalization.DateTimeStyles.None, out DateTime dt2))
|
||
{
|
||
setting.Year = (byte)(dt2.Year - 2000);
|
||
setting.Month = (byte)dt2.Month;
|
||
setting.Day = (byte)dt2.Day;
|
||
setting.Hour = (byte)dt2.Hour;
|
||
setting.Minute = (byte)dt2.Minute;
|
||
setting.Second = (byte)dt2.Second;
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// 缓存的定时任务列表
|
||
private BLEProtocol.ScheduleTask[] _cachedScheduleTasks;
|
||
|
||
/// <summary>
|
||
/// 读取定时任务列表
|
||
/// </summary>
|
||
private void OnReadScheduleClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取定时任务...");
|
||
Log("发送读取定时任务命令 (0x12)");
|
||
|
||
BLECommunicationManager.Instance.ReadScheduleTasks((response) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (response.IsSuccess)
|
||
{
|
||
_cachedScheduleTasks = response.Tasks;
|
||
string tasksStr = FormatScheduleTasks(response.Tasks);
|
||
UpdateStatus($"定时任务读取成功,共 {response.Tasks.Length} 个任务");
|
||
Log($"定时任务列表:\n{tasksStr}");
|
||
|
||
// 更新输入框
|
||
if (SettingsInputField != null)
|
||
SettingsInputField.text = tasksStr;
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("定时任务读取失败");
|
||
Log("定时任务读取失败");
|
||
|
||
// 生成默认模板
|
||
string template = GenerateScheduleTaskTemplate();
|
||
if (SettingsInputField != null)
|
||
SettingsInputField.text = template;
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入定时任务(支持批量写入最多5条)
|
||
/// </summary>
|
||
private void OnWriteScheduleClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (SettingsInputField == null || string.IsNullOrEmpty(SettingsInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入定时任务数据");
|
||
return;
|
||
}
|
||
|
||
// 解析多条定时任务
|
||
if (!TryParseScheduleTasksMulti(SettingsInputField.text, out BLEProtocol.ScheduleTask[] tasks))
|
||
{
|
||
UpdateStatus("错误: 定时任务格式不正确");
|
||
return;
|
||
}
|
||
|
||
if (tasks.Length == 1)
|
||
{
|
||
UpdateStatus($"正在写入定时任务 {tasks[0].TaskId}...");
|
||
Log($"发送写入定时任务命令 (0x12): {tasks[0]}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus($"正在批量写入 {tasks.Length} 条定时任务...");
|
||
Log($"发送批量写入定时任务命令 (0x12),共 {tasks.Length} 条任务");
|
||
}
|
||
|
||
BLECommunicationManager.Instance.WriteScheduleTasks(tasks, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
if (tasks.Length == 1)
|
||
{
|
||
UpdateStatus($"定时任务 {tasks[0].TaskId} 写入成功");
|
||
Log($"定时任务写入成功: {tasks[0]}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus($"定时任务批量写入成功,共 {tasks.Length} 条");
|
||
Log($"定时任务批量写入成功,任务列表:\n{FormatScheduleTasks(tasks)}");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus($"定时任务写入失败");
|
||
Log($"定时任务写入失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 格式化定时任务列表为表格形式
|
||
/// </summary>
|
||
private string FormatScheduleTasks(BLEProtocol.ScheduleTask[] tasks)
|
||
{
|
||
if (tasks == null || tasks.Length == 0)
|
||
return "无定时任务";
|
||
|
||
var sb = new System.Text.StringBuilder();
|
||
// 表头
|
||
sb.AppendLine("ID|开关| 时间 |模式| 重复 ");
|
||
sb.AppendLine("--|----|--------|----|----------");
|
||
|
||
for (int i = 0; i < tasks.Length; i++)
|
||
{
|
||
var task = tasks[i];
|
||
string timeStr = $"{task.StartHour:D2}:{task.StartMinute:D2}-{task.EndHour:D2}:{task.EndMinute:D2}";
|
||
string modeStr = GetModeShortString(task.Mode);
|
||
string repeatStr = GetRepeatShortString(task.Repeat);
|
||
string enabledStr = task.Enabled ? "开" : "关";
|
||
|
||
sb.AppendLine($"{task.TaskId}| {enabledStr} |{timeStr}|{modeStr}|{repeatStr}");
|
||
}
|
||
|
||
sb.AppendLine();
|
||
sb.AppendLine("说明: 模式(待/扫/消)=待机/扫描/消杀, 重复(一/二/三/四/五/六/日)");
|
||
return sb.ToString();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取模式缩写
|
||
/// </summary>
|
||
private string GetModeShortString(BLEProtocol.ScheduleTaskMode mode)
|
||
{
|
||
return mode switch
|
||
{
|
||
BLEProtocol.ScheduleTaskMode.Standby => "待机",
|
||
BLEProtocol.ScheduleTaskMode.Scan => "扫描",
|
||
BLEProtocol.ScheduleTaskMode.Sterilize => "消杀",
|
||
_ => "未知"
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取重复缩写
|
||
/// </summary>
|
||
private string GetRepeatShortString(byte repeat)
|
||
{
|
||
if (repeat == 0) return "不重复";
|
||
|
||
var sb = new System.Text.StringBuilder();
|
||
if ((repeat & BLEProtocol.ScheduleTask.REPEAT_MONDAY) != 0) sb.Append("一");
|
||
if ((repeat & BLEProtocol.ScheduleTask.REPEAT_TUESDAY) != 0) sb.Append("二");
|
||
if ((repeat & BLEProtocol.ScheduleTask.REPEAT_WEDNESDAY) != 0) sb.Append("三");
|
||
if ((repeat & BLEProtocol.ScheduleTask.REPEAT_THURSDAY) != 0) sb.Append("四");
|
||
if ((repeat & BLEProtocol.ScheduleTask.REPEAT_FRIDAY) != 0) sb.Append("五");
|
||
if ((repeat & BLEProtocol.ScheduleTask.REPEAT_SATURDAY) != 0) sb.Append("六");
|
||
if ((repeat & BLEProtocol.ScheduleTask.REPEAT_SUNDAY) != 0) sb.Append("日");
|
||
|
||
return sb.ToString();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 生成定时任务输入模板(表格形式,5条任务)
|
||
/// </summary>
|
||
private string GenerateScheduleTaskTemplate()
|
||
{
|
||
var sb = new System.Text.StringBuilder();
|
||
sb.AppendLine("ID|开关| 时间 |模式| 重复 ");
|
||
sb.AppendLine("--|----|--------|----|----------");
|
||
sb.AppendLine("0| 开 |08:00-09:00|扫描|一二三四五");
|
||
sb.AppendLine("1| 开 |12:00-13:00|消杀|一二三四五六日");
|
||
sb.AppendLine("2| 关 |18:00-20:00|扫描|六日");
|
||
sb.AppendLine("3| 关 |22:00-23:00|待机|一二三四五");
|
||
sb.AppendLine("4| 关 |00:00-00:00|待机|不重复");
|
||
sb.AppendLine();
|
||
sb.AppendLine("说明:");
|
||
sb.AppendLine("- ID: 任务编号(0-4)");
|
||
sb.AppendLine("- 开关: 开/关 或 启用/禁用");
|
||
sb.AppendLine("- 时间: 开始-结束 (HH:mm-HH:mm)");
|
||
sb.AppendLine("- 模式: 待机/扫描/消杀");
|
||
sb.AppendLine("- 重复: 一/二/三/四/五/六/日 或 不重复");
|
||
sb.AppendLine("- 可一次写入1-5条任务,删除不需要的行即可");
|
||
return sb.ToString();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析多条定时任务字符串(支持表格格式,最多5条)
|
||
/// </summary>
|
||
private bool TryParseScheduleTasksMulti(string input, out BLEProtocol.ScheduleTask[] tasks)
|
||
{
|
||
tasks = new BLEProtocol.ScheduleTask[0];
|
||
var taskList = new System.Collections.Generic.List<BLEProtocol.ScheduleTask>();
|
||
|
||
try
|
||
{
|
||
var lines = input.Split('\n');
|
||
|
||
// 按表格格式解析所有任务行
|
||
foreach (var line in lines)
|
||
{
|
||
string trimmed = line.Trim();
|
||
if (string.IsNullOrEmpty(trimmed)) continue;
|
||
if (trimmed.StartsWith("ID") || trimmed.StartsWith("--") || trimmed.StartsWith("说明")) continue;
|
||
|
||
// 表格格式: ID|开关|时间|模式|重复
|
||
var parts = trimmed.Split('|');
|
||
if (parts.Length >= 5)
|
||
{
|
||
var task = new BLEProtocol.ScheduleTask();
|
||
|
||
// 解析ID
|
||
byte.TryParse(parts[0].Trim(), out byte taskId);
|
||
task.TaskId = taskId;
|
||
|
||
// 解析开关
|
||
string switchStr = parts[1].Trim();
|
||
task.Enabled = switchStr == "开" || switchStr == "启用" || switchStr == "1" || switchStr.ToLower() == "true";
|
||
|
||
// 解析时间 (格式: HH:mm-HH:mm)
|
||
string timeStr = parts[2].Trim();
|
||
ParseTimeRange(timeStr, out byte startHour, out byte startMinute, out byte endHour, out byte endMinute);
|
||
task.StartHour = startHour;
|
||
task.StartMinute = startMinute;
|
||
task.EndHour = endHour;
|
||
task.EndMinute = endMinute;
|
||
|
||
// 解析模式
|
||
task.Mode = ParseMode(parts[3].Trim());
|
||
|
||
// 解析重复
|
||
task.Repeat = ParseRepeatShort(parts[4].Trim());
|
||
|
||
taskList.Add(task);
|
||
|
||
// 最多5条任务
|
||
if (taskList.Count >= 5) break;
|
||
}
|
||
}
|
||
|
||
// 如果没有解析到任务,尝试旧格式解析单条
|
||
if (taskList.Count == 0)
|
||
{
|
||
if (TryParseScheduleTasksOldFormat(input, out BLEProtocol.ScheduleTask singleTask))
|
||
{
|
||
taskList.Add(singleTask);
|
||
}
|
||
}
|
||
|
||
if (taskList.Count > 0)
|
||
{
|
||
tasks = taskList.ToArray();
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析定时任务字符串(支持表格格式)- 单条解析,保持兼容
|
||
/// </summary>
|
||
private bool TryParseScheduleTasks(string input, out BLEProtocol.ScheduleTask task)
|
||
{
|
||
task = new BLEProtocol.ScheduleTask();
|
||
|
||
if (TryParseScheduleTasksMulti(input, out BLEProtocol.ScheduleTask[] tasks) && tasks.Length > 0)
|
||
{
|
||
task = tasks[0];
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析时间范围 (HH:mm-HH:mm)
|
||
/// </summary>
|
||
private void ParseTimeRange(string timeRange, out byte startHour, out byte startMinute, out byte endHour, out byte endMinute)
|
||
{
|
||
startHour = 0; startMinute = 0; endHour = 0; endMinute = 0;
|
||
|
||
var timeParts = timeRange.Split('-');
|
||
if (timeParts.Length == 2)
|
||
{
|
||
ParseTime(timeParts[0].Trim(), out startHour, out startMinute);
|
||
ParseTime(timeParts[1].Trim(), out endHour, out endMinute);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析重复缩写 (一二三四五六日)
|
||
/// </summary>
|
||
private byte ParseRepeatShort(string repeatStr)
|
||
{
|
||
byte repeat = 0;
|
||
if (repeatStr.Contains("不重复")) return 0;
|
||
|
||
if (repeatStr.Contains("一")) repeat |= BLEProtocol.ScheduleTask.REPEAT_MONDAY;
|
||
if (repeatStr.Contains("二")) repeat |= BLEProtocol.ScheduleTask.REPEAT_TUESDAY;
|
||
if (repeatStr.Contains("三")) repeat |= BLEProtocol.ScheduleTask.REPEAT_WEDNESDAY;
|
||
if (repeatStr.Contains("四")) repeat |= BLEProtocol.ScheduleTask.REPEAT_THURSDAY;
|
||
if (repeatStr.Contains("五")) repeat |= BLEProtocol.ScheduleTask.REPEAT_FRIDAY;
|
||
if (repeatStr.Contains("六")) repeat |= BLEProtocol.ScheduleTask.REPEAT_SATURDAY;
|
||
if (repeatStr.Contains("日")) repeat |= BLEProtocol.ScheduleTask.REPEAT_SUNDAY;
|
||
|
||
return repeat;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 旧格式解析(兼容旧版)
|
||
/// </summary>
|
||
private bool TryParseScheduleTasksOldFormat(string input, out BLEProtocol.ScheduleTask task)
|
||
{
|
||
task = new BLEProtocol.ScheduleTask();
|
||
|
||
try
|
||
{
|
||
var lines = input.Split('\n');
|
||
byte taskId = 0;
|
||
bool enabled = true;
|
||
byte startHour = 0, startMinute = 0;
|
||
byte endHour = 0, endMinute = 0;
|
||
BLEProtocol.ScheduleTaskMode mode = BLEProtocol.ScheduleTaskMode.Scan;
|
||
byte repeat = 0;
|
||
|
||
foreach (var line in lines)
|
||
{
|
||
string trimmed = line.Trim();
|
||
if (string.IsNullOrEmpty(trimmed)) continue;
|
||
|
||
// 解析任务ID
|
||
if (trimmed.StartsWith("任务") && trimmed.Contains(":"))
|
||
{
|
||
int colonIndex = trimmed.IndexOf(':');
|
||
if (colonIndex > 2)
|
||
{
|
||
string idStr = trimmed.Substring(2, colonIndex - 2);
|
||
byte.TryParse(idStr, out taskId);
|
||
}
|
||
continue;
|
||
}
|
||
|
||
// 解析开关
|
||
if (trimmed.Contains("开关:"))
|
||
{
|
||
string value = trimmed.Substring(trimmed.IndexOf(':') + 1).Trim();
|
||
enabled = value.Contains("启用") || value == "1" || value.ToLower() == "true" || value.ToLower() == "on";
|
||
continue;
|
||
}
|
||
|
||
// 解析开始时间
|
||
if (trimmed.Contains("开始:"))
|
||
{
|
||
string value = trimmed.Substring(trimmed.IndexOf(':') + 1).Trim();
|
||
ParseTime(value, out startHour, out startMinute);
|
||
continue;
|
||
}
|
||
|
||
// 解析结束时间
|
||
if (trimmed.Contains("结束:"))
|
||
{
|
||
string value = trimmed.Substring(trimmed.IndexOf(':') + 1).Trim();
|
||
ParseTime(value, out endHour, out endMinute);
|
||
continue;
|
||
}
|
||
|
||
// 解析模式
|
||
if (trimmed.Contains("模式:"))
|
||
{
|
||
string value = trimmed.Substring(trimmed.IndexOf(':') + 1).Trim();
|
||
mode = ParseMode(value);
|
||
continue;
|
||
}
|
||
|
||
// 解析重复
|
||
if (trimmed.Contains("重复:"))
|
||
{
|
||
string value = trimmed.Substring(trimmed.IndexOf(':') + 1).Trim();
|
||
repeat = ParseRepeat(value);
|
||
continue;
|
||
}
|
||
}
|
||
|
||
task.TaskId = taskId;
|
||
task.Enabled = enabled;
|
||
task.StartHour = startHour;
|
||
task.StartMinute = startMinute;
|
||
task.EndHour = endHour;
|
||
task.EndMinute = endMinute;
|
||
task.Mode = mode;
|
||
task.Repeat = repeat;
|
||
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析时间字符串 (HH:mm)
|
||
/// </summary>
|
||
private void ParseTime(string timeStr, out byte hour, out byte minute)
|
||
{
|
||
hour = 0;
|
||
minute = 0;
|
||
|
||
var parts = timeStr.Split(':');
|
||
if (parts.Length >= 2)
|
||
{
|
||
byte.TryParse(parts[0], out hour);
|
||
byte.TryParse(parts[1], out minute);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析模式字符串
|
||
/// </summary>
|
||
private BLEProtocol.ScheduleTaskMode ParseMode(string modeStr)
|
||
{
|
||
modeStr = modeStr.Trim().ToLower();
|
||
return modeStr switch
|
||
{
|
||
"待机" or "shutdown" or "standby" or "0" => BLEProtocol.ScheduleTaskMode.Standby,
|
||
"扫描" or "scan" or "1" => BLEProtocol.ScheduleTaskMode.Scan,
|
||
"消杀" or "sterilize" or "disinfect" or "2" => BLEProtocol.ScheduleTaskMode.Sterilize,
|
||
_ => BLEProtocol.ScheduleTaskMode.Scan
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取模式显示字符串
|
||
/// </summary>
|
||
private string GetModeString(BLEProtocol.ScheduleTaskMode mode)
|
||
{
|
||
return mode switch
|
||
{
|
||
BLEProtocol.ScheduleTaskMode.Standby => "待机",
|
||
BLEProtocol.ScheduleTaskMode.Scan => "扫描",
|
||
BLEProtocol.ScheduleTaskMode.Sterilize => "消杀",
|
||
_ => "未知"
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析重复字符串
|
||
/// </summary>
|
||
private byte ParseRepeat(string repeatStr)
|
||
{
|
||
byte repeat = 0;
|
||
repeatStr = repeatStr.ToLower();
|
||
|
||
if (repeatStr.Contains("周一") || repeatStr.Contains("mon")) repeat |= BLEProtocol.ScheduleTask.REPEAT_MONDAY;
|
||
if (repeatStr.Contains("周二") || repeatStr.Contains("tue")) repeat |= BLEProtocol.ScheduleTask.REPEAT_TUESDAY;
|
||
if (repeatStr.Contains("周三") || repeatStr.Contains("wed")) repeat |= BLEProtocol.ScheduleTask.REPEAT_WEDNESDAY;
|
||
if (repeatStr.Contains("周四") || repeatStr.Contains("thu")) repeat |= BLEProtocol.ScheduleTask.REPEAT_THURSDAY;
|
||
if (repeatStr.Contains("周五") || repeatStr.Contains("fri")) repeat |= BLEProtocol.ScheduleTask.REPEAT_FRIDAY;
|
||
if (repeatStr.Contains("周六") || repeatStr.Contains("sat")) repeat |= BLEProtocol.ScheduleTask.REPEAT_SATURDAY;
|
||
if (repeatStr.Contains("周日") || repeatStr.Contains("sun")) repeat |= BLEProtocol.ScheduleTask.REPEAT_SUNDAY;
|
||
|
||
return repeat;
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 外设控制功能
|
||
|
||
/// <summary>
|
||
/// 读取LCD休眠设置
|
||
/// </summary>
|
||
private void OnReadLCDSleepClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取LCD休眠设置...");
|
||
Log("发送读取LCD休眠设置命令 (0x20)");
|
||
|
||
BLECommunicationManager.Instance.ReadLCDSleepSetting((setting) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string sleepStr = setting.GetSleepTimeString();
|
||
string result = $"LCD休眠: 开关={(setting.Enable ? "开启" : "关闭")}, 时间={sleepStr}";
|
||
UpdateStatus(result);
|
||
Log(result);
|
||
|
||
// 更新输入框
|
||
if (PeripheralInputField != null)
|
||
PeripheralInputField.text = result;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入LCD休眠设置
|
||
/// </summary>
|
||
private void OnWriteLCDSleepClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (PeripheralInputField == null || string.IsNullOrEmpty(PeripheralInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入LCD休眠设置");
|
||
return;
|
||
}
|
||
|
||
// 解析LCD休眠设置
|
||
if (!TryParseLCDSleepSetting(PeripheralInputField.text.Trim(), out LCDSleepSetting setting))
|
||
{
|
||
UpdateStatus("错误: LCD休眠设置格式不正确");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在设置LCD休眠: 开关={(setting.Enable ? "开启" : "关闭")}, 时间={setting.GetSleepTimeString()}...");
|
||
Log($"发送写入LCD休眠设置命令 (0x20)");
|
||
|
||
BLECommunicationManager.Instance.WriteLCDSleepSetting(setting, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("LCD休眠设置成功");
|
||
Log("LCD休眠设置成功");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("LCD休眠设置失败");
|
||
Log("LCD休眠设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析LCD休眠设置
|
||
/// </summary>
|
||
private bool TryParseLCDSleepSetting(string input, out LCDSleepSetting setting)
|
||
{
|
||
setting = new LCDSleepSetting();
|
||
|
||
try
|
||
{
|
||
// 解析新格式: "LCD休眠: 开关=开启, 时间=X分钟"
|
||
string trimmed = input.Trim();
|
||
|
||
// 提取开关状态
|
||
int switchIndex = trimmed.IndexOf("开关=");
|
||
if (switchIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", switchIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string switchValue = trimmed.Substring(switchIndex + 3, endIndex - switchIndex - 3).Trim();
|
||
setting.Enable = switchValue.Contains("开启") || switchValue == "1" || switchValue.ToLower() == "true" || switchValue.ToLower() == "on";
|
||
}
|
||
|
||
// 提取时间设置
|
||
int timeIndex = trimmed.IndexOf("时间=");
|
||
if (timeIndex != -1)
|
||
{
|
||
string timeValue = trimmed.Substring(timeIndex + 3).Trim();
|
||
setting.SleepTime = timeValue switch
|
||
{
|
||
"1分钟" or "1" => 0x01,
|
||
"5分钟" or "5" => 0x05,
|
||
"10分钟" or "10" => 0x0A,
|
||
"30分钟" or "30" => 0x1E,
|
||
_ => 0x05 // 默认5分钟
|
||
};
|
||
}
|
||
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取LCD亮度设置
|
||
/// </summary>
|
||
private void OnReadLCDBrightnessClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取LCD亮度设置...");
|
||
Log("发送读取LCD亮度设置命令 (0x21)");
|
||
|
||
BLECommunicationManager.Instance.ReadLCDBrightnessSetting((setting) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string result = $"LCD亮度: 自适应={(setting.AutoBrightness ? "开启" : "关闭")}, 亮度={setting.Brightness}%";
|
||
UpdateStatus(result);
|
||
Log(result);
|
||
|
||
// 更新输入框
|
||
if (PeripheralInputField != null)
|
||
PeripheralInputField.text = result;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入LCD亮度设置
|
||
/// </summary>
|
||
private void OnWriteLCDBrightnessClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (PeripheralInputField == null || string.IsNullOrEmpty(PeripheralInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入LCD亮度设置");
|
||
return;
|
||
}
|
||
|
||
// 解析LCD亮度设置
|
||
if (!TryParseLCDBrightnessSetting(PeripheralInputField.text.Trim(), out LCDBrightnessSetting setting))
|
||
{
|
||
UpdateStatus("错误: LCD亮度设置格式不正确");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在设置LCD亮度: 自适应={(setting.AutoBrightness ? "开启" : "关闭")}, 亮度={setting.Brightness}%...");
|
||
Log($"发送写入LCD亮度设置命令 (0x21)");
|
||
|
||
BLECommunicationManager.Instance.WriteLCDBrightnessSetting(setting, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("LCD亮度设置成功");
|
||
Log("LCD亮度设置成功");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("LCD亮度设置失败");
|
||
Log("LCD亮度设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析LCD亮度设置
|
||
/// </summary>
|
||
private bool TryParseLCDBrightnessSetting(string input, out LCDBrightnessSetting setting)
|
||
{
|
||
setting = new LCDBrightnessSetting();
|
||
|
||
try
|
||
{
|
||
// 解析新格式: "LCD亮度: 自适应=开启, 亮度=X%"
|
||
string trimmed = input.Trim();
|
||
|
||
// 提取自适应状态
|
||
int autoIndex = trimmed.IndexOf("自适应=");
|
||
if (autoIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", autoIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string autoValue = trimmed.Substring(autoIndex + 4, endIndex - autoIndex - 4).Trim();
|
||
setting.AutoBrightness = autoValue.Contains("开启") || autoValue == "1" || autoValue.ToLower() == "true" || autoValue.ToLower() == "on";
|
||
}
|
||
|
||
// 提取亮度值
|
||
int brightnessIndex = trimmed.IndexOf("亮度=");
|
||
if (brightnessIndex != -1)
|
||
{
|
||
string brightnessValue = trimmed.Substring(brightnessIndex + 3).Trim().Replace("%", "");
|
||
byte.TryParse(brightnessValue, out byte brightness);
|
||
setting.Brightness = brightness;
|
||
}
|
||
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取RGB控制
|
||
/// </summary>
|
||
private void OnReadRGBClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取RGB控制设置...");
|
||
Log("发送读取RGB控制命令 (0x22)");
|
||
|
||
BLECommunicationManager.Instance.ReadRGBControl((control) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string effectStr = control.Effect switch
|
||
{
|
||
RGBEffectMode.Off => "关闭",
|
||
RGBEffectMode.Solid => "常亮",
|
||
RGBEffectMode.Blinking => "闪烁",
|
||
RGBEffectMode.Warning => "警示",
|
||
_ => "未知"
|
||
};
|
||
string result = $"RGB控制: 开关={(control.Enable ? "开启" : "关闭")}, 颜色={control.Red},{control.Green},{control.Blue}, 效果={effectStr}";
|
||
UpdateStatus(result);
|
||
Log(result);
|
||
|
||
// 更新输入框
|
||
if (PeripheralInputField != null)
|
||
PeripheralInputField.text = result;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入RGB控制
|
||
/// </summary>
|
||
private void OnWriteRGBClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (PeripheralInputField == null || string.IsNullOrEmpty(PeripheralInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入RGB控制设置");
|
||
return;
|
||
}
|
||
|
||
// 解析RGB控制设置
|
||
if (!TryParseRGBControl(PeripheralInputField.text.Trim(), out RGBControl control))
|
||
{
|
||
UpdateStatus("错误: RGB控制设置格式不正确");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在设置RGB控制: 开关={(control.Enable ? "开启" : "关闭")}, 颜色={control.Red},{control.Green},{control.Blue}...");
|
||
Log($"发送写入RGB控制命令 (0x22)");
|
||
|
||
BLECommunicationManager.Instance.WriteRGBControl(control, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("RGB控制设置成功");
|
||
Log("RGB控制设置成功");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("RGB控制设置失败");
|
||
Log("RGB控制设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析RGB控制设置
|
||
/// </summary>
|
||
private bool TryParseRGBControl(string input, out RGBControl control)
|
||
{
|
||
control = new RGBControl();
|
||
|
||
try
|
||
{
|
||
// 解析新格式: "RGB控制: 开关=开启, 颜色=R,G,B, 效果=X"
|
||
string trimmed = input.Trim();
|
||
|
||
// 提取开关状态
|
||
int switchIndex = trimmed.IndexOf("开关=");
|
||
if (switchIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", switchIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string switchValue = trimmed.Substring(switchIndex + 3, endIndex - switchIndex - 3).Trim();
|
||
control.Enable = switchValue.Contains("开启") || switchValue == "1" || switchValue.ToLower() == "true" || switchValue.ToLower() == "on";
|
||
}
|
||
|
||
// 提取颜色值
|
||
int colorIndex = trimmed.IndexOf("颜色=");
|
||
if (colorIndex != -1)
|
||
{
|
||
int startIndex = colorIndex + 3;
|
||
int endIndex = trimmed.Length;
|
||
|
||
// 查找颜色值之后的下一个逗号(用于分隔效果字段)
|
||
// 颜色值格式为 R,G,B,包含两个逗号
|
||
// 所以需要找到颜色值之后的第一个逗号(即第3个逗号)
|
||
int commaCount = 0;
|
||
for (int i = startIndex; i < trimmed.Length; i++)
|
||
{
|
||
if (trimmed[i] == ',')
|
||
{
|
||
commaCount++;
|
||
if (commaCount == 3)
|
||
{
|
||
endIndex = i;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
string colorValue = trimmed.Substring(startIndex, endIndex - startIndex).Trim();
|
||
var parts = colorValue.Split(',');
|
||
if (parts.Length >= 3)
|
||
{
|
||
byte.TryParse(parts[0].Trim(), out control.Red);
|
||
byte.TryParse(parts[1].Trim(), out control.Green);
|
||
byte.TryParse(parts[2].Trim(), out control.Blue);
|
||
}
|
||
}
|
||
|
||
// 提取效果
|
||
int effectIndex = trimmed.IndexOf("效果=");
|
||
if (effectIndex != -1)
|
||
{
|
||
string effectValue = trimmed.Substring(effectIndex + 3).Trim();
|
||
control.Effect = effectValue switch
|
||
{
|
||
"关闭" or "Off" or "0" => RGBEffectMode.Off,
|
||
"常亮" or "Solid" or "1" => RGBEffectMode.Solid,
|
||
"闪烁" or "Blinking" or "2" => RGBEffectMode.Blinking,
|
||
"警示" or "Warning" or "3" => RGBEffectMode.Warning,
|
||
_ => RGBEffectMode.Solid
|
||
};
|
||
}
|
||
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取WIFI控制
|
||
/// </summary>
|
||
private void OnReadWIFIClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取WIFI控制设置...");
|
||
Log("发送读取WIFI控制命令 (0x23)");
|
||
|
||
BLECommunicationManager.Instance.ReadWIFIControl((control) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string result = $"WIFI控制: 开关={(control.Enable ? "开启" : "关闭")}, SSID={control.SSID}, 密码={new string('*', control.Password?.Length ?? 0)}";
|
||
UpdateStatus(result);
|
||
Log(result);
|
||
|
||
// 更新输入框
|
||
if (PeripheralInputField != null)
|
||
PeripheralInputField.text = result;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入WIFI控制
|
||
/// </summary>
|
||
private void OnWriteWIFIClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (PeripheralInputField == null || string.IsNullOrEmpty(PeripheralInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入WIFI控制设置");
|
||
return;
|
||
}
|
||
|
||
// 解析WIFI控制设置
|
||
if (!TryParseWIFIControl(PeripheralInputField.text.Trim(), out WIFIControl control))
|
||
{
|
||
UpdateStatus("错误: WIFI控制设置格式不正确");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在设置WIFI控制: 开关={(control.Enable ? "开启" : "关闭")}, SSID={control.SSID}...");
|
||
Log($"发送写入WIFI控制命令 (0x23)");
|
||
|
||
BLECommunicationManager.Instance.WriteWIFIControl(control, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("WIFI控制设置成功");
|
||
Log("WIFI控制设置成功");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("WIFI控制设置失败");
|
||
Log("WIFI控制设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析WIFI控制设置
|
||
/// </summary>
|
||
private bool TryParseWIFIControl(string input, out WIFIControl control)
|
||
{
|
||
control = new WIFIControl();
|
||
|
||
try
|
||
{
|
||
// 解析新格式: "WIFI控制: 开关=开启, SSID=X, 密码=***"
|
||
string trimmed = input.Trim();
|
||
|
||
// 提取开关状态
|
||
int switchIndex = trimmed.IndexOf("开关=");
|
||
if (switchIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", switchIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string switchValue = trimmed.Substring(switchIndex + 3, endIndex - switchIndex - 3).Trim();
|
||
control.Enable = switchValue.Contains("开启") || switchValue == "1" || switchValue.ToLower() == "true" || switchValue.ToLower() == "on";
|
||
}
|
||
|
||
// 提取SSID
|
||
int ssidIndex = trimmed.IndexOf("SSID=");
|
||
if (ssidIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", ssidIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
control.SSID = trimmed.Substring(ssidIndex + 4, endIndex - ssidIndex - 4).Trim();
|
||
}
|
||
|
||
// 提取密码
|
||
int passwordIndex = trimmed.IndexOf("密码=");
|
||
if (passwordIndex != -1)
|
||
{
|
||
control.Password = trimmed.Substring(passwordIndex + 3).Trim();
|
||
}
|
||
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取BLE控制
|
||
/// </summary>
|
||
private void OnReadBLEClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取BLE控制设置...");
|
||
Log("发送读取BLE控制命令 (0x24)");
|
||
|
||
BLECommunicationManager.Instance.ReadBLEControl((control) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string result = $"BLE控制: 设备名称={control.DeviceName}";
|
||
UpdateStatus(result);
|
||
Log(result);
|
||
|
||
// 更新输入框
|
||
if (PeripheralInputField != null)
|
||
PeripheralInputField.text = result;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入BLE控制
|
||
/// </summary>
|
||
private void OnWriteBLEClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (PeripheralInputField == null || string.IsNullOrEmpty(PeripheralInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入BLE控制设置");
|
||
return;
|
||
}
|
||
|
||
// 解析BLE控制设置
|
||
if (!TryParseBLEControl(PeripheralInputField.text.Trim(), out BLEControl control))
|
||
{
|
||
UpdateStatus("错误: BLE控制设置格式不正确");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在设置BLE控制: 设备名称={control.DeviceName}...");
|
||
Log($"发送写入BLE控制命令 (0x24)");
|
||
|
||
BLECommunicationManager.Instance.WriteBLEControl(control, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("BLE控制设置成功");
|
||
Log("BLE控制设置成功");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("BLE控制设置失败");
|
||
Log("BLE控制设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析BLE控制设置
|
||
/// </summary>
|
||
private bool TryParseBLEControl(string input, out BLEControl control)
|
||
{
|
||
control = new BLEControl();
|
||
|
||
try
|
||
{
|
||
// 解析新格式: "BLE控制: 设备名称=X"
|
||
string trimmed = input.Trim();
|
||
|
||
// 提取设备名称
|
||
int nameIndex = trimmed.IndexOf("设备名称=");
|
||
if (nameIndex != -1)
|
||
{
|
||
control.DeviceName = trimmed.Substring(nameIndex + 5).Trim();
|
||
}
|
||
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取多媒体控制
|
||
/// </summary>
|
||
private void OnReadMultimediaClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取多媒体控制设置...");
|
||
Log("发送读取多媒体控制命令 (0x25)");
|
||
|
||
BLECommunicationManager.Instance.ReadMultimediaControl((control) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string result = $"多媒体控制: 视频录制={(control.VideoRecordEnable ? "开启" : "关闭")}, 录制时长={control.GetDurationString()}, 音效={(control.SoundEnable ? "开启" : "关闭")}, 类型={control.GetSoundTypeString()}, 音量={control.Volume}";
|
||
UpdateStatus(result);
|
||
Log(result);
|
||
|
||
// 更新输入框
|
||
if (PeripheralInputField != null)
|
||
PeripheralInputField.text = result;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入多媒体控制
|
||
/// </summary>
|
||
private void OnWriteMultimediaClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (PeripheralInputField == null || string.IsNullOrEmpty(PeripheralInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入多媒体控制设置");
|
||
return;
|
||
}
|
||
|
||
// 解析多媒体控制设置
|
||
if (!TryParseMultimediaControl(PeripheralInputField.text.Trim(), out MultimediaControl control))
|
||
{
|
||
UpdateStatus("错误: 多媒体控制设置格式不正确");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在设置多媒体控制: 视频录制={(control.VideoRecordEnable ? "开启" : "关闭")}, 音效={(control.SoundEnable ? "开启" : "关闭")}...");
|
||
Log($"发送写入多媒体控制命令 (0x25)");
|
||
|
||
BLECommunicationManager.Instance.WriteMultimediaControl(control, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("多媒体控制设置成功");
|
||
Log("多媒体控制设置成功");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("多媒体控制设置失败");
|
||
Log("多媒体控制设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析多媒体控制设置
|
||
/// </summary>
|
||
private bool TryParseMultimediaControl(string input, out MultimediaControl control)
|
||
{
|
||
control = new MultimediaControl();
|
||
|
||
try
|
||
{
|
||
// 解析新格式: "多媒体控制: 视频录制=开启, 录制时长=X, 音效=开启, 类型=X, 音量=X"
|
||
string trimmed = input.Trim();
|
||
|
||
// 提取视频录制状态
|
||
int videoIndex = trimmed.IndexOf("视频录制=");
|
||
if (videoIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", videoIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string videoValue = trimmed.Substring(videoIndex + 5, endIndex - videoIndex - 5).Trim();
|
||
control.VideoRecordEnable = videoValue.Contains("开启") || videoValue == "1" || videoValue.ToLower() == "true" || videoValue.ToLower() == "on";
|
||
}
|
||
|
||
// 提取录制时长
|
||
int durationIndex = trimmed.IndexOf("录制时长=");
|
||
if (durationIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", durationIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string durationValue = trimmed.Substring(durationIndex + 5, endIndex - durationIndex - 5).Trim().Replace("秒", "");
|
||
control.RecordDuration = durationValue switch
|
||
{
|
||
"3" => 0x03,
|
||
"5" => 0x05,
|
||
"10" => 0x0A,
|
||
_ => 0x05
|
||
};
|
||
}
|
||
|
||
// 提取音效状态
|
||
int soundIndex = trimmed.IndexOf("音效=");
|
||
if (soundIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", soundIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string soundValue = trimmed.Substring(soundIndex + 3, endIndex - soundIndex - 3).Trim();
|
||
control.SoundEnable = soundValue.Contains("开启") || soundValue == "1" || soundValue.ToLower() == "true" || soundValue.ToLower() == "on";
|
||
}
|
||
|
||
// 提取音效类型
|
||
int typeIndex = trimmed.IndexOf("类型=");
|
||
if (typeIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", typeIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string typeValue = trimmed.Substring(typeIndex + 3, endIndex - typeIndex - 3).Trim();
|
||
control.SoundType = typeValue switch
|
||
{
|
||
"Hello" or "0" => SoundEffectType.Hello,
|
||
"Goodbye" or "1" => SoundEffectType.Goodbye,
|
||
"Test" or "2" => SoundEffectType.Test,
|
||
"BIU" or "3" => SoundEffectType.BIU,
|
||
"Main" or "4" => SoundEffectType.Main,
|
||
_ => SoundEffectType.Main
|
||
};
|
||
}
|
||
|
||
// 提取音量
|
||
int volumeIndex = trimmed.IndexOf("音量=");
|
||
if (volumeIndex != -1)
|
||
{
|
||
string volumeValue = trimmed.Substring(volumeIndex + 3).Trim();
|
||
byte.TryParse(volumeValue, out control.Volume);
|
||
}
|
||
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取补光灯控制
|
||
/// </summary>
|
||
private void OnReadFillLightClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取补光灯控制设置...");
|
||
Log("发送读取补光灯控制命令 (0x26)");
|
||
|
||
BLECommunicationManager.Instance.ReadFillLightControl((control) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string result = $"补光灯控制: 开关={(control.Enable ? "开启" : "关闭")}, 类型={control.GetLightTypeString()}, 强度={control.GetIntensityString()}";
|
||
UpdateStatus(result);
|
||
Log(result);
|
||
|
||
// 更新输入框
|
||
if (PeripheralInputField != null)
|
||
PeripheralInputField.text = result;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入补光灯控制
|
||
/// </summary>
|
||
private void OnWriteFillLightClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (PeripheralInputField == null || string.IsNullOrEmpty(PeripheralInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入补光灯控制设置");
|
||
return;
|
||
}
|
||
|
||
// 解析补光灯控制设置
|
||
if (!TryParseFillLightControl(PeripheralInputField.text.Trim(), out FillLightControl control))
|
||
{
|
||
UpdateStatus("错误: 补光灯控制设置格式不正确");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在设置补光灯控制: 开关={(control.Enable ? "开启" : "关闭")}, 类型={control.GetLightTypeString()}, 强度={control.GetIntensityString()}...");
|
||
Log($"发送写入补光灯控制命令 (0x26)");
|
||
|
||
BLECommunicationManager.Instance.WriteFillLightControl(control, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("补光灯控制设置成功");
|
||
Log("补光灯控制设置成功");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("补光灯控制设置失败");
|
||
Log("补光灯控制设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析补光灯控制设置
|
||
/// </summary>
|
||
private bool TryParseFillLightControl(string input, out FillLightControl control)
|
||
{
|
||
control = new FillLightControl();
|
||
|
||
try
|
||
{
|
||
// 解析新格式: "补光灯控制: 开关=开启, 类型=X, 强度=X"
|
||
string trimmed = input.Trim();
|
||
|
||
// 提取开关状态
|
||
int switchIndex = trimmed.IndexOf("开关=");
|
||
if (switchIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", switchIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string switchValue = trimmed.Substring(switchIndex + 3, endIndex - switchIndex - 3).Trim();
|
||
control.Enable = switchValue.Contains("开启") || switchValue == "1" || switchValue.ToLower() == "true" || switchValue.ToLower() == "on";
|
||
}
|
||
|
||
// 提取类型
|
||
int typeIndex = trimmed.IndexOf("类型=");
|
||
if (typeIndex != -1)
|
||
{
|
||
int endIndex = trimmed.IndexOf(",", typeIndex);
|
||
if (endIndex == -1) endIndex = trimmed.Length;
|
||
string typeValue = trimmed.Substring(typeIndex + 3, endIndex - typeIndex - 3).Trim();
|
||
control.LightType = typeValue.Contains("红外") ? FillLightType.Infrared : FillLightType.White;
|
||
}
|
||
|
||
// 提取强度
|
||
int intensityIndex = trimmed.IndexOf("强度=");
|
||
if (intensityIndex != -1)
|
||
{
|
||
string intensityValue = trimmed.Substring(intensityIndex + 3).Trim();
|
||
control.Intensity = intensityValue switch
|
||
{
|
||
"低" or "0" => LightIntensity.Low,
|
||
"中" or "1" => LightIntensity.Medium,
|
||
"高" or "2" => LightIntensity.High,
|
||
_ => LightIntensity.Medium
|
||
};
|
||
}
|
||
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取可见光激光器控制
|
||
/// </summary>
|
||
private void OnReadVisibleLaserClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取可见光激光器控制设置...");
|
||
Log("发送读取可见光激光器控制命令 (0x28)");
|
||
|
||
BLECommunicationManager.Instance.ReadVisibleLaserControl((control) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string result = $"可见光激光器: 开关={(control.Enable ? "开启" : "关闭")}";
|
||
UpdateStatus(result);
|
||
Log(result);
|
||
|
||
// 更新输入框
|
||
if (PeripheralInputField != null)
|
||
PeripheralInputField.text = result;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入可见光激光器控制
|
||
/// </summary>
|
||
private void OnWriteVisibleLaserClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
if (PeripheralInputField == null || string.IsNullOrEmpty(PeripheralInputField.text))
|
||
{
|
||
UpdateStatus("错误: 请输入可见光激光器控制设置");
|
||
return;
|
||
}
|
||
|
||
// 解析可见光激光器控制设置
|
||
if (!TryParseVisibleLaserControl(PeripheralInputField.text.Trim(), out VisibleLaserControl control))
|
||
{
|
||
UpdateStatus("错误: 可见光激光器控制设置格式不正确");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"正在设置可见光激光器控制: 开关={(control.Enable ? "开启" : "关闭")}...");
|
||
Log($"发送写入可见光激光器控制命令 (0x28)");
|
||
|
||
BLECommunicationManager.Instance.WriteVisibleLaserControl(control, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("可见光激光器控制设置成功");
|
||
Log("可见光激光器控制设置成功");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("可见光激光器控制设置失败");
|
||
Log("可见光激光器控制设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析可见光激光器控制设置
|
||
/// </summary>
|
||
private bool TryParseVisibleLaserControl(string input, out VisibleLaserControl control)
|
||
{
|
||
control = new VisibleLaserControl();
|
||
|
||
try
|
||
{
|
||
// 解析新格式: "可见光激光器: 开关=开启"
|
||
string trimmed = input.Trim();
|
||
|
||
// 提取开关状态
|
||
int switchIndex = trimmed.IndexOf("开关=");
|
||
if (switchIndex != -1)
|
||
{
|
||
string switchValue = trimmed.Substring(switchIndex + 3).Trim();
|
||
control.Enable = switchValue.Contains("开启") || switchValue == "1" || switchValue.ToLower() == "true" || switchValue.ToLower() == "on";
|
||
}
|
||
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取补光灯连接状态
|
||
/// </summary>
|
||
private void OnReadFillLightConnectionClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取补光灯连接状态...");
|
||
Log("发送读取补光灯连接状态命令 (0x27)");
|
||
|
||
BLECommunicationManager.Instance.ReadFillLightConnectionStatus((status) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string result = $"补光灯连接: 状态={(status.IsConnected ? "已连接" : "未连接")}";
|
||
UpdateStatus(result);
|
||
Log(result);
|
||
|
||
// 更新输入框
|
||
if (PeripheralInputField != null)
|
||
PeripheralInputField.text = result;
|
||
});
|
||
});
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 害虫消灭控制
|
||
|
||
/// <summary>
|
||
/// 读取角度控制
|
||
/// 读取结果直接显示为可编辑的角度值
|
||
/// </summary>
|
||
private void OnReadAngleClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取角度控制设置...");
|
||
Log("发送读取角度控制命令 (0x40)");
|
||
|
||
BLECommunicationManager.Instance.ReadAngleControl((control) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
// 直接显示角度值,方便修改
|
||
string displayValue = control.ActualAngle.ToString("F1");
|
||
UpdateStatus($"角度控制: {control}");
|
||
Log($"读取角度控制: {control}");
|
||
|
||
// 更新输入框为纯数字格式,方便直接修改
|
||
if (PestControlInputField != null)
|
||
PestControlInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入角度控制
|
||
/// 输入格式: 角度值(度),例如: 45.5
|
||
/// </summary>
|
||
private void OnWriteAngleClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
// 解析输入
|
||
float angle = 45.0f;
|
||
if (PestControlInputField != null && !string.IsNullOrEmpty(PestControlInputField.text))
|
||
{
|
||
string input = PestControlInputField.text.Trim();
|
||
|
||
// 尝试解析纯数字
|
||
if (!float.TryParse(input, out angle))
|
||
{
|
||
UpdateStatus("错误: 请输入有效的角度值(例如: 45.5)");
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 限制范围
|
||
if (angle < 0.1f) angle = 0.1f;
|
||
if (angle > 90.0f) angle = 90.0f;
|
||
|
||
var control = new AngleControl();
|
||
control.SetAngle(angle);
|
||
|
||
UpdateStatus($"正在设置角度控制: {control}...");
|
||
Log($"发送写入角度控制命令 (0x40): {control}");
|
||
|
||
BLECommunicationManager.Instance.WriteAngleControl(control, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"角度控制设置成功: {control}");
|
||
Log($"角度控制设置成功: {control}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("角度控制设置失败");
|
||
Log("角度控制设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取距离控制
|
||
/// 读取结果直接显示为可编辑的距离值
|
||
/// </summary>
|
||
private void OnReadDistanceClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取距离控制设置...");
|
||
Log("发送读取距离控制命令 (0x41)");
|
||
|
||
BLECommunicationManager.Instance.ReadDistanceControl((control) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
// 直接显示距离值,格式: 检测距离,瞄准距离
|
||
string displayValue = $"{control.DetectionDistance},{control.AimDistance}";
|
||
UpdateStatus($"距离控制: {control}");
|
||
Log($"读取距离控制: {control}");
|
||
|
||
// 更新输入框为简洁格式,方便直接修改
|
||
if (PestControlInputField != null)
|
||
PestControlInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入距离控制
|
||
/// 输入格式: 检测距离,瞄准距离,例如: 5,3
|
||
/// </summary>
|
||
private void OnWriteDistanceClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
// 解析输入
|
||
ushort detectionDistance = 5;
|
||
ushort aimDistance = 3;
|
||
|
||
if (PestControlInputField != null && !string.IsNullOrEmpty(PestControlInputField.text))
|
||
{
|
||
string input = PestControlInputField.text.Trim();
|
||
|
||
// 尝试解析格式: 检测距离,瞄准距离
|
||
var parts = input.Split(',');
|
||
if (parts.Length >= 2)
|
||
{
|
||
if (!ushort.TryParse(parts[0].Trim(), out detectionDistance))
|
||
{
|
||
UpdateStatus("错误: 检测距离格式无效");
|
||
return;
|
||
}
|
||
if (!ushort.TryParse(parts[1].Trim(), out aimDistance))
|
||
{
|
||
UpdateStatus("错误: 瞄准距离格式无效");
|
||
return;
|
||
}
|
||
}
|
||
else if (parts.Length == 1)
|
||
{
|
||
// 如果只输入一个值,同时设置为检测距离和瞄准距离
|
||
if (!ushort.TryParse(parts[0].Trim(), out detectionDistance))
|
||
{
|
||
UpdateStatus("错误: 距离格式无效");
|
||
return;
|
||
}
|
||
aimDistance = detectionDistance;
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 请输入距离格式(例如: 5,3 或 5)");
|
||
return;
|
||
}
|
||
}
|
||
|
||
var control = new DistanceControl
|
||
{
|
||
DetectionDistance = detectionDistance,
|
||
AimDistance = aimDistance
|
||
};
|
||
|
||
UpdateStatus($"正在设置距离控制: {control}...");
|
||
Log($"发送写入距离控制命令 (0x41): {control}");
|
||
|
||
BLECommunicationManager.Instance.WriteDistanceControl(control, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"距离控制设置成功: {control}");
|
||
Log($"距离控制设置成功: {control}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("距离控制设置失败");
|
||
Log("距离控制设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 安全设置
|
||
|
||
/// <summary>
|
||
/// 读取毫米波雷达设置
|
||
/// </summary>
|
||
private void OnReadMillimeterWaveClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取毫米波雷达设置...");
|
||
Log("发送读取毫米波雷达设置命令 (0x50)");
|
||
|
||
BLECommunicationManager.Instance.ReadMillimeterWaveSetting((setting) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string displayValue = $"{(setting.Enable ? 1 : 0)},{(byte)setting.Sensitivity},{setting.SafeDistance}";
|
||
UpdateStatus($"毫米波雷达设置: {setting}");
|
||
Log($"读取毫米波雷达设置: {setting}");
|
||
|
||
if (SafetySettingInputField != null)
|
||
SafetySettingInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入毫米波雷达设置
|
||
/// 输入格式: 开关,灵敏度,安全距离,例如: 1,1,100
|
||
/// </summary>
|
||
private void OnWriteMillimeterWaveClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
var setting = new MillimeterWaveSetting { Enable = true, Sensitivity = SensitivityLevel.Medium, SafeDistance = 100 };
|
||
|
||
if (SafetySettingInputField != null && !string.IsNullOrEmpty(SafetySettingInputField.text))
|
||
{
|
||
string input = SafetySettingInputField.text.Trim();
|
||
var parts = input.Split(',');
|
||
|
||
if (parts.Length >= 3)
|
||
{
|
||
if (!int.TryParse(parts[0].Trim(), out int enable))
|
||
{
|
||
UpdateStatus("错误: 开关格式无效 (0或1)");
|
||
return;
|
||
}
|
||
if (!byte.TryParse(parts[1].Trim(), out byte sens))
|
||
{
|
||
UpdateStatus("错误: 灵敏度格式无效 (0-2)");
|
||
return;
|
||
}
|
||
if (!ushort.TryParse(parts[2].Trim(), out ushort dist))
|
||
{
|
||
UpdateStatus("错误: 安全距离格式无效");
|
||
return;
|
||
}
|
||
setting.Enable = enable == 1;
|
||
setting.Sensitivity = (SensitivityLevel)sens;
|
||
setting.SafeDistance = dist;
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 请输入格式: 开关,灵敏度,安全距离 (例如: 1,1,100)");
|
||
return;
|
||
}
|
||
}
|
||
|
||
UpdateStatus($"正在设置毫米波雷达: {setting}...");
|
||
Log($"发送写入毫米波雷达设置命令 (0x50): {setting}");
|
||
|
||
BLECommunicationManager.Instance.WriteMillimeterWaveSetting(setting, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"毫米波雷达设置成功: {setting}");
|
||
Log($"毫米波雷达设置成功: {setting}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("毫米波雷达设置失败");
|
||
Log("毫米波雷达设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取视觉检测设置
|
||
/// </summary>
|
||
private void OnReadVisualDetectionClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取视觉检测设置...");
|
||
Log("发送读取视觉检测设置命令 (0x51)");
|
||
|
||
BLECommunicationManager.Instance.ReadVisualDetectionSetting((setting) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string displayValue = $"{(setting.Enable ? 1 : 0)},{(byte)setting.Sensitivity}";
|
||
UpdateStatus($"视觉检测设置: {setting}");
|
||
Log($"读取视觉检测设置: {setting}");
|
||
|
||
if (SafetySettingInputField != null)
|
||
SafetySettingInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入视觉检测设置
|
||
/// 输入格式: 开关,灵敏度,例如: 1,1
|
||
/// </summary>
|
||
private void OnWriteVisualDetectionClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
var setting = new VisualDetectionSetting { Enable = true, Sensitivity = SensitivityLevel.Medium };
|
||
|
||
if (SafetySettingInputField != null && !string.IsNullOrEmpty(SafetySettingInputField.text))
|
||
{
|
||
string input = SafetySettingInputField.text.Trim();
|
||
var parts = input.Split(',');
|
||
|
||
if (parts.Length >= 2)
|
||
{
|
||
if (!int.TryParse(parts[0].Trim(), out int enable))
|
||
{
|
||
UpdateStatus("错误: 开关格式无效 (0或1)");
|
||
return;
|
||
}
|
||
if (!byte.TryParse(parts[1].Trim(), out byte sens))
|
||
{
|
||
UpdateStatus("错误: 灵敏度格式无效 (0-2)");
|
||
return;
|
||
}
|
||
setting.Enable = enable == 1;
|
||
setting.Sensitivity = (SensitivityLevel)sens;
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 请输入格式: 开关,灵敏度 (例如: 1,1)");
|
||
return;
|
||
}
|
||
}
|
||
|
||
UpdateStatus($"正在设置视觉检测: {setting}...");
|
||
Log($"发送写入视觉检测设置命令 (0x51): {setting}");
|
||
|
||
BLECommunicationManager.Instance.WriteVisualDetectionSetting(setting, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"视觉检测设置成功: {setting}");
|
||
Log($"视觉检测设置成功: {setting}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("视觉检测设置失败");
|
||
Log("视觉检测设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取加速度传感器设置
|
||
/// </summary>
|
||
private void OnReadAccelerometerSettingClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取加速度传感器设置...");
|
||
Log("发送读取加速度传感器设置命令 (0x52)");
|
||
|
||
BLECommunicationManager.Instance.ReadAccelerometerSetting((setting) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string displayValue = $"{(setting.Enable ? 1 : 0)},{(byte)setting.Sensitivity},{setting.VibrationThreshold}";
|
||
UpdateStatus($"加速度传感器设置: {setting}");
|
||
Log($"读取加速度传感器设置: {setting}");
|
||
|
||
if (SafetySettingInputField != null)
|
||
SafetySettingInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入加速度传感器设置
|
||
/// 输入格式: 开关,灵敏度,振动阈值,例如: 1,1,50
|
||
/// </summary>
|
||
private void OnWriteAccelerometerSettingClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
var setting = new AccelerometerSetting { Enable = true, Sensitivity = SensitivityLevel.Medium, VibrationThreshold = 50 };
|
||
|
||
if (SafetySettingInputField != null && !string.IsNullOrEmpty(SafetySettingInputField.text))
|
||
{
|
||
string input = SafetySettingInputField.text.Trim();
|
||
var parts = input.Split(',');
|
||
|
||
if (parts.Length >= 3)
|
||
{
|
||
if (!int.TryParse(parts[0].Trim(), out int enable))
|
||
{
|
||
UpdateStatus("错误: 开关格式无效 (0或1)");
|
||
return;
|
||
}
|
||
if (!byte.TryParse(parts[1].Trim(), out byte sens))
|
||
{
|
||
UpdateStatus("错误: 灵敏度格式无效 (0-2)");
|
||
return;
|
||
}
|
||
if (!byte.TryParse(parts[2].Trim(), out byte threshold))
|
||
{
|
||
UpdateStatus("错误: 振动阈值格式无效 (0-255)");
|
||
return;
|
||
}
|
||
setting.Enable = enable == 1;
|
||
setting.Sensitivity = (SensitivityLevel)sens;
|
||
setting.VibrationThreshold = threshold;
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 请输入格式: 开关,灵敏度,振动阈值 (例如: 1,1,50)");
|
||
return;
|
||
}
|
||
}
|
||
|
||
UpdateStatus($"正在设置加速度传感器: {setting}...");
|
||
Log($"发送写入加速度传感器设置命令 (0x52): {setting}");
|
||
|
||
BLECommunicationManager.Instance.WriteAccelerometerSetting(setting, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"加速度传感器设置成功: {setting}");
|
||
Log($"加速度传感器设置成功: {setting}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("加速度传感器设置失败");
|
||
Log("加速度传感器设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取加速度传感器数据
|
||
/// </summary>
|
||
private void OnReadAccelerometerDataClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取加速度传感器数据...");
|
||
Log("发送读取加速度传感器数据命令 (0x53)");
|
||
|
||
BLECommunicationManager.Instance.ReadAccelerometerData((data) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string displayValue = $"{data.X},{data.Y},{data.Z}";
|
||
UpdateStatus($"加速度传感器数据: {data}");
|
||
Log($"读取加速度传感器数据: {data}");
|
||
|
||
if (SafetySettingInputField != null)
|
||
SafetySettingInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取温度监控设置
|
||
/// </summary>
|
||
private void OnReadTemperatureMonitorClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取温度监控设置...");
|
||
Log("发送读取温度监控设置命令 (0x55)");
|
||
|
||
BLECommunicationManager.Instance.ReadTemperatureMonitorSetting((setting) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string displayValue = $"{setting.AlarmThreshold},{setting.StopThreshold},{(setting.Enable ? 1 : 0)}";
|
||
UpdateStatus($"温度监控设置: {setting}");
|
||
Log($"读取温度监控设置: {setting}");
|
||
|
||
if (SafetySettingInputField != null)
|
||
SafetySettingInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入温度监控设置
|
||
/// 输入格式: 告警阈值,停止阈值,开关,例如: 70,85,1
|
||
/// </summary>
|
||
private void OnWriteTemperatureMonitorClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
var setting = new TemperatureMonitorSetting { AlarmThreshold = 70, StopThreshold = 85, Enable = true };
|
||
|
||
if (SafetySettingInputField != null && !string.IsNullOrEmpty(SafetySettingInputField.text))
|
||
{
|
||
string input = SafetySettingInputField.text.Trim();
|
||
var parts = input.Split(',');
|
||
|
||
if (parts.Length >= 3)
|
||
{
|
||
if (!byte.TryParse(parts[0].Trim(), out byte alarm))
|
||
{
|
||
UpdateStatus("错误: 告警阈值格式无效");
|
||
return;
|
||
}
|
||
if (!byte.TryParse(parts[1].Trim(), out byte stop))
|
||
{
|
||
UpdateStatus("错误: 停止阈值格式无效");
|
||
return;
|
||
}
|
||
if (!int.TryParse(parts[2].Trim(), out int enable))
|
||
{
|
||
UpdateStatus("错误: 开关格式无效 (0或1)");
|
||
return;
|
||
}
|
||
setting.AlarmThreshold = alarm;
|
||
setting.StopThreshold = stop;
|
||
setting.Enable = enable == 1;
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 请输入格式: 告警阈值,停止阈值,开关 (例如: 70,85,1)");
|
||
return;
|
||
}
|
||
}
|
||
|
||
UpdateStatus($"正在设置温度监控: {setting}...");
|
||
Log($"发送写入温度监控设置命令 (0x55): {setting}");
|
||
|
||
BLECommunicationManager.Instance.WriteTemperatureMonitorSetting(setting, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"温度监控设置成功: {setting}");
|
||
Log($"温度监控设置成功: {setting}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("温度监控设置失败");
|
||
Log("温度监控设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取环境变化状态 (0x56)
|
||
/// </summary>
|
||
private void OnReadEnvironmentChangeClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取环境变化状态...");
|
||
Log("发送读取环境变化状态命令 (0x56读操作)");
|
||
|
||
BLECommunicationManager.Instance.ReadEnvironmentChangeStatus((status) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
UpdateStatus($"环境变化状态: {status}");
|
||
Log($"读取环境变化状态: {status}");
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 触发激光试射测试 (0x56)
|
||
/// </summary>
|
||
private void OnTriggerLaserTestClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在触发激光试射测试...");
|
||
Log("发送触发激光试射测试命令 (0x56写操作)");
|
||
Log("注意: 将进行3次试射,每次间隔1秒,每次持续10ms");
|
||
|
||
BLECommunicationManager.Instance.TriggerLaserTest((success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("激光试射测试已触发");
|
||
Log("激光试射测试已触发: 3次试射,间隔1秒,每次10ms");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("激光试射测试触发失败");
|
||
Log("激光试射测试触发失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 事件回调
|
||
|
||
private void OnBluetoothInitialized(bool success)
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("蓝牙初始化成功!");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("蓝牙初始化失败!");
|
||
}
|
||
}
|
||
|
||
private void OnDeviceFound(BluetoothDevice device)
|
||
{
|
||
string displayName = string.IsNullOrEmpty(device.Name) ? "Unknown" : device.Name;
|
||
device.Name = displayName;
|
||
AddOneDevice(device);
|
||
|
||
// UpdateStatus($"发现设备: {device.Name}");
|
||
}
|
||
|
||
private void OnDeviceConnected(string address)
|
||
{
|
||
UpdateStatus($"已连接到设备: {address}");
|
||
if (deviceStatusText != null)
|
||
deviceStatusText.text = $"已连接: {address}";
|
||
}
|
||
|
||
private void OnConnectFailed(string address)
|
||
{
|
||
UpdateStatus($"连接失败: {address}");
|
||
if (deviceStatusText != null)
|
||
deviceStatusText.text = "连接失败";
|
||
Log($"连接失败: {address}");
|
||
}
|
||
|
||
private void OnDeviceDisconnected(string address)
|
||
{
|
||
UpdateStatus($"已断开连接: {address}");
|
||
if (deviceStatusText != null)
|
||
deviceStatusText.text = "未连接";
|
||
}
|
||
|
||
private void OnBluetoothError(string error)
|
||
{
|
||
UpdateStatus($"错误: {error}");
|
||
}
|
||
|
||
private void OnBluetoothLog(string log)
|
||
{
|
||
Log(log);
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region BLE事件回调
|
||
|
||
private void OnRegistrationStatusReceived(DeviceRegistrationStatus status)
|
||
{
|
||
Log("收到注册状态事件通知");
|
||
}
|
||
|
||
private void OnRegisterResult(bool success, string message)
|
||
{
|
||
Log($"收到注册结果事件: {(success ? "成功" : "失败")}");
|
||
}
|
||
|
||
private void OnUserLoginResult(UserLoginResponse response)
|
||
{
|
||
Log($"收到用户登录结果事件: {(response.IsSuccess ? "成功" : "失败")}");
|
||
}
|
||
|
||
private void OnUserListReceived(UserListResponse response)
|
||
{
|
||
Log($"收到用户列表事件: 共 {response.UserCount} 个用户");
|
||
}
|
||
|
||
private void OnUnregisterUserResult(UnregisterUserResponse response)
|
||
{
|
||
Log($"收到注销用户结果事件: {(response.IsSuccess ? "成功" : "失败")}");
|
||
}
|
||
|
||
private void OnFingerprintEnableResult(FingerprintEnableResponse response)
|
||
{
|
||
Log($"收到指纹使能设置结果事件: {(response.IsSuccess ? "成功" : "失败")}");
|
||
}
|
||
|
||
private void OnFingerprintRecordResult(FingerprintRecordResponse response)
|
||
{
|
||
Log($"收到指纹录制结果事件: {(response.IsSuccess ? "成功" : "失败")}");
|
||
}
|
||
|
||
private void OnLanguageSettingReceived(LanguageSetting setting)
|
||
{
|
||
Log($"收到语言设置事件: {(setting.IsChinese ? "中文" : "英文")}");
|
||
}
|
||
|
||
private void OnTimeSettingReceived(TimeSetting setting)
|
||
{
|
||
Log($"收到时间设置事件: {setting}");
|
||
}
|
||
|
||
private void OnScheduleTaskListReceived(ScheduleTaskListResponse response)
|
||
{
|
||
if (response.IsSuccess)
|
||
{
|
||
Log($"收到定时任务列表事件: 共 {response.Tasks.Length} 个任务");
|
||
}
|
||
else
|
||
{
|
||
Log("收到定时任务列表事件: 读取失败");
|
||
}
|
||
}
|
||
|
||
private void OnLCDSleepSettingReceived(LCDSleepSetting setting)
|
||
{
|
||
Log($"收到LCD休眠设置事件: 开关={(setting.Enable ? "开启" : "关闭")}, 时间={setting.GetSleepTimeString()}");
|
||
}
|
||
|
||
private void OnLCDBrightnessSettingReceived(LCDBrightnessSetting setting)
|
||
{
|
||
Log($"收到LCD亮度设置事件: 自适应={(setting.AutoBrightness ? "开启" : "关闭")}, 亮度={setting.Brightness}%");
|
||
}
|
||
|
||
private void OnRGBControlReceived(RGBControl control)
|
||
{
|
||
string effectStr = control.Effect switch
|
||
{
|
||
RGBEffectMode.Off => "关闭",
|
||
RGBEffectMode.Solid => "常亮",
|
||
RGBEffectMode.Blinking => "闪烁",
|
||
RGBEffectMode.Warning => "警示",
|
||
_ => "未知"
|
||
};
|
||
Log($"收到RGB控制事件: 开关={(control.Enable ? "开启" : "关闭")}, 颜色={control.Red},{control.Green},{control.Blue}, 效果={effectStr}");
|
||
}
|
||
|
||
private void OnWIFIControlReceived(WIFIControl control)
|
||
{
|
||
Log($"收到WIFI控制事件: 开关={(control.Enable ? "开启" : "关闭")}, SSID={control.SSID}");
|
||
}
|
||
|
||
private void OnBLEControlReceived(BLEControl control)
|
||
{
|
||
Log($"收到BLE控制事件: 设备名称={control.DeviceName}");
|
||
}
|
||
|
||
private void OnMultimediaControlReceived(MultimediaControl control)
|
||
{
|
||
Log($"收到多媒体控制事件: 视频录制={(control.VideoRecordEnable ? "开启" : "关闭")}, 音效={(control.SoundEnable ? "开启" : "关闭")}");
|
||
}
|
||
|
||
private void OnFillLightControlReceived(FillLightControl control)
|
||
{
|
||
Log($"收到补光灯控制事件: 开关={(control.Enable ? "开启" : "关闭")}, 类型={control.GetLightTypeString()}, 强度={control.GetIntensityString()}");
|
||
}
|
||
|
||
private void OnVisibleLaserControlReceived(VisibleLaserControl control)
|
||
{
|
||
Log($"收到可见光激光器控制事件: 开关={(control.Enable ? "开启" : "关闭")}");
|
||
}
|
||
|
||
private void OnFillLightConnectionStatusReceived(FillLightConnectionStatus status)
|
||
{
|
||
Log($"收到补光灯连接状态事件: {(status.IsConnected ? "已连接" : "未连接")}");
|
||
}
|
||
|
||
private void OnMillimeterWaveSettingReceived(MillimeterWaveSetting setting)
|
||
{
|
||
Log($"收到毫米波雷达设置事件: {setting}");
|
||
}
|
||
|
||
private void OnVisualDetectionSettingReceived(VisualDetectionSetting setting)
|
||
{
|
||
Log($"收到视觉检测设置事件: {setting}");
|
||
}
|
||
|
||
private void OnAccelerometerSettingReceived(AccelerometerSetting setting)
|
||
{
|
||
Log($"收到加速度传感器设置事件: {setting}");
|
||
}
|
||
|
||
private void OnAccelerometerDataReceived(AccelerometerData data)
|
||
{
|
||
Log($"收到加速度传感器数据事件: {data}");
|
||
}
|
||
|
||
private void OnTemperatureMonitorSettingReceived(TemperatureMonitorSetting setting)
|
||
{
|
||
Log($"收到温度监控设置事件: {setting}");
|
||
}
|
||
|
||
private void OnEnvironmentChangeStatusReceived(EnvironmentChangeTest status)
|
||
{
|
||
Log($"收到环境变化状态事件: {status}");
|
||
}
|
||
|
||
private void OnWorkModeSettingReceived(WorkModeSetting setting)
|
||
{
|
||
Log($"收到工作模式设置事件: {setting}");
|
||
}
|
||
|
||
private void OnHardwareStatusReceived(HardwareStatus status)
|
||
{
|
||
Log($"收到硬件状态事件: {status}");
|
||
}
|
||
|
||
private void OnDeviceInfoReceived(DeviceInfo info)
|
||
{
|
||
Log($"收到设备信息事件: {info}");
|
||
}
|
||
|
||
private void OnStatisticsDataReceived(StatisticsData stats)
|
||
{
|
||
Log($"收到统计数据事件: {stats}");
|
||
}
|
||
|
||
private void OnSensorDataReceived(SensorData data)
|
||
{
|
||
Log($"收到传感器数据事件: {data}");
|
||
}
|
||
|
||
private void OnAngleControlReceived(AngleControl control)
|
||
{
|
||
Log($"收到角度控制事件: {control}");
|
||
}
|
||
|
||
private void OnDistanceControlReceived(DistanceControl control)
|
||
{
|
||
Log($"收到距离控制事件: {control}");
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 状态查询
|
||
|
||
/// <summary>
|
||
/// 读取工作模式
|
||
/// </summary>
|
||
private void OnReadWorkModeClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在读取工作模式...");
|
||
Log("发送读取工作模式命令 (0xA0)");
|
||
|
||
BLECommunicationManager.Instance.ReadWorkMode((setting) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string displayValue = ((byte)setting.Mode).ToString();
|
||
UpdateStatus($"工作模式: {setting}");
|
||
Log($"读取工作模式: {setting}");
|
||
|
||
if (StatusQueryInputField != null)
|
||
StatusQueryInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入工作模式
|
||
/// 输入格式: 模式值(0=待机,1=扫描,2=消杀),例如: 1
|
||
/// </summary>
|
||
private void OnWriteWorkModeClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
var setting = new WorkModeSetting { Mode = WorkMode.Standby };
|
||
|
||
if (StatusQueryInputField != null && !string.IsNullOrEmpty(StatusQueryInputField.text))
|
||
{
|
||
string input = StatusQueryInputField.text.Trim();
|
||
|
||
if (byte.TryParse(input, out byte mode))
|
||
{
|
||
setting.Mode = (WorkMode)mode;
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 请输入有效的工作模式 (0=待机, 1=扫描, 2=消杀)");
|
||
return;
|
||
}
|
||
}
|
||
|
||
UpdateStatus($"正在设置工作模式: {setting}...");
|
||
Log($"发送写入工作模式命令 (0xA0): {setting}");
|
||
|
||
BLECommunicationManager.Instance.WriteWorkMode(setting, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"工作模式设置成功: {setting}");
|
||
Log($"工作模式设置成功: {setting}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("工作模式设置失败");
|
||
Log("工作模式设置失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取硬件状态
|
||
/// </summary>
|
||
private void OnReadHardwareStatusClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在查询硬件状态...");
|
||
Log("发送查询硬件状态命令 (0xA1)");
|
||
|
||
BLECommunicationManager.Instance.ReadHardwareStatus((status) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
UpdateStatus($"硬件状态: {status}");
|
||
Log($"查询硬件状态: {status}");
|
||
|
||
if (StatusQueryInputField != null)
|
||
StatusQueryInputField.text = status.ToString();
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取设备信息 (0xA2读操作)
|
||
/// </summary>
|
||
private void OnReadDeviceInfoClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在查询设备信息...");
|
||
Log("发送查询设备信息命令 (0xA2读操作)");
|
||
|
||
BLECommunicationManager.Instance.ReadDeviceInfo((info) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
// 输入框显示5个字段,与写操作格式一致:序列号|型号|ID|固件版本|硬件版本
|
||
string displayValue = $"{info.GetSerialNumberString()}|{info.GetDeviceModelString()}|{info.GetDeviceIdString()}|{info.GetFirmwareVersionString()}|{info.GetHardwareVersionString()}";
|
||
UpdateStatus($"设备信息: {info}");
|
||
Log($"查询设备信息: 序列号={info.GetSerialNumberString()}, 型号={info.GetDeviceModelString()}, ID={info.GetDeviceIdString()}, BLE_MAC={info.GetBleMacAddressString()}, WiFi_MAC={info.GetWifiMacAddressString()}, 固件={info.GetFirmwareVersionString()}, 硬件={info.GetHardwareVersionString()}, OTA={info.GetOtaVersionString()}");
|
||
|
||
if (StatusQueryInputField != null)
|
||
StatusQueryInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写入设备信息 (0xA2写操作)
|
||
/// 输入格式: 序列号|型号|ID|固件版本|硬件版本
|
||
/// 例如: SN123456|MODEL-A|DEV001|100|200
|
||
/// </summary>
|
||
private void OnWriteDeviceInfoClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
// 解析输入
|
||
string serialNumber = "DEFAULT_SN";
|
||
string deviceModel = "DEFAULT_MODEL";
|
||
string deviceId = "DEFAULT_ID";
|
||
uint firmwareVersion = 0;
|
||
uint hardwareVersion = 0;
|
||
|
||
if (StatusQueryInputField != null && !string.IsNullOrEmpty(StatusQueryInputField.text))
|
||
{
|
||
string input = StatusQueryInputField.text.Trim();
|
||
var parts = input.Split('|');
|
||
|
||
if (parts.Length >= 5)
|
||
{
|
||
serialNumber = parts[0].Trim();
|
||
deviceModel = parts[1].Trim();
|
||
deviceId = parts[2].Trim();
|
||
|
||
// 解析固件版本(支持 x.x.x.x 格式或整数格式)
|
||
string fwVersionStr = parts[3].Trim();
|
||
if (!ParseVersionString(fwVersionStr, out firmwareVersion))
|
||
{
|
||
UpdateStatus("错误: 固件版本格式无效,请使用 x.x.x.x 格式(如 1.0.0.0)");
|
||
return;
|
||
}
|
||
|
||
// 解析硬件版本(支持 x.x.x.x 格式或整数格式)
|
||
string hwVersionStr = parts[4].Trim();
|
||
if (!ParseVersionString(hwVersionStr, out hardwareVersion))
|
||
{
|
||
UpdateStatus("错误: 硬件版本格式无效,请使用 x.x.x.x 格式(如 1.0.0.0)");
|
||
return;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 请输入格式: 序列号|型号|ID|固件版本|硬件版本 (例如: SN123456|MODEL-A|DEV001|1.0.0.0|1.0.0.0)");
|
||
return;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 请输入设备信息格式: 序列号|型号|ID|固件版本|硬件版本");
|
||
return;
|
||
}
|
||
|
||
var deviceInfo = new DeviceInfoWrite(serialNumber, deviceModel, deviceId, firmwareVersion, hardwareVersion);
|
||
|
||
UpdateStatus($"正在写入设备信息: {deviceInfo}...");
|
||
Log($"发送写入设备信息命令 (0xA2写操作): {deviceInfo}");
|
||
|
||
BLECommunicationManager.Instance.WriteDeviceInfo(deviceInfo, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"设备信息写入成功: {deviceInfo}");
|
||
Log($"设备信息写入成功: {deviceInfo}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("设备信息写入失败");
|
||
Log("设备信息写入失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取统计数据
|
||
/// </summary>
|
||
private void OnReadStatisticsClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在查询统计数据...");
|
||
Log("发送查询统计数据命令 (0xA3)");
|
||
|
||
BLECommunicationManager.Instance.ReadStatisticsData((stats) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
UpdateStatus($"统计数据: {stats}");
|
||
Log($"查询统计数据: {stats}");
|
||
|
||
if (StatusQueryInputField != null)
|
||
StatusQueryInputField.text = stats.ToString();
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 查询蚊虫数据
|
||
/// 输入格式: 起始索引,结束索引,例如: 0,10
|
||
/// </summary>
|
||
private void OnQueryMosquitoDataClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
var query = new MosquitoDataQuery { StartIndex = 0, EndIndex = 10 };
|
||
|
||
if (StatusQueryInputField != null && !string.IsNullOrEmpty(StatusQueryInputField.text))
|
||
{
|
||
string input = StatusQueryInputField.text.Trim();
|
||
var parts = input.Split(',');
|
||
|
||
if (parts.Length >= 2)
|
||
{
|
||
if (!uint.TryParse(parts[0].Trim(), out uint start))
|
||
{
|
||
UpdateStatus("错误: 起始索引格式无效");
|
||
return;
|
||
}
|
||
if (!uint.TryParse(parts[1].Trim(), out uint end))
|
||
{
|
||
UpdateStatus("错误: 结束索引格式无效");
|
||
return;
|
||
}
|
||
query.StartIndex = start;
|
||
query.EndIndex = end;
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 请输入格式: 起始索引,结束索引 (例如: 0,10)");
|
||
return;
|
||
}
|
||
}
|
||
|
||
UpdateStatus($"正在查询蚊虫数据: {query}...");
|
||
Log($"发送查询蚊虫数据命令 (0xA4): {query}");
|
||
|
||
BLECommunicationManager.Instance.QueryMosquitoData(query, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"蚊虫数据查询成功: {query}");
|
||
Log($"蚊虫数据查询成功: {query}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("蚊虫数据查询失败");
|
||
Log("蚊虫数据查询失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取传感器数据
|
||
/// </summary>
|
||
private void OnReadSensorDataClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在查询传感器数据...");
|
||
Log("发送查询传感器数据命令 (0xA5)");
|
||
|
||
BLECommunicationManager.Instance.ReadSensorData((data) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
string displayValue = $"{data.GetTemperatureCelsius():F1},{data.AccelX},{data.AccelY},{data.AccelZ},{data.GetCapacitorVoltage():F2}";
|
||
UpdateStatus($"传感器数据: {data}");
|
||
Log($"查询传感器数据: {data}");
|
||
|
||
if (StatusQueryInputField != null)
|
||
StatusQueryInputField.text = displayValue;
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取所有蚊虫数据 (0xA4)
|
||
/// 流程:1.查询数量 -> 2.请求数据 -> 3.接收通知
|
||
/// </summary>
|
||
private void OnGetAllMosquitoDataClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
// 清空之前的数据
|
||
_mosquitoDataList.Clear();
|
||
UpdateMosquitoDataDisplay();
|
||
|
||
UpdateStatus("正在查询蚊虫数据数量...");
|
||
Log("步骤1: 发送查询蚊虫数据数量命令 (0xA4读操作)");
|
||
|
||
// 步骤1: 查询蚊虫数据数量
|
||
BLECommunicationManager.Instance.ReadMosquitoDataCount((count) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (count.Count == 0)
|
||
{
|
||
UpdateStatus("设备中没有蚊虫数据");
|
||
Log("设备中没有蚊虫数据");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus($"检测到 {count.Count} 条蚊虫数据,正在请求...");
|
||
Log($"步骤2: 检测到 {count.Count} 条数据,发送请求命令 (0xA4写操作)");
|
||
|
||
// 步骤2: 请求所有蚊虫数据
|
||
BLECommunicationManager.Instance.RequestMosquitoData(count.Count, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus($"已请求 {count.Count} 条蚊虫数据,等待接收...");
|
||
Log($"步骤3: 请求成功,等待设备通过通知发送数据 (通知类型0x0B)");
|
||
// 数据将通过 OnMosquitoDataReceived 事件接收
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("蚊虫数据请求失败");
|
||
Log("蚊虫数据请求失败");
|
||
}
|
||
});
|
||
});
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 收到蚊虫数据事件回调
|
||
/// </summary>
|
||
private void OnMosquitoDataReceived(MosquitoData data)
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
_mosquitoDataList.Add(data);
|
||
Log($"收到蚊虫数据 [{_mosquitoDataList.Count}]: {data}");
|
||
UpdateMosquitoDataDisplay();
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 更新蚊虫数据显示
|
||
/// </summary>
|
||
private void UpdateMosquitoDataDisplay()
|
||
{
|
||
if (MosquitoDataDisplay == null) return;
|
||
|
||
if (_mosquitoDataList.Count == 0)
|
||
{
|
||
MosquitoDataDisplay.text = "暂无蚊虫数据\n点击\"获取所有蚊虫数据\"按钮查询";
|
||
return;
|
||
}
|
||
|
||
System.Text.StringBuilder sb = new System.Text.StringBuilder();
|
||
sb.AppendLine($"共 {_mosquitoDataList.Count} 条蚊虫数据:");
|
||
sb.AppendLine("----------------------------------------");
|
||
|
||
// 只显示最近10条,避免UI卡顿
|
||
int displayCount = Mathf.Min(_mosquitoDataList.Count, 10);
|
||
for (int i = 0; i < displayCount; i++)
|
||
{
|
||
var data = _mosquitoDataList[i];
|
||
sb.AppendLine($"{i + 1}. {data}");
|
||
}
|
||
|
||
if (_mosquitoDataList.Count > 10)
|
||
{
|
||
sb.AppendLine($"... 还有 {_mosquitoDataList.Count - 10} 条数据");
|
||
}
|
||
|
||
MosquitoDataDisplay.text = sb.ToString();
|
||
}
|
||
|
||
#endregion
|
||
|
||
private void OnRawDataReceived(string hexData)
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (revicedText != null)
|
||
{
|
||
// 追加到文本末尾,另起一行
|
||
string newLine = $"[{System.DateTime.Now:HH:mm:ss}] ← {hexData}";
|
||
if (string.IsNullOrEmpty(revicedText.text))
|
||
{
|
||
revicedText.text = newLine;
|
||
}
|
||
else
|
||
{
|
||
revicedText.text += "\n" + newLine;
|
||
}
|
||
|
||
// 限制行数,避免UI卡顿
|
||
string[] lines = revicedText.text.Split('\n');
|
||
if (lines.Length > 200)
|
||
{
|
||
revicedText.text = string.Join("\n", lines, lines.Length - 200, 200);
|
||
}
|
||
}
|
||
Log($"收到原始数据: {hexData}");
|
||
});
|
||
}
|
||
|
||
private void OnRawDataSent(string hexData)
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (revicedText != null)
|
||
{
|
||
// 追加到文本末尾,另起一行
|
||
string newLine = $"[{System.DateTime.Now:HH:mm:ss}] → {hexData}";
|
||
if (string.IsNullOrEmpty(revicedText.text))
|
||
{
|
||
revicedText.text = newLine;
|
||
}
|
||
else
|
||
{
|
||
revicedText.text += "\n" + newLine;
|
||
}
|
||
|
||
// 限制行数,避免UI卡顿
|
||
string[] lines = revicedText.text.Split('\n');
|
||
if (lines.Length > 200)
|
||
{
|
||
revicedText.text = string.Join("\n", lines, lines.Length - 200, 200);
|
||
}
|
||
}
|
||
Log($"发送原始数据: {hexData}");
|
||
});
|
||
}
|
||
|
||
private void OnCommunicationError(string error)
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
UpdateStatus($"通信错误: {error}");
|
||
Log($"错误: {error}");
|
||
});
|
||
}
|
||
|
||
private void UpdateStatus(string message)
|
||
{
|
||
if (StatusText != null)
|
||
{
|
||
StatusText.text = message;
|
||
}
|
||
Debug.Log($"[BluetoothDemo] {message}");
|
||
}
|
||
|
||
private void Log(string message)
|
||
{
|
||
Debug.Log($"[BluetoothDemo] {message}");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析版本号字符串(支持 x.x.x.x 格式或整数格式)
|
||
/// </summary>
|
||
private bool ParseVersionString(string versionStr, out uint version)
|
||
{
|
||
version = 0;
|
||
if (string.IsNullOrEmpty(versionStr)) return false;
|
||
|
||
// 尝试直接解析为整数
|
||
if (uint.TryParse(versionStr, out version))
|
||
{
|
||
return true;
|
||
}
|
||
|
||
// 尝试解析 x.x.x.x 格式
|
||
var parts = versionStr.Split('.');
|
||
if (parts.Length != 4) return false;
|
||
|
||
if (!byte.TryParse(parts[0], out byte v1)) return false;
|
||
if (!byte.TryParse(parts[1], out byte v2)) return false;
|
||
if (!byte.TryParse(parts[2], out byte v3)) return false;
|
||
if (!byte.TryParse(parts[3], out byte v4)) return false;
|
||
|
||
// 组合为 uint(小端序)
|
||
version = (uint)(v1 | (v2 << 8) | (v3 << 16) | (v4 << 24));
|
||
return true;
|
||
}
|
||
|
||
#region 设备管理
|
||
|
||
/// <summary>
|
||
/// 恢复出厂设置 (0x60)
|
||
/// 需要管理员权限
|
||
/// </summary>
|
||
private void OnFactoryResetClick()
|
||
{
|
||
if (BLECommunicationManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: BLECommunicationManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
// 确认对话框
|
||
// 注意:实际项目中应该使用UI对话框,这里简化处理
|
||
UpdateStatus("正在恢复出厂设置...");
|
||
Log("发送恢复出厂设置命令 (0x60)");
|
||
Log("警告: 恢复出厂设置将清除所有用户数据和配置!");
|
||
|
||
BLECommunicationManager.Instance.FactoryReset((success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("恢复出厂设置成功,设备将重启");
|
||
Log("恢复出厂设置成功,设备将重启");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("恢复出厂设置失败,请检查是否具有管理员权限");
|
||
Log("恢复出厂设置失败,请检查是否具有管理员权限");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region OTA升级
|
||
|
||
/// <summary>
|
||
/// 查询OTA版本信息 (0x80)
|
||
/// </summary>
|
||
private void OnOTAQueryVersionClick()
|
||
{
|
||
if (OTAManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: OTAManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在查询OTA版本信息...");
|
||
Log("查询OTA版本信息 (0x80)");
|
||
|
||
OTAManager.Instance.QueryVersionInfo((info) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (info != null)
|
||
{
|
||
UpdateStatus($"OTA版本: 固件={info.FirmwareVersion}, 硬件={info.HardwareVersion}");
|
||
Log($"OTA版本信息: {info}");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("查询OTA版本信息失败");
|
||
Log("查询OTA版本信息失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 选择固件文件
|
||
/// </summary>
|
||
private void OnOTASelectFileClick()
|
||
{
|
||
#if UNITY_ANDROID && !UNITY_EDITOR
|
||
// Android平台 - 使用原生文件选择器
|
||
if (AndroidFilePicker.Instance != null)
|
||
{
|
||
// 取消之前的订阅
|
||
AndroidFilePicker.Instance.OnFileSelected -= OnAndroidFileSelected;
|
||
AndroidFilePicker.Instance.OnFileSelectCanceled -= OnAndroidFileSelectCanceled;
|
||
AndroidFilePicker.Instance.OnError -= OnAndroidFileError;
|
||
|
||
// 订阅事件
|
||
AndroidFilePicker.Instance.OnFileSelected += OnAndroidFileSelected;
|
||
AndroidFilePicker.Instance.OnFileSelectCanceled += OnAndroidFileSelectCanceled;
|
||
AndroidFilePicker.Instance.OnError += OnAndroidFileError;
|
||
|
||
// 打开文件选择器,限制为二进制文件
|
||
string[] mimeTypes = new string[] { "application/octet-stream", "*/*" };
|
||
AndroidFilePicker.Instance.PickFile(mimeTypes);
|
||
|
||
UpdateStatus("正在打开文件选择器...");
|
||
Log("[FILE-PICKER] [UI] 打开Android文件选择器");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: AndroidFilePicker 未初始化");
|
||
Log("错误: AndroidFilePicker 未初始化,请确保场景中有AndroidFilePicker对象");
|
||
}
|
||
#elif UNITY_EDITOR
|
||
// Editor平台使用文件对话框
|
||
string path = UnityEditor.EditorUtility.OpenFilePanel("选择固件文件", "", "bin");
|
||
if (!string.IsNullOrEmpty(path))
|
||
{
|
||
LoadFirmwareFile(path);
|
||
}
|
||
#else
|
||
// 其他平台使用Application.persistentDataPath
|
||
string testPath = Path.Combine(Application.persistentDataPath, "firmware.bin");
|
||
if (File.Exists(testPath))
|
||
{
|
||
LoadFirmwareFile(testPath);
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("请将固件文件复制到: " + testPath);
|
||
Log($"请将固件文件复制到: {testPath}");
|
||
}
|
||
#endif
|
||
}
|
||
|
||
#if UNITY_ANDROID && !UNITY_EDITOR
|
||
/// <summary>
|
||
/// Android文件选择成功回调
|
||
/// </summary>
|
||
private void OnAndroidFileSelected(string filePath, string fileName, byte[] fileData)
|
||
{
|
||
Log("[FILE-PICKER] [UI] OnAndroidFileSelected 被调用");
|
||
|
||
// 取消订阅
|
||
if (AndroidFilePicker.Instance != null)
|
||
{
|
||
AndroidFilePicker.Instance.OnFileSelected -= OnAndroidFileSelected;
|
||
AndroidFilePicker.Instance.OnFileSelectCanceled -= OnAndroidFileSelectCanceled;
|
||
AndroidFilePicker.Instance.OnError -= OnAndroidFileError;
|
||
}
|
||
|
||
Log($"[FILE-PICKER] [UI] Android文件选择成功: filePath={filePath}, fileName={fileName}, fileData长度={fileData?.Length ?? 0}");
|
||
|
||
// 直接使用已读取的文件数据
|
||
if (fileData != null && fileData.Length > 0)
|
||
{
|
||
Log($"[FILE-PICKER] [UI] 文件数据有效,开始检查文件限制...");
|
||
|
||
// 检查文件限制
|
||
if (CheckFirmwareFile(fileName, fileData.Length))
|
||
{
|
||
Log("[FILE-PICKER] [UI] 文件检查通过,保存固件数据...");
|
||
_selectedFirmwareData = fileData;
|
||
_selectedFirmwarePath = filePath;
|
||
|
||
// 更新UI
|
||
string fileSizeStr = FormatFileSize(fileData.Length);
|
||
if (OTAInfoText != null)
|
||
OTAInfoText.text = $"=== 固件信息 ===\n文件名: {fileName}\n大小: {fileSizeStr}\n路径: {filePath}";
|
||
|
||
UpdateStatus($"已选择固件: {fileName} ({fileSizeStr})");
|
||
Log($"[FILE-PICKER] [UI] 已选择固件文件: {fileName}, 大小: {fileData.Length}字节");
|
||
}
|
||
else
|
||
{
|
||
Log("[FILE-PICKER] [UI] 文件检查未通过");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("错误: 文件数据为空");
|
||
Log("[FILE-PICKER] [UI] 错误: 从Android返回的文件数据为空");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Android文件选择取消回调
|
||
/// </summary>
|
||
private void OnAndroidFileSelectCanceled()
|
||
{
|
||
// 取消订阅
|
||
if (AndroidFilePicker.Instance != null)
|
||
{
|
||
AndroidFilePicker.Instance.OnFileSelected -= OnAndroidFileSelected;
|
||
AndroidFilePicker.Instance.OnFileSelectCanceled -= OnAndroidFileSelectCanceled;
|
||
AndroidFilePicker.Instance.OnError -= OnAndroidFileError;
|
||
}
|
||
|
||
UpdateStatus("用户取消选择文件");
|
||
Log("[FILE-PICKER] [UI] 用户取消选择文件");
|
||
}
|
||
|
||
/// <summary>
|
||
/// Android文件选择错误回调
|
||
/// </summary>
|
||
private void OnAndroidFileError(string error)
|
||
{
|
||
// 取消订阅
|
||
if (AndroidFilePicker.Instance != null)
|
||
{
|
||
AndroidFilePicker.Instance.OnFileSelected -= OnAndroidFileSelected;
|
||
AndroidFilePicker.Instance.OnFileSelectCanceled -= OnAndroidFileSelectCanceled;
|
||
AndroidFilePicker.Instance.OnError -= OnAndroidFileError;
|
||
}
|
||
|
||
UpdateStatus($"文件选择错误: {error}");
|
||
Log($"Android文件选择错误: {error}");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 检查固件文件是否符合要求
|
||
/// </summary>
|
||
private bool CheckFirmwareFile(string fileName, long fileSize)
|
||
{
|
||
// 检查文件扩展名
|
||
string extension = Path.GetExtension(fileName).ToLower();
|
||
if (Array.IndexOf(ALLOWED_EXTENSIONS, extension) < 0)
|
||
{
|
||
UpdateStatus($"错误: 不支持的文件格式 '{extension}',请使用 {string.Join(", ", ALLOWED_EXTENSIONS)} 文件");
|
||
return false;
|
||
}
|
||
|
||
// 检查文件大小
|
||
if (fileSize < MIN_FIRMWARE_SIZE)
|
||
{
|
||
UpdateStatus($"错误: 文件太小 ({FormatFileSize(fileSize)}),最小要求 {FormatFileSize(MIN_FIRMWARE_SIZE)}");
|
||
return false;
|
||
}
|
||
|
||
if (fileSize > MAX_FIRMWARE_SIZE)
|
||
{
|
||
UpdateStatus($"错误: 文件太大 ({FormatFileSize(fileSize)}),最大限制 {FormatFileSize(MAX_FIRMWARE_SIZE)}");
|
||
return false;
|
||
}
|
||
|
||
return true;
|
||
}
|
||
#endif
|
||
|
||
/// <summary>
|
||
/// 加载固件文件
|
||
/// </summary>
|
||
// 固件文件限制
|
||
private const long MAX_FIRMWARE_SIZE = 1024 * 1024; // 最大1MB
|
||
private const int MIN_FIRMWARE_SIZE = 256; // 最小256字节
|
||
private readonly string[] ALLOWED_EXTENSIONS = { ".bin", ".hex", ".fw" };
|
||
|
||
private void LoadFirmwareFile(string filePath)
|
||
{
|
||
try
|
||
{
|
||
if (!File.Exists(filePath))
|
||
{
|
||
UpdateStatus($"错误: 文件不存在: {filePath}");
|
||
return;
|
||
}
|
||
|
||
// 检查文件扩展名
|
||
string extension = Path.GetExtension(filePath).ToLower();
|
||
if (Array.IndexOf(ALLOWED_EXTENSIONS, extension) < 0)
|
||
{
|
||
UpdateStatus($"错误: 不支持的文件格式 '{extension}',请使用 {string.Join(", ", ALLOWED_EXTENSIONS)} 文件");
|
||
return;
|
||
}
|
||
|
||
// 获取文件大小
|
||
FileInfo fileInfo = new FileInfo(filePath);
|
||
long fileSize = fileInfo.Length;
|
||
|
||
// 检查文件大小
|
||
if (fileSize < MIN_FIRMWARE_SIZE)
|
||
{
|
||
UpdateStatus($"错误: 文件太小 ({FormatFileSize(fileSize)}),最小要求 {FormatFileSize(MIN_FIRMWARE_SIZE)}");
|
||
return;
|
||
}
|
||
|
||
if (fileSize > MAX_FIRMWARE_SIZE)
|
||
{
|
||
UpdateStatus($"错误: 文件太大 ({FormatFileSize(fileSize)}),最大限制 {FormatFileSize(MAX_FIRMWARE_SIZE)}");
|
||
return;
|
||
}
|
||
|
||
// 读取文件
|
||
_selectedFirmwareData = File.ReadAllBytes(filePath);
|
||
_selectedFirmwarePath = filePath;
|
||
|
||
string fileName = Path.GetFileName(filePath);
|
||
string fileSizeStr = FormatFileSize(fileSize);
|
||
|
||
// 更新UI
|
||
if (OTAInfoText != null)
|
||
OTAInfoText.text = $"=== 固件信息 ===\n文件名: {fileName}\n大小: {fileSizeStr}\n路径: {filePath}";
|
||
|
||
UpdateStatus($"已选择固件: {fileName} ({fileSizeStr})");
|
||
Log($"已选择固件文件: {filePath}, 大小: {fileSize}字节");
|
||
}
|
||
catch (System.Exception ex)
|
||
{
|
||
UpdateStatus($"加载固件文件失败: {ex.Message}");
|
||
Log($"加载固件文件失败: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 格式化文件大小
|
||
/// </summary>
|
||
private string FormatFileSize(long bytes)
|
||
{
|
||
if (bytes < 1024) return $"{bytes} B";
|
||
if (bytes < 1024 * 1024) return $"{bytes / 1024.0:F2} KB";
|
||
if (bytes < 1024 * 1024 * 1024) return $"{bytes / (1024.0 * 1024.0):F2} MB";
|
||
return $"{bytes / (1024.0 * 1024.0 * 1024.0):F2} GB";
|
||
}
|
||
|
||
/// <summary>
|
||
/// 开始OTA升级 (0x81)
|
||
/// </summary>
|
||
private void OnOTAStartUpgradeClick()
|
||
{
|
||
if (OTAManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: OTAManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
if (!BluetoothManager.Instance.IsConnected)
|
||
{
|
||
UpdateStatus("错误: 蓝牙未连接");
|
||
return;
|
||
}
|
||
|
||
// 检查是否有已选择的固件文件
|
||
if (_selectedFirmwareData == null || _selectedFirmwareData.Length == 0)
|
||
{
|
||
UpdateStatus("错误: 请先选择固件文件");
|
||
return;
|
||
}
|
||
|
||
// 解析版本号(从文件名或输入框)
|
||
uint firmwareVersion = ParseFirmwareVersion(_selectedFirmwarePath);
|
||
|
||
UpdateStatus($"开始OTA升级: 文件大小={FormatFileSize(_selectedFirmwareData.Length)}");
|
||
Log($"开始OTA升级: 文件={_selectedFirmwarePath}, 大小={_selectedFirmwareData.Length}字节, 版本={firmwareVersion}");
|
||
|
||
StartCoroutine(OTAManager.Instance.PerformFullUpgrade(_selectedFirmwareData, firmwareVersion, (success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("OTA升级成功!设备将重启");
|
||
Log("OTA升级成功!设备将重启应用新固件");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("OTA升级失败");
|
||
Log("OTA升级失败");
|
||
}
|
||
});
|
||
}));
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析固件版本号
|
||
/// </summary>
|
||
private uint ParseFirmwareVersion(string filePath)
|
||
{
|
||
// 尝试从文件名解析版本号,例如:firmware_v1.2.3.bin
|
||
try
|
||
{
|
||
string fileName = Path.GetFileNameWithoutExtension(filePath);
|
||
// 查找 v 或 V 开头的版本号
|
||
int vIndex = fileName.IndexOf('v');
|
||
if (vIndex < 0) vIndex = fileName.IndexOf('V');
|
||
|
||
if (vIndex >= 0 && vIndex + 1 < fileName.Length)
|
||
{
|
||
string versionStr = fileName.Substring(vIndex + 1);
|
||
// 尝试解析版本号,支持格式:1.2.3 或 1_2_3
|
||
versionStr = versionStr.Replace('_', '.');
|
||
string[] parts = versionStr.Split('.');
|
||
|
||
if (parts.Length >= 3 &&
|
||
uint.TryParse(parts[0], out uint major) &&
|
||
uint.TryParse(parts[1], out uint minor) &&
|
||
uint.TryParse(parts[2], out uint patch))
|
||
{
|
||
// 版本号格式:主版本.次版本.修订号 -> 32位整数
|
||
return (major << 16) | (minor << 8) | patch;
|
||
}
|
||
}
|
||
}
|
||
catch { }
|
||
|
||
// 默认返回版本号 1
|
||
return 1;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 取消OTA升级 (0x85)
|
||
/// </summary>
|
||
private void OnOTACancelUpgradeClick()
|
||
{
|
||
if (OTAManager.Instance == null)
|
||
{
|
||
UpdateStatus("错误: OTAManager 未初始化");
|
||
return;
|
||
}
|
||
|
||
UpdateStatus("正在取消OTA升级...");
|
||
Log("取消OTA升级 (0x85)");
|
||
|
||
OTAManager.Instance.CancelUpgrade((success) =>
|
||
{
|
||
Loom.QueueOnMainThread(() =>
|
||
{
|
||
if (success)
|
||
{
|
||
UpdateStatus("OTA升级已取消");
|
||
Log("OTA升级已取消");
|
||
}
|
||
else
|
||
{
|
||
UpdateStatus("取消OTA升级失败");
|
||
Log("取消OTA升级失败");
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// OTA版本信息回调
|
||
/// </summary>
|
||
private void OnOTAVersionInfoReceived(OTAVersionInfo info)
|
||
{
|
||
if (OTAInfoText != null)
|
||
{
|
||
OTAInfoText.text = $"=== 设备版本信息 ===\n固件版本: {info.FirmwareVersion}\n硬件版本: {info.HardwareVersion}\nOTA版本: {info.OTAVersion}";
|
||
}
|
||
}
|
||
|
||
// OTA传输进度跟踪
|
||
private int _lastProgressCurrent = 0;
|
||
private float _lastProgressTime = 0f;
|
||
private float _transferSpeed = 0f; // bytes per second
|
||
|
||
/// <summary>
|
||
/// OTA传输进度回调
|
||
/// </summary>
|
||
private void OnOTATransferProgress(int current, int total, int retryCount, int maxRetries)
|
||
{
|
||
float progress = (float)current / total * 100;
|
||
|
||
// 计算传输速度
|
||
float currentTime = Time.time;
|
||
if (_lastProgressTime > 0 && current > _lastProgressCurrent)
|
||
{
|
||
float timeDelta = currentTime - _lastProgressTime;
|
||
int bytesDelta = (current - _lastProgressCurrent) * 253; // 每包253字节数据
|
||
_transferSpeed = bytesDelta / timeDelta;
|
||
}
|
||
_lastProgressCurrent = current;
|
||
_lastProgressTime = currentTime;
|
||
|
||
// 计算剩余时间
|
||
float remainingTime = 0f;
|
||
if (_transferSpeed > 0)
|
||
{
|
||
int remainingBytes = (total - current) * 253;
|
||
remainingTime = remainingBytes / _transferSpeed;
|
||
}
|
||
|
||
// 更新UI
|
||
if (OTAInfoText != null)
|
||
{
|
||
string speedStr = _transferSpeed > 0 ? FormatFileSize((long)_transferSpeed) + "/s" : "计算中...";
|
||
string timeStr = remainingTime > 0 ? $"{remainingTime:F1}秒" : "计算中...";
|
||
string retryStr = retryCount > 0 ? $" (重试 {retryCount}/{maxRetries})" : "";
|
||
|
||
OTAInfoText.text = $"=== OTA升级中 ===\n" +
|
||
$"进度: {current}/{total} ({progress:F1}%){retryStr}\n" +
|
||
$"速度: {speedStr}\n" +
|
||
$"剩余时间: {timeStr}\n" +
|
||
$"已传输: {FormatFileSize(current * 253)} / {FormatFileSize(total * 253)}";
|
||
}
|
||
|
||
if (retryCount > 0)
|
||
{
|
||
Log($"OTA传输进度: {current}/{total} ({progress:F1}%) - 重试 {retryCount}/{maxRetries}");
|
||
}
|
||
else
|
||
{
|
||
Log($"OTA传输进度: {current}/{total} ({progress:F1}%), 速度: {FormatFileSize((long)_transferSpeed)}/s");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// OTA状态变化回调
|
||
/// </summary>
|
||
private void OnOTAStateChanged(OTAState state)
|
||
{
|
||
if (OTAInfoText != null && state != OTAState.Transferring) // 传输状态由进度回调更新
|
||
{
|
||
OTAInfoText.text = $"=== OTA状态 ===\n{state}";
|
||
}
|
||
Log($"OTA状态变化: {state}");
|
||
}
|
||
|
||
/// <summary>
|
||
/// OTA错误回调
|
||
/// </summary>
|
||
private void OnOTAError(string error)
|
||
{
|
||
UpdateStatus($"OTA错误: {error}");
|
||
Log($"OTA错误: {error}");
|
||
}
|
||
|
||
#endregion
|
||
|
||
}
|