DCS/ruiyiweiUX/Assets/Scripts/Services/SystemSettingsService.cs

529 lines
14 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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

using System;
using UnityEngine;
public class SystemSettingsService : ISystemSettingsService
{
private SystemSettings _settings;
private IDataPersistenceService _persistence;
public SystemSettingsService()
{
// 获取数据持久化服务
_persistence = ServiceLocator.Get<IDataPersistenceService>();
// 加载保存的设置,如果没有则使用默认值
LoadSettings();
ApplyPersistedSettingsOnStartup();
}
public float Brightness
{
get => _settings.brightness;
set
{
float oldValue = _settings.brightness;
_settings.brightness = Mathf.Clamp(value, 10f, 100f);
SaveSettings();
// 应用实际的亮度控制
ApplyBrightnessChange(_settings.brightness);
// 记录亮度调整日志
LogSettingChange("调整屏幕亮度", $"从 {oldValue:F0}% 调整到 {_settings.brightness:F0}%");
}
}
public int Volume
{
get => _settings.volume;
set
{
int oldValue = _settings.volume;
_settings.volume = Mathf.Clamp(value, 10, 100);
SaveSettings();
// 应用实际的音量控制
ApplyVolumeChange(_settings.volume);
// 记录音量调整日志
LogSettingChange("调整系统音量", $"从 {oldValue}% 调整到 {_settings.volume}%");
}
}
public int MuteDurationMinutes
{
get => _settings.muteDurationMinutes;
set
{
_settings.muteDurationMinutes = Mathf.Clamp(value, 1, 10);
SaveSettings();
}
}
public DateTime SystemTime
{
get
{
if (_settings != null && _settings.useCustomSystemTime)
{
try
{
return DateTime.Now.AddTicks(_settings.customTimeOffsetTicks);
}
catch
{
return DateTime.Now;
}
}
return DateTime.Now;
}
set
{
DateTime oldValue = SystemTime;
DateTime now = DateTime.Now;
TimeSpan offset = value - now;
// 选择当前时间(或接近当前时间)时,恢复跟随系统时钟,避免关机后时间漂移。
if (Mathf.Abs((float)offset.TotalSeconds) <= 2f)
{
_settings.useCustomSystemTime = false;
_settings.customTimeOffsetTicks = 0;
_settings.systemTime = DateTime.MinValue;
SaveSettings();
LogSettingChange("调整UI显示时间", $"恢复跟随系统时间(旧显示时间: {oldValue:yyyy-MM-dd HH:mm:ss}");
return;
}
_settings.useCustomSystemTime = true;
_settings.customTimeOffsetTicks = offset.Ticks;
_settings.systemTime = value;
SaveSettings();
// 注意:仅更新应用显示时间,不修改系统时间。
LogSettingChange("调整UI显示时间", $"从 {oldValue:yyyy-MM-dd HH:mm:ss} 调整到 {value:yyyy-MM-dd HH:mm:ss}仅UI显示");
}
}
public NetworkConfig Network
{
get => _settings.network;
set
{
_settings.network = value;
SaveSettings();
// 应用网络配置变化
ApplyNetworkConfigChange(value);
// 记录网络配置日志
LogSettingChange("修改网络配置", $"模式: {value.Mode}, IP: {value.IPv4}, 网关: {value.Gateway}");
}
}
public string VersionShort => _settings.version;
public string VersionFull => $"{_settings.version}+2025.09.17";
// 串口通信相关属性
public string SerialPortName
{
get => _settings.serialPortName ?? "COM1";
set
{
string oldValue = _settings.serialPortName;
_settings.serialPortName = value;
SaveSettings();
ApplySerialPortChange(value);
// 记录串口名称调整日志
LogSettingChange("修改串口名称", $"从 {oldValue} 修改为 {value}");
}
}
public int SerialBaudRate
{
get => _settings.serialBaudRate > 0 ? _settings.serialBaudRate : 115200;
set
{
int oldValue = _settings.serialBaudRate;
_settings.serialBaudRate = value;
SaveSettings();
ApplySerialBaudRateChange(value);
// 记录波特率调整日志
LogSettingChange("修改串口波特率", $"从 {oldValue} 修改为 {value}");
}
}
public bool EnableSerialCommunication
{
get => _settings.enableSerialCommunication;
set
{
_settings.enableSerialCommunication = value;
SaveSettings();
ApplySerialCommunicationToggle(value);
}
}
// BFI阈值设置实现
public float BFILowThreshold
{
get => _settings.bfiLowThreshold;
set
{
_settings.bfiLowThreshold = Mathf.Clamp(value, 0f, 200f);
SaveSettings();
ApplyBFIThresholdChange();
}
}
public float BFIHighThreshold
{
get => _settings.bfiHighThreshold;
set
{
_settings.bfiHighThreshold = Mathf.Clamp(value, 0f, 200f);
SaveSettings();
ApplyBFIThresholdChange();
}
}
public int BFIAlarmPriority
{
get => _settings.bfiAlarmPriority;
set
{
_settings.bfiAlarmPriority = Mathf.Clamp(value, 0, 2); // 0=低, 1=中, 2=高
SaveSettings();
// ApplyBFIThresholdChange();
}
}
public bool EnableBFIAlarm
{
get => _settings.enableBFIAlarm;
set
{
_settings.enableBFIAlarm = value;
SaveSettings();
// ApplyBFIThresholdChange();
}
}
public void SetBFIAlarmSettings(float lowThreshold, float highThreshold, int priority, bool enabled)
{
_settings.bfiLowThreshold = Mathf.Clamp(lowThreshold, 0f, 200f);
_settings.bfiHighThreshold = Mathf.Clamp(highThreshold, 0f, 200f);
if (_settings.bfiHighThreshold < _settings.bfiLowThreshold)
{
_settings.bfiHighThreshold = _settings.bfiLowThreshold;
}
_settings.bfiAlarmPriority = Mathf.Clamp(priority, 0, 2);
_settings.enableBFIAlarm = enabled;
SaveSettings();
ApplyBFIThresholdChange();
}
private void LoadSettings()
{
if (_persistence != null)
{
_settings = _persistence.LoadSettings();
}
else
{
// 如果持久化服务不可用,使用默认设置
_settings = new SystemSettings();
}
NormalizeLoadedSettings();
SaveSettings();
Debug.Log($"系统设置已加载 - 亮度:{_settings.brightness:F1}%, 音量:{_settings.volume}%, 静音:{_settings.muteDurationMinutes}分钟, BFI:{_settings.bfiLowThreshold:F1}-{_settings.bfiHighThreshold:F1}, 优先级:{_settings.bfiAlarmPriority}, 启用:{_settings.enableBFIAlarm}");
}
private void NormalizeLoadedSettings()
{
if (_settings == null)
{
_settings = new SystemSettings();
return;
}
_settings.brightness = Mathf.Clamp(_settings.brightness, 10f, 100f);
_settings.volume = Mathf.Clamp(_settings.volume, 10, 100);
_settings.muteDurationMinutes = Mathf.Clamp(_settings.muteDurationMinutes, 1, 10);
_settings.bfiLowThreshold = Mathf.Clamp(_settings.bfiLowThreshold, 0f, 200f);
_settings.bfiHighThreshold = Mathf.Clamp(_settings.bfiHighThreshold, 0f, 200f);
_settings.bfiAlarmPriority = Mathf.Clamp(_settings.bfiAlarmPriority, 0, 2);
// 旧版本没有useCustomSystemTime字段时默认false统一按系统时钟显示。
if (!_settings.useCustomSystemTime)
{
_settings.customTimeOffsetTicks = 0;
_settings.systemTime = DateTime.MinValue;
}
}
private void ApplyPersistedSettingsOnStartup()
{
if (_settings == null)
{
return;
}
ApplyBrightnessChange(_settings.brightness);
ApplyVolumeChange(_settings.volume);
ApplyBFIThresholdChange();
Debug.Log($"启动应用已恢复系统设置 - 亮度:{_settings.brightness:F1}%, 音量:{_settings.volume}%, BFI:{_settings.bfiLowThreshold:F1}-{_settings.bfiHighThreshold:F1}");
}
private bool SaveSettings()
{
if (_persistence == null)
{
return false;
}
return _persistence.SaveSettings(_settings);
}
private void ApplyBrightnessChange(float brightness)
{
try
{
int brightnessInt = Mathf.RoundToInt(brightness);
Screen.brightness = brightness / 100f;
bool success = WindowsSystemController.SetMonitorBrightness(brightnessInt);
if (success)
{
Debug.Log($"应用亮度变化成功: {brightness}%");
}
else
{
Debug.LogWarning($"应用亮度变化失败: {brightness}% - 可能需要管理员权限或不支持的硬件");
}
}
catch (System.Exception ex)
{
Debug.LogError($"应用亮度设置失败: {ex.Message}");
}
}
private void ApplyVolumeChange(int volume)
{
try
{
// 使用 WindowsSystemController 进行真实的音量控制
bool success = WindowsSystemController.SetSystemVolume(volume);
if (success)
{
Debug.Log($"应用音量变化成功: {volume}%");
}
else
{
Debug.LogWarning($"应用音量变化失败: {volume}% - 尝试使用现有SoundManager");
// 备用方案使用现有的SoundManager
#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
var soundManager = GeneralTools.SoundManager.Instance;
if (soundManager != null)
{
// 这是一个简化的音量调整,实际效果可能不够精确
Debug.Log($"使用SoundManager模拟音量变化: {volume}%");
}
#endif
}
}
catch (System.Exception ex)
{
Debug.LogError($"应用音量设置失败: {ex.Message}");
}
}
private void ApplySystemTimeChange(DateTime dateTime)
{
try
{
// 首先检查时间设置权限
if (!TimeSettingsPermissionManager.HasTimeSettingsPermission())
{
Debug.LogWarning($"缺少时间设置权限: {TimeSettingsPermissionManager.GetTimeSettingsLimitations()}");
// 尝试请求权限或引导用户
bool permissionResult = TimeSettingsPermissionManager.RequestTimeSettingsPermission();
if (!permissionResult)
{
Debug.Log("时间设置需要用户手动操作,请按照系统提示进行");
return;
}
}
// 使用 WindowsSystemController 进行真实的系统时间设置
bool success = WindowsSystemController.SetSystemTime(dateTime);
if (success)
{
Debug.Log($"应用系统时间变化成功: {dateTime:yyyy-MM-dd HH:mm:ss}");
// 验证时间是否设置成功
if (TimeSettingsPermissionManager.VerifyTimeSet(dateTime))
{
Debug.Log("系统时间设置已验证成功");
}
else
{
Debug.LogWarning("系统时间设置验证失败,可能存在时间差异");
}
}
else
{
Debug.LogWarning($"应用系统时间变化失败: {dateTime:yyyy-MM-dd HH:mm:ss}");
#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
Debug.LogWarning("Windows: 可能需要管理员权限来修改系统时间");
Debug.Log($"推荐操作流程: {TimeSettingsPermissionManager.GetRecommendedTimeSetupProcess()}");
#elif UNITY_ANDROID && !UNITY_EDITOR
Debug.LogWarning("Android: 普通应用无法直接修改系统时间,已引导用户到系统设置");
Debug.Log($"请按照以下流程操作: {TimeSettingsPermissionManager.GetRecommendedTimeSetupProcess()}");
#endif
}
}
catch (System.Exception ex)
{
Debug.LogError($"应用系统时间设置失败: {ex.Message}");
}
}
private void ApplyNetworkConfigChange(NetworkConfig config)
{
try
{
bool applied = NetworkConfigurator.Apply(config);
}
catch (System.Exception ex)
{
Debug.LogError($"应用网络配置失败: {ex.Message}");
}
}
private void ApplySerialPortChange(string portName)
{
try
{
var serialService = ServiceLocator.Get<ISerialCommunicationService>();
if (serialService != null && serialService.IsConnected)
{
// 重新连接串口
serialService.Disconnect();
serialService.Connect(portName, SerialBaudRate);
}
Debug.Log($"串口设置变更: {portName}");
}
catch (System.Exception ex)
{
Debug.LogError($"应用串口设置失败: {ex.Message}");
}
}
private void ApplySerialBaudRateChange(int baudRate)
{
try
{
var serialService = ServiceLocator.Get<ISerialCommunicationService>();
if (serialService != null && serialService.IsConnected)
{
// 重新连接串口
serialService.Disconnect();
serialService.Connect(SerialPortName, baudRate);
}
Debug.Log($"串口波特率变更: {baudRate}");
}
catch (System.Exception ex)
{
Debug.LogError($"应用串口波特率设置失败: {ex.Message}");
}
}
private void ApplySerialCommunicationToggle(bool enabled)
{
try
{
var serialService = ServiceLocator.Get<ISerialCommunicationService>();
if (serialService != null)
{
if (enabled && !serialService.IsConnected)
{
serialService.Connect(SerialPortName, SerialBaudRate);
}
else if (!enabled && serialService.IsConnected)
{
serialService.Disconnect();
}
}
Debug.Log($"串口通信 {(enabled ? "" : "")}");
}
catch (System.Exception ex)
{
Debug.LogError($"切换串口通信状态失败: {ex.Message}");
}
}
/// <summary>
/// 记录系统设置变更日志
/// </summary>
private void LogSettingChange(string settingName, string details)
{
try
{
var authService = ServiceLocator.Get<IAuthenticationService>();
var logService = ServiceLocator.Get<UserLogService>();
logService?.LogUserOperation(
authService?.CurrentUsername ?? "system",
settingName,
details,
true);
}
catch (Exception ex)
{
Debug.LogError($"记录设置变更日志失败: {ex.Message}");
}
}
private void ApplyBFIThresholdChange()
{
try
{
// 通知DCSAlarmManager更新BFI阈值配置
if (DCSAlarmManager.Instance != null)
{
DCSAlarmManager.Instance.UpdateBFIThresholds(
BFILowThreshold,
BFIHighThreshold,
BFIAlarmPriority,
EnableBFIAlarm
);
}
// 记录BFI阈值调整日志
var authService = ServiceLocator.Get<IAuthenticationService>();
var logService = ServiceLocator.Get<UserLogService>();
logService?.LogUserOperation(
authService?.CurrentUsername ?? "system",
"调整BFI阈值",
$"下限: {BFILowThreshold:F1}, 上限: {BFIHighThreshold:F1}, 优先级: {BFIAlarmPriority}, 启用: {EnableBFIAlarm}",
true);
Debug.Log($"DCSAlarmManager: BFI阈值已更新 - 下限:{BFILowThreshold}, 上限:{BFIHighThreshold}, 优先级:{BFIAlarmPriority}, 启用:{EnableBFIAlarm}");
}
catch (System.Exception ex)
{
Debug.LogError($"应用BFI阈值设置失败: {ex.Message}");
}
}
}