using System;
using System.Text;
namespace TeamAAS.Communication.LightSources
{
///
/// TSD 光源协议命令构造器
/// 适用于 DPA12024V-4T-3.0 等型号
/// 特点: 所有命令带 XOR 校验字
///
public static class TSDLightProtocol
{
///
/// 读取指定通道亮度
/// #4{CH}00015 + XOR校验
///
public static string BuildReadCommand(int channelIndex)
{
string cmd = $"#4{channelIndex + 1}00015";
return cmd + CalcXor(cmd);
}
///
/// 设置指定通道亮度
/// #3{CH}0{HEX} + XOR校验
///
public static string BuildSetBrightnessCommand(int channelIndex, int brightness)
{
int br = Math.Max(0, Math.Min(255, brightness));
string cmd = $"#3{channelIndex + 1}0{br.ToString("X2")}";
return cmd + CalcXor(cmd);
}
///
/// 打开指定通道
/// #1{CH}064 + XOR校验
///
public static string BuildTurnOnChannelCommand(int channelIndex)
{
string cmd = $"#1{channelIndex + 1}064";
return cmd + CalcXor(cmd);
}
///
/// 关闭指定通道
/// #2{CH}029 + XOR校验
///
public static string BuildTurnOffChannelCommand(int channelIndex)
{
string cmd = $"#2{channelIndex + 1}029";
return cmd + CalcXor(cmd);
}
///
/// 全开所有通道(逐通道发送)
///
public static string[] BuildTurnOnAllCommands(int channelCount)
{
var cmds = new string[channelCount];
for (int i = 0; i < channelCount; i++)
cmds[i] = BuildTurnOnChannelCommand(i);
return cmds;
}
///
/// 全关所有通道(逐通道发送)
///
public static string[] BuildTurnOffAllCommands(int channelCount)
{
var cmds = new string[channelCount];
for (int i = 0; i < channelCount; i++)
cmds[i] = BuildTurnOffChannelCommand(i);
return cmds;
}
///
/// 解析读取响应,返回亮度值(16进制转10进制)
///
public static int ParseReadResponse(string response)
{
if (string.IsNullOrEmpty(response)) return 0;
if (response.Contains("$")) return 0;
try
{
string val = response.Substring(4, 2);
return Convert.ToInt32(val, 16);
}
catch { return 0; }
}
///
/// 验证响应是否成功
/// 成功: 响应包含 "#"
/// 失败: 响应包含 "$"
///
public static bool VerifyResponse(string response)
{
return !string.IsNullOrEmpty(response) && response.Contains("#");
}
///
/// XOR 校验字计算
///
public static string CalcXor(string asciiData)
{
if (string.IsNullOrEmpty(asciiData)) return "00";
byte[] data = Encoding.ASCII.GetBytes(asciiData);
byte xor = data[0];
for (int i = 1; i < data.Length; i++)
xor ^= data[i];
char high = NibbleToAscii((byte)((xor >> 4) & 0x0F));
char low = NibbleToAscii((byte)(xor & 0x0F));
return new string(new[] { high, low });
}
private static char NibbleToAscii(byte nibble)
{
return nibble < 10 ? (char)('0' + nibble) : (char)('A' + (nibble - 10));
}
}
}