package com.welampiot.utils.lamp; import com.welampiot.utils.ToolUtils; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Date; /** * 4G 控制器工具类 */ @Component public class WeLamp4G { public static String transIn = "/Lamp/TransIn/"; public static String transOut = "/Lamp/TransOut/"; /** * 灯控调光 * @param address 灯控地址 * @param light 亮度值 0-100 * @param mode 通道值 0 A灯,1 B灯 * @return */ public static boolean dimming(String address,Integer light,Integer mode){ String sendTopic = transIn+address; String backTopic = transOut+address; String cmd; if (mode == 0){ // A 路 cmd = "0106DF0A"; }else { // B 路 cmd = "0106DF0C"; } String lightStr = "0000"+Integer.toHexString(light).toString(); lightStr = lightStr.substring(-4); cmd += lightStr; cmd += getCRC(cmd.getBytes()); String s = ToolUtils.sendMqttCmdInfo(sendTopic, "0232"+cmd, backTopic); if (s.isEmpty()){ return false; }else { return true; } } /** * 计算modbus CRC16校验码 * @param bytes 需要计算的数据 * @return */ public static String getCRC(byte[] bytes) { // CRC寄存器全为1 int CRC = 0x0000ffff; // 多项式校验值 int POLYNOMIAL = 0x0000a001; int i, j; for (i = 0; i < bytes.length; i++) { CRC ^= ((int) bytes[i] & 0x000000ff); for (j = 0; j < 8; j++) { if ((CRC & 0x00000001) != 0) { CRC >>= 1; CRC ^= POLYNOMIAL; } else { CRC >>= 1; } } } // 结果转换为16进制 String result = Integer.toHexString(CRC).toUpperCase(); if (result.length() != 4) { StringBuffer sb = new StringBuffer("0000"); result = sb.replace(4 - result.length(), 4, result).toString(); } //高位在前地位在后 //return result.substring(2, 4) + " " + result.substring(0, 2); // 交换高低位,低位在前高位在后 return result.substring(2, 4)+result.substring(0, 2); } }