张世豪
4 小时以前 d22349714c8d199c02f336f90fba841ef8f5cd39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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));
    }
}