WeLamp4G.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package com.welampiot.utils.lamp;
  2. import com.welampiot.utils.ToolUtils;
  3. import org.eclipse.paho.client.mqttv3.MqttClient;
  4. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  5. import org.eclipse.paho.client.mqttv3.MqttMessage;
  6. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Component;
  9. import java.util.Date;
  10. /**
  11. * 4G 控制器工具类
  12. */
  13. @Component
  14. public class WeLamp4G {
  15. public static String transIn = "/Lamp/TransIn/";
  16. public static String transOut = "/Lamp/TransOut/";
  17. /**
  18. * 灯控调光
  19. * @param address 灯控地址
  20. * @param light 亮度值 0-100
  21. * @param mode 通道值 0 A灯,1 B灯
  22. * @return
  23. */
  24. public static boolean dimming(String address,Integer light,Integer mode){
  25. String sendTopic = transIn+address;
  26. String backTopic = transOut+address;
  27. String cmd;
  28. if (mode == 0){ // A 路
  29. cmd = "0106DF0A";
  30. }else { // B 路
  31. cmd = "0106DF0C";
  32. }
  33. String lightStr = "0000"+Integer.toHexString(light).toString();
  34. lightStr = lightStr.substring(-4);
  35. cmd += lightStr;
  36. cmd += getCRC(cmd.getBytes());
  37. String s = ToolUtils.sendMqttCmdInfo(sendTopic, "0232"+cmd, backTopic);
  38. if (s.isEmpty()){
  39. return false;
  40. }else {
  41. return true;
  42. }
  43. }
  44. /**
  45. * 计算modbus CRC16校验码
  46. * @param bytes 需要计算的数据
  47. * @return
  48. */
  49. public static String getCRC(byte[] bytes) {
  50. // CRC寄存器全为1
  51. int CRC = 0x0000ffff;
  52. // 多项式校验值
  53. int POLYNOMIAL = 0x0000a001;
  54. int i, j;
  55. for (i = 0; i < bytes.length; i++) {
  56. CRC ^= ((int) bytes[i] & 0x000000ff);
  57. for (j = 0; j < 8; j++) {
  58. if ((CRC & 0x00000001) != 0) {
  59. CRC >>= 1;
  60. CRC ^= POLYNOMIAL;
  61. } else {
  62. CRC >>= 1;
  63. }
  64. }
  65. }
  66. // 结果转换为16进制
  67. String result = Integer.toHexString(CRC).toUpperCase();
  68. if (result.length() != 4) {
  69. StringBuffer sb = new StringBuffer("0000");
  70. result = sb.replace(4 - result.length(), 4, result).toString();
  71. }
  72. //高位在前地位在后
  73. //return result.substring(2, 4) + " " + result.substring(0, 2);
  74. // 交换高低位,低位在前高位在后
  75. return result.substring(2, 4)+result.substring(0, 2);
  76. }
  77. }