DHDHSoftware/DH.Commons/Base/VisualLocalization.cs
2025-04-22 18:03:12 +08:00

80 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace DH.Commons.Base
{
public class VisualLocalization
{
// 配置属性
public string CameraName { get; set; }
public string ModelPath { get; set; }
public string ImgPath { get; set; }
public string Threshold { get; set; }
public string Direction { get; set; }
public string Speed { get; set; }
public string MSpeed { get; set; }
// 配置文件路径
private const string ConfigFile = "VisualConfigs.json";
private static readonly object _fileLock = new object();
/// <summary>
/// 保存当前配置(存在则更新,不存在则新增)
/// </summary>
public void Save()
{
lock (_fileLock)
{
var list = LoadAll();
var existing = list.FirstOrDefault(c => c.CameraName == CameraName);
if (existing != null)
{
// 更新现有配置
existing.ModelPath = ModelPath;
existing.ImgPath = ImgPath;
existing.Threshold = Threshold;
existing.Direction = Direction;
existing.Speed = Speed;
existing.MSpeed = MSpeed;
}
else
{
list.Add(this);
}
SaveAll(list);
}
}
/// <summary>
/// 获取全部配置列表
/// </summary>
public static List<VisualLocalization> LoadAll()
{
lock (_fileLock)
{
if (!File.Exists(ConfigFile)) return new List<VisualLocalization>();
var json = File.ReadAllText(ConfigFile);
return JsonSerializer.Deserialize<List<VisualLocalization>>(json)
?? new List<VisualLocalization>();
}
}
private static void SaveAll(List<VisualLocalization> list)
{
var options = new JsonSerializerOptions
{
WriteIndented = true,
IgnoreNullValues = true
};
File.WriteAllText(ConfigFile, JsonSerializer.Serialize(list, options));
}
}
}