Files
Evergreen-Health/Evergreen.Health.Application/Health/Devices/Contracts/DeviceValues.cs
T
2026-10-09 16:46:30 +08:00

53 lines
2.4 KiB
C#

using System.Globalization;
using System.Text.Json;
namespace Evergreen.Health.Application.Health.Devices.Contracts;
public static class DeviceValues
{
public static string Text(object? value)
=> value is JsonElement element
? (element.ValueKind == JsonValueKind.String ? element.GetString() ?? "" : element.ToString()).Trim()
: Convert.ToString(value, CultureInfo.InvariantCulture)?.Trim() ?? "";
public static int Integer(object? value, int minimum, int maximum, string label)
{
if (!int.TryParse(Text(value), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ||
number < minimum || number > maximum)
throw new InvalidOperationException($"{label}应在 {minimum} 到 {maximum} 之间");
return number;
}
public static bool Boolean(object? value)
{
if (bool.TryParse(Text(value), out var result)) return result;
throw new InvalidOperationException("开关参数无效");
}
public static string Choice(object? value, IReadOnlyList<string> options, string label)
{
var text = Text(value);
if (!options.Contains(text, StringComparer.Ordinal))
throw new InvalidOperationException($"{label}选项无效");
return text;
}
public static DeviceParameterDefinition Switch(string key, string entity, string domain, string label)
=> new(key, entity, value => new(label, entity, domain,
Boolean(value) ? "turn_on" : "turn_off"), label);
public static DeviceParameterDefinition Number(string key, string entity, int min, int max, string label)
=> new(key, entity, value => new(label, entity, "number", "set_value",
new Dictionary<string, object?> { ["value"] = Integer(value, min, max, label) }), label, min, max);
public static DeviceParameterDefinition Select(string key, string entity, IReadOnlyList<string> options, string label,
bool verify = false, DeviceCommandIntent intent = DeviceCommandIntent.Normal)
=> new(key, entity, value =>
{
var option = Choice(value, options, label);
return new(label, entity, "select", "select_option",
new Dictionary<string, object?> { ["option"] = option }, verify ? option : null)
{ Intent = option == "无" ? DeviceCommandIntent.Normal : intent };
}, label, Options: options);
}