package publicway; /** * 生成功能码 0x52 的 LED 控制报文(与 Led51 风格一致)。 * * 使用示例: * String cmd = Led52.build(1, 0x11); // 返回不带空格的大写十六进制字符串,已包含 CRC */ public class Led52 { /** * 构建控制字符串(不带空格,全部大写,包含 CRC) * * @param hostAddr 主机地址(1 字节,0-255) * @param dutyCycle 占空比(0-255) * @return 完整报文十六进制字符串,例如 "DDCC0008F001525AA55AA511C77" */ public static String build(int hostAddr, int dutyCycle) { int cmd = 0xF0; int func = 0x52; // payload prefix bytes 与 Led51 保持一致 int[] prefix = new int[] {0x5A, 0xA5, 0x5A, 0xA5}; int duty = dutyCycle & 0xFF; int host = hostAddr & 0xFF; int payloadLen = prefix.length + 1; // prefix + duty int len = 1 /*cmd*/ + 1 /*host*/ + 1 /*func*/ + payloadLen; StringBuilder sb = new StringBuilder(); sb.append(String.format("%02X", 0xDD)); sb.append(String.format("%02X", 0xCC)); sb.append(String.format("%02X%02X", (len >> 8) & 0xFF, len & 0xFF)); sb.append(String.format("%02X", cmd)); sb.append(String.format("%02X", host)); sb.append(String.format("%02X", func)); for (int b : prefix) { sb.append(String.format("%02X", b)); } sb.append(String.format("%02X", duty)); String withoutCrc = sb.toString(); String crc = CRC16Modbus.calculate(withoutCrc).toUpperCase(); return withoutCrc + crc; } /** * 与 build 相同,但返回带空格分隔的可读字符串(大写)。 */ public static String buildWithSpaces(int hostAddr, int dutyCycle) { String raw = build(hostAddr, dutyCycle); StringBuilder sb = new StringBuilder(); for (int i = 0; i < raw.length(); i += 2) { if (i > 0) sb.append(' '); sb.append(raw.substring(i, i + 2)); } return sb.toString(); } public static void main(String args[]) { System.out.println(build(1,1)); } }