using System;
using System.IO;
using UnityEngine;
using GeneralTools;
///
/// Android测试配置管理器
///
public class AndroidTestConfigManager : MonoBehaviour
{
[Header("测试配置")]
public bool enableSerialTest = true;
public bool enableSimulatedData = false;
public string testSerialPort = "/dev/ttyS4";
public int testBaudRate = 115200;
[Header("调试选项")]
public bool verboseLogging = true;
public bool exportConfigOnStart = true;
void Start()
{
if (exportConfigOnStart)
{
// ExportCurrentConfig();
}
SetupAndroidTestEnvironment();
}
///
/// 设置Android测试环境
///
private void SetupAndroidTestEnvironment()
{
Debug.Log("=== 设置Android测试环境 ===");
#if UNITY_ANDROID && !UNITY_EDITOR
// 1. 确保配置文件存在
EnsureAndroidConfigExists();
// 2. 更新测试配置
UpdateTestConfig();
// 3. 设置日志级别
SetupLogging();
// 4. 检查文件权限
CheckFilePermissions();
#else
Debug.Log("当前不在Android平台,跳过Android特定配置");
#endif
}
///
/// 确保Android配置文件存在
///
private void EnsureAndroidConfigExists()
{
string persistentConfigPath = Path.Combine(Application.persistentDataPath, "config_android.ini");
string streamingConfigPath = Path.Combine(Application.streamingAssetsPath, "config_android.ini");
Debug.Log($"持久化配置路径: {persistentConfigPath}");
Debug.Log($"StreamingAssets配置路径: {streamingConfigPath}");
if (!File.Exists(persistentConfigPath))
{
if (File.Exists(streamingConfigPath))
{
try
{
// 从StreamingAssets复制
string configContent = File.ReadAllText(streamingConfigPath);
File.WriteAllText(persistentConfigPath, configContent);
Debug.Log("已从StreamingAssets复制配置文件到持久化目录");
}
catch (Exception ex)
{
Debug.LogError($"复制配置文件失败: {ex.Message}");
CreateDefaultAndroidConfig(persistentConfigPath);
}
}
else
{
Debug.LogWarning("StreamingAssets中未找到Android配置文件,创建默认配置");
CreateDefaultAndroidConfig(persistentConfigPath);
}
}
else
{
Debug.Log("Android配置文件已存在");
}
}
///
/// 创建默认Android配置
///
private void CreateDefaultAndroidConfig(string configPath)
{
string defaultConfig = $@"[config]
screen_width=1920
screen_height=1080
window_Left=0
window_Top=0
showcursor=false
fullscreen=2
screenDepth=2
isAllowPlayBGM=true
audioShotLimit=5
logType=0
saveLog=true
broadcastDebug=false
debugSocketMsgMode=1
targetFramerate=60
keyDownActionLevel=0
releaseTime=30
[SerialCommunication]
serialPortName={testSerialPort}
baudRate={testBaudRate}
enabled={enableSerialTest.ToString().ToLower()}
connectionTimeoutMs=5000
heartbeatIntervalSeconds=30
[SerialPort]
serialPortName={testSerialPort}
serialBaudRate={testBaudRate}
serialDataBits=8
serialStopBits=1
serialParity=None
serialFlowControl=false
heartbeatInterval=1000
communicationTimeout=5000
autoReconnect=true
maxReconnectAttempts=5
frameHeader1=0xAA
frameHeader2=0x55
frameTail1=0x0D
frameTail2=0x0A
dataReportInterval=1000
alarmCheckInterval=500
[Display]
brightness=47.0
[Audio]
volume=26
muteDurationMinutes=4
[Network]
mode=Dhcp
ipv4=
mask=255.255.255.0
gateway=
[System]
autoBackup=True
dataRetentionDays=30
[AlarmSettings]
enableLowPriorityAlarm=true
enableMediumPriorityAlarm=true
enableHighPriorityAlarm=true
batteryLowThreshold=40
batteryCriticalThreshold=20
batteryEmptyThreshold=5
bfiAbnormalThreshold=100.0
laserTempAbnormalThreshold=60.0
enableAlarmSound=true
enableAlarmLight=true
[DataProcessing]
bfiSamplingRate=100
dataSmoothingWindow=10
enableDataValidation=true
filterAbnormalData=true
enableDataStorage=true
dataStorageInterval=60
";
try
{
File.WriteAllText(configPath, defaultConfig);
Debug.Log($"已创建默认Android配置文件: {configPath}");
}
catch (Exception ex)
{
Debug.LogError($"创建默认配置文件失败: {ex.Message}");
}
}
///
/// 更新测试配置
///
private void UpdateTestConfig()
{
try
{
string configPath = Path.Combine(Application.persistentDataPath, "config_android.ini");
// 初始化ConfigHelper
ConfigHelper.Init(configPath);
// 验证配置读取
var serialPortName = ConfigHelper.GetConfig("serialPortName", "SerialCommunication", "");
var baudRate = ConfigHelper.GetConfig("baudRate", "SerialCommunication", 0);
var enabled = ConfigHelper.GetConfig("enabled", "SerialCommunication", false);
Debug.Log($"当前配置 - 串口: {serialPortName}, 波特率: {baudRate}, 启用: {enabled}");
if (verboseLogging)
{
LogDetailedConfig();
}
}
catch (Exception ex)
{
Debug.LogError($"更新测试配置失败: {ex.Message}");
}
}
///
/// 设置日志记录
///
private void SetupLogging()
{
if (verboseLogging)
{
Debug.Log("启用详细日志记录");
Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.ScriptOnly);
Application.SetStackTraceLogType(LogType.Warning, StackTraceLogType.ScriptOnly);
Application.SetStackTraceLogType(LogType.Error, StackTraceLogType.Full);
}
}
///
/// 检查文件权限
///
private void CheckFilePermissions()
{
try
{
string testFilePath = Path.Combine(Application.persistentDataPath, "permission_test.txt");
File.WriteAllText(testFilePath, "权限测试");
File.Delete(testFilePath);
Debug.Log("文件读写权限正常");
}
catch (Exception ex)
{
Debug.LogError($"文件权限检查失败: {ex.Message}");
}
}
///
/// 记录详细配置信息
///
private void LogDetailedConfig()
{
Debug.Log("=== 详细配置信息 ===");
try
{
string configPath = Path.Combine(Application.persistentDataPath, "config_android.ini");
if (File.Exists(configPath))
{
string[] lines = File.ReadAllLines(configPath);
Debug.Log($"配置文件总行数: {lines.Length}");
foreach (string line in lines)
{
if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith(";") && !line.StartsWith("["))
{
Debug.Log($"配置项: {line}");
}
}
}
}
catch (Exception ex)
{
Debug.LogError($"记录详细配置失败: {ex.Message}");
}
}
///
/// 导出当前配置
///
public void ExportCurrentConfig()
{
try
{
string exportPath = Path.Combine(Application.persistentDataPath, $"exported_config_{DateTime.Now:yyyyMMdd_HHmmss}.txt");
string configPath = Path.Combine(Application.persistentDataPath, "config_android.ini");
string exportContent = $"=== 配置导出 ===\n";
exportContent += $"导出时间: {DateTime.Now}\n";
exportContent += $"设备型号: {SystemInfo.deviceModel}\n";
exportContent += $"操作系统: {SystemInfo.operatingSystem}\n\n";
if (File.Exists(configPath))
{
exportContent += "=== 当前配置文件内容 ===\n";
exportContent += File.ReadAllText(configPath);
}
else
{
exportContent += "配置文件不存在\n";
}
File.WriteAllText(exportPath, exportContent);
Debug.Log($"配置已导出到: {exportPath}");
}
catch (Exception ex)
{
Debug.LogError($"导出配置失败: {ex.Message}");
}
}
///
/// 重置为测试配置
///
[ContextMenu("重置为测试配置")]
public void ResetToTestConfig()
{
string configPath = Path.Combine(Application.persistentDataPath, "config_android.ini");
CreateDefaultAndroidConfig(configPath);
Debug.Log("已重置为测试配置");
}
///
/// 测试串口设备访问
///
[ContextMenu("测试串口设备")]
public void TestSerialDeviceAccess()
{
Debug.Log("=== 测试串口设备访问 ===");
#if UNITY_ANDROID && !UNITY_EDITOR
string[] testPorts = { testSerialPort, "/dev/ttyS0", "/dev/ttyUSB0", "/dev/ttyACM0" };
foreach (string port in testPorts)
{
try
{
bool exists = File.Exists(port);
Debug.Log($"串口 {port}: {(exists ? "存在" : "不存在")}");
if (exists)
{
// 尝试获取文件信息
var fileInfo = new FileInfo(port);
Debug.Log($" 文件大小: {fileInfo.Length}");
Debug.Log($" 最后修改: {fileInfo.LastWriteTime}");
}
}
catch (Exception ex)
{
Debug.LogError($"检查串口 {port} 失败: {ex.Message}");
}
}
#else
Debug.Log("非Android平台,无法测试串口设备");
#endif
}
}