76 lines
2.7 KiB
C#
76 lines
2.7 KiB
C#
using System;
|
||
using System.IO;
|
||
using UnityEngine;
|
||
|
||
[Serializable]
|
||
public class ControllerConfig
|
||
{
|
||
public bool Enable = true;
|
||
public string PortName = "COM3";
|
||
public int BaudRate = 115200;
|
||
public int DataBits = 8;
|
||
public int Parity = 0;
|
||
public int StopBits = 1;
|
||
public int ReadTimeoutMs = 5;
|
||
public int WriteTimeoutMs = 10;
|
||
|
||
public static ControllerConfig LoadOrCreate()
|
||
{
|
||
string filePath = Path.Combine(Application.streamingAssetsPath, "Configs", "Controller.json");
|
||
ControllerConfig device = null;
|
||
|
||
try
|
||
{
|
||
if (File.Exists(filePath))
|
||
{
|
||
// Читаем JSON файл
|
||
string jsonContent = File.ReadAllText(filePath);
|
||
device = JsonUtility.FromJson<ControllerConfig>(jsonContent);
|
||
|
||
if (device != null)
|
||
{
|
||
Debug.Log($"ControllerDevice загружен из {filePath}");
|
||
return device;
|
||
}
|
||
}
|
||
|
||
// Если файл не существует или десериализация не удалась, создаем новый экземпляр
|
||
device = new ControllerConfig();
|
||
|
||
// Сохраняем настройки в файл
|
||
SaveToFile(device, filePath);
|
||
|
||
Debug.Log($"Создан новый ControllerDevice с настройками по умолчанию и сохранен в {filePath}");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Debug.LogError($"Ошибка при загрузке или создании ControllerDevice: {ex.Message}");
|
||
|
||
// В случае ошибки возвращаем новый экземпляр с настройками по умолчанию
|
||
device = new ControllerConfig();
|
||
}
|
||
|
||
return device;
|
||
}
|
||
|
||
private static void SaveToFile(ControllerConfig device, string filePath)
|
||
{
|
||
try
|
||
{
|
||
// Создаем директорию, если она не существует
|
||
string directory = Path.GetDirectoryName(filePath);
|
||
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
|
||
{
|
||
Directory.CreateDirectory(directory);
|
||
}
|
||
|
||
// Сериализуем в JSON и сохраняем
|
||
string jsonContent = JsonUtility.ToJson(device, true); // true для форматирования
|
||
File.WriteAllText(filePath, jsonContent);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Debug.LogError($"Ошибка при сохранении ControllerDevice: {ex.Message}");
|
||
}
|
||
}
|
||
} |