69 lines
2.8 KiB
C#
69 lines
2.8 KiB
C#
using System.IO;
|
|
using System.Text.Json;
|
|
using SopHelper.Engine.Camera;
|
|
using SopHelper.Presentation;
|
|
|
|
namespace SopHelper.Models;
|
|
|
|
public sealed record CameraDeviceSettings
|
|
{
|
|
public UvcCaptureOptions UsbCapture { get; set; } = new();
|
|
|
|
public void Validate()
|
|
{
|
|
UsbCapture.Validate();
|
|
}
|
|
}
|
|
|
|
/// <summary>按设备保存相机设置,独立于所有配方。</summary>
|
|
public sealed class CameraSettingsStore(string root)
|
|
{
|
|
public string FilePath => Path.Combine(root, "workspace", "camera-device-settings.json");
|
|
public static CameraSettingsStore Current => new(DesktopPlatform.WorkspaceRoot);
|
|
private static string Key(CameraInfo camera) => $"Uvc:{camera.Index}";
|
|
private Dictionary<string, CameraDeviceSettings> Read()
|
|
{
|
|
// 旧路径也用于录像目录;只迁移设备项,避免把 directory 字符串读成设备设置。
|
|
var path = File.Exists(FilePath) ? FilePath : Path.Combine(root, "workspace", "camera-settings.json");
|
|
if (!File.Exists(path)) return new();
|
|
using var json = JsonDocument.Parse(File.ReadAllText(path));
|
|
if (json.RootElement.ValueKind != JsonValueKind.Object)
|
|
throw new InvalidDataException("相机设置文件必须为 JSON 对象");
|
|
var settings = new Dictionary<string, CameraDeviceSettings>();
|
|
foreach (var property in json.RootElement.EnumerateObject())
|
|
{
|
|
if (!property.Name.StartsWith("Uvc:", StringComparison.Ordinal)) continue;
|
|
settings[property.Name] = property.Value.Deserialize<CameraDeviceSettings>()
|
|
?? throw new InvalidDataException("相机设备设置内容为空:" + property.Name);
|
|
}
|
|
return settings;
|
|
}
|
|
public CameraDeviceSettings Load(CameraInfo camera) => Read().GetValueOrDefault(Key(camera)) ?? new();
|
|
public void Save(CameraInfo camera, CameraDeviceSettings settings)
|
|
{
|
|
settings.Validate();
|
|
var all = Read();
|
|
all[Key(camera)] = settings;
|
|
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
|
|
var temporary = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp";
|
|
try
|
|
{
|
|
File.WriteAllText(temporary, JsonSerializer.Serialize(all, new JsonSerializerOptions { WriteIndented = true }));
|
|
File.Move(temporary, FilePath, true);
|
|
}
|
|
finally { if (File.Exists(temporary)) File.Delete(temporary); }
|
|
}
|
|
public Task<bool> ConnectAsync(ICameraService service, CameraInfo camera)
|
|
{
|
|
var settings = Load(camera);
|
|
settings.Validate();
|
|
return service.ConnectAsync(camera);
|
|
}
|
|
public async Task<string> ApplyAsync(ICameraService service, CameraInfo camera)
|
|
{
|
|
var settings = Load(camera);
|
|
settings.Validate();
|
|
return await service.ConfigureUvcAsync(settings.UsbCapture);
|
|
}
|
|
}
|