作者 钟来

生产数据库字段转化java字段bug

正在显示 16 个修改的文件 包含 95 行增加941 行删除
... ... @@ -11,10 +11,6 @@
<artifactId>lh-central-control</artifactId>
<description>
中控平台
</description>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
... ... @@ -22,132 +18,16 @@
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<!-- SpringBoot Web容器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring框架基本的核心工具 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- SpringWeb模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- servlet包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
</dependency>
<!-- 文档 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--https://mvnrepository.com/artifact/io.swagger/swagger-models-->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger-models.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui &ndash;&gt;-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>${swagger-ui.version}</version>
</dependency>
<!-- mqtt -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
</dependency>
<dependency>
<groupId>net.jodah</groupId>
<artifactId>expiringmap</artifactId>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- redis 缓存操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- 通用工具-->
<!-- 系统模块-->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>lh-domain</artifactId>
<artifactId>ruoyi-common</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
... ...
package com.zhonglai.luhui.central.control;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.Message;
import com.ruoyi.common.core.domain.MessageCode;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.html.HttpUtils;
import com.ruoyi.system.domain.IotDevice;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Service
public class DeviceControlService {
@Autowired
private RedisCache redisCache;
private String redisHostPath = "luhui:mqttservice:device:device:";
private IotDevice getRedisIotDevice(String imei)
{
return (IotDevice)redisCache.getCacheObject(redisHostPath+imei);
}
private String getServiceAdrres(String imei) {
IotDevice iotDevice = getRedisIotDevice(imei);
if(null == iotDevice || StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
return null;
}
return "http://"+iotDevice.getListen_service_ip()+"device/control/"+imei;
}
/**
* 固件版本更新
* @param imei 主机imei
* @param firmwareVersion 版本号
* @param code 版本码
* @return
*/
public Message firmwareUp(String imei,String firmwareVersion,Integer code)
{
String url = getServiceAdrres(imei);
if(null == url)
{
return null;
}
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("firmwareVersion",firmwareVersion);
valueMap.put("code",code);
return post(url, jsonObject -> jsonObject.put("0",valueMap));
}
/**
* 设备重启
* @param imei 主机imei
* @param restart 1重启,2复位,3恢复出厂值
* @return
*/
public Message restart(String imei ,Integer restart)
{
String url = getServiceAdrres(imei);
if(null == url)
{
return new Message(MessageCode.DEFAULT_FAIL_CODE,"设备不在线");
}
Map<String,Object> map = new HashMap<>();
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("restart",restart);
return post(url, jsonObject -> jsonObject.put("0",valueMap));
}
private Message post(String url, HttpUtils.JsonBody jsonBody)
{
Response response = null;
try {
response = HttpUtils.postJsonBody(url, jsonBody);
if(null != response.body() && StringUtils.isNotEmpty(response.body().string()))
{
Message message = com.alibaba.fastjson.JSONObject.parseObject(response.body().string(),Message.class);
return message;
}
} catch (IOException e) {
return new Message(MessageCode.DEFAULT_FAIL_CODE,"指令转发失败请联系管理员");
}
return new Message(MessageCode.DEFAULT_FAIL_CODE,"指令执行失败请稍后重试");
}
}
... ...
package com.zhonglai.luhui.central.control;
public class LhCentralControlApplication {
}
package com.zhonglai.luhui.central.control.comm;
public class Message {
private int code;
private String message;
private Object data;
public Message() {
}
public Message(MessageCodeType code, String message, Object data) {
this.code = code.getCode();
this.message = message;
if (null == message || "".equals(message)) {
this.message = code.getMessage();
}
this.data = data;
}
public Message(MessageCodeType code, Object data) {
this.code = code.getCode();
this.message = code.getMessage();
this.data = data;
}
public Message(MessageCodeType code, String message) {
this.code = code.getCode();
this.message = message;
this.data = null;
}
public Message(MessageCodeType code) {
this.code = code.getCode();
this.message = code.getMessage();
}
public void setCode(MessageCode messageCode )
{
code = messageCode.code;
}
public void setCode(MessageCodeType code) {
this.code = code.getCode();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
package com.zhonglai.luhui.central.control.comm;
public enum MessageCode implements MessageCodeType{
DEFAULT_FAIL_CODE(0, "请求失败"),
DEFAULT_SUCCESS_CODE(1, "请求成功"),
SESSION_TIME_OUT(2, "会话超时,请刷新令牌"),
USER_INVALID(4, "用户失效,请重新登录"),
SYS_ERROR(3, "已知系统错误"),
REQUEST_METHOD_ERROR(6, "请求方式错误"),
REQUEST_PATH_ERROR(7, "请求路径错误"),
UNKNOWN_SYS_ERROR(5, "未知系统错误");
public int code;
public String message;
public int getCode() {
return this.code;
}
public String getMessage() {
return this.message;
}
private MessageCode(int code, String message) {
this.code = code;
this.message = message;
}
}
package com.zhonglai.luhui.central.control.comm;
public interface MessageCodeType {
int getCode();
String getMessage();
}
package com.zhonglai.luhui.central.control.comm;
/**
* mqtt消息解析结果
*/
public enum MqttAnalysisMessageResult {
/**
* 成功
*/
Success,
/**
* 失败
*/
Fail,
/**
*topic异常
*/
TopicException,
/**
*设备不存在
*/
DeviceDoesNotExist,
/**
*payload解析异常
*/
PayloadParsingException
}
package com.zhonglai.luhui.central.control.comm;
public class MyException extends RuntimeException{
private static final long serialVersionUID = 8827598182853467258L;
private Message errmge;
public MyException(Message myMessage) {
super(myMessage.getMessage());
this.errmge = myMessage;
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(String message) {
super(message);
}
}
package com.zhonglai.luhui.central.control.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
public class SysParameter {
private static Logger log = LoggerFactory.getLogger(SysParameter.class);
public static String service_ip = ""; //服务所在地址
@Value("${mqtt.topicconfig:/{{roleid}}/{{username}}/{{clientid}}/{{topicType}}/{{messageid}}}")
public String tempTopicconfig ; //topic 配置
@Value("${mqtt.topics")
public String topics ; //topic
public static String topicconfig ; //topic 配置
@PostConstruct
public void init() {
inittopicconfig();
}
public void inittopicconfig()
{
topicconfig = tempTopicconfig;
}
}
package com.zhonglai.luhui.central.control.comm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.Optional;
public class Topic {
private static final Logger log = LoggerFactory.getLogger(Topic.class);
private String roleid;
private String username;
private String clientid;
private String topicType;
private String messageid;
private String payloadtype;
public Topic() {
}
public Topic(String roleid, String username, String clientid, String topicType, String payloadtype) {
this.roleid = roleid;
this.username = username;
this.clientid = clientid;
this.topicType = topicType;
this.payloadtype = payloadtype;
}
public Topic(String roleid, String username, String clientid, String topicType, String messageid, String payloadtype) {
this.roleid = roleid;
this.username = username;
this.clientid = clientid;
this.topicType = topicType;
this.messageid = messageid;
this.payloadtype = payloadtype;
}
public Topic(String topic)
{
topic = Optional.ofNullable(topic).orElseThrow(()->new MyException("topic为空"));
String[] sts = topic.split("/");
String[] config = SysParameter.topicconfig.split("/");
int number = sts.length;
if(number>config.length)
{
number = config.length;
}
for(int i=1;i<number;i++)
{
String cf = config[i].replace("{{","").replace("}}","");
try {
Field field = this.getClass().getDeclaredField(cf);
field.set(this,sts[i]);
} catch (NoSuchFieldException e) {
log.info("{}生成topic时没有属性{}",topic,cf);
} catch (IllegalAccessException e) {
log.info("{}生成topic时无法给{}赋值{}",topic,cf,sts[i]);
}
}
if("ONLINE".equals(topicType.toUpperCase()))
{
this.payloadtype = "String";
}
}
/**
* 生成缓存关键字
* @return
*/
public String generateRedicKey()
{
return generate(":");
}
/**
* 生成发送消息的topic
* @return
*/
public String generateSendMessageTopic()
{
return "/"+generate("/");
}
/**
* 生成客户端关键字
* @return
*/
public String generateClienKey()
{
return "/"+generate("/");
}
private String generate(String division)
{
String str = SysParameter.topicconfig;
if(StringUtils.isEmpty(roleid))
{
roleid = "2";
}
str = str.replace("/{{roleid}}",roleid+division);
if(StringUtils.isEmpty(username))
{
username = "+";
}
str = str.replace("/{{username}}",username+division);
if(StringUtils.isEmpty(clientid))
{
clientid = "+";
}
str = str.replace("/{{clientid}}",clientid+division);
if(StringUtils.isEmpty(payloadtype))
{
payloadtype = "String";
}
str = str.replace("/{{payloadtype}}",payloadtype+division);
if(StringUtils.isEmpty(topicType))
{
topicType = "PUT";
}
str = str.replace("/{{topicType}}",topicType+division);
if(StringUtils.isNotEmpty(messageid))
{
str = str.replace("/{{messageid}}",messageid);
}
return str;
}
public String getRoleid() {
return roleid;
}
public void setRoleid(String roleid) {
this.roleid = roleid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getClientid() {
return clientid;
}
public void setClientid(String clientid) {
this.clientid = clientid;
}
public String getTopicType() {
return topicType;
}
public void setTopicType(String topicType) {
this.topicType = topicType;
}
public String getMessageid() {
return messageid;
}
public void setMessageid(String messageid) {
this.messageid = messageid;
}
public String getPayloadtype() {
return payloadtype;
}
public void setPayloadtype(String payloadtype) {
this.payloadtype = payloadtype;
}
}
package com.zhonglai.luhui.central.control.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MqttConfig {
@Value("${mqtt.broker}")
private String broker;
@Value("${mqtt.clientId}")
private String clientId;
@Value("${mqtt.topics}")
private String topics;
@Value("${mqtt.username}")
private String username;
@Value("${mqtt.password}")
private String password;
public String getBroker() {
return broker;
}
public void setBroker(String broker) {
this.broker = broker;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getTopics() {
return topics;
}
public void setTopics(String topics) {
this.topics = topics;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.zhonglai.luhui.central.control.service;
import com.ruoyi.system.domain.IotDevice;
public interface DeviceService {
IotDevice getDeviceById(String clientId);
}
package com.zhonglai.luhui.central.control.service;
import com.zhonglai.luhui.central.control.config.MqttConfig;
import com.zhonglai.luhui.central.control.util.ByteUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class MqttClientService {
private Logger log = LoggerFactory.getLogger(MqttClientService.class);
@Autowired
private MqttConfig mqttConfig;
@Autowired
private MqttMessageArrivedService mqttMessageArrivedService;
@Autowired
private MqttOperation mqttOperation;
private MqttClient mqttclient;
private MqttConnectOptions options;
{
if(null == mqttclient)
{
try {
mqttclient = new MqttClient(mqttConfig.getBroker(), mqttConfig.getClientId(), new MemoryPersistence());
} catch (MqttException e) {
e.printStackTrace();
}
options = new MqttConnectOptions();
options.setCleanSession(true);
options.setConnectionTimeout(15);
//设置断开后重新连接
options.setAutomaticReconnect(true);
mqttclient.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean b, String s) {
log.info("连接成功");
try {
subscribe();
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void connectionLost(Throwable cause) {
log.error("连接丢失",cause);
}
@Override
public void messageArrived(String topic, MqttMessage message) {
log.info("接收到消息topc:{}, mqttMessage {},payload 十六进制 {}",topic,message, ByteUtil.hexStringToSpace(ByteUtil.toHexString(message.getPayload())));
mqttMessageArrivedService.analysisMessage(topic,message);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
try {
log.info("成功发出消息 messageid{}",token.getMessage());
} catch (MqttException e) {
e.printStackTrace();
}
}
});
}
}
@PostConstruct
public void init() throws MqttException {
log.info("-----------终端数据模型配置成功--------------------");
connect();
log.info("-----------mqtt连接服务器成功--------------------");
subscribe();
log.info("-----------订阅{}成功--------------------",mqttConfig.getTopics());
}
private void connect() throws MqttException {
options.setUserName(mqttConfig.getUsername());
options.setPassword(mqttConfig.getPassword().toCharArray());
mqttclient.connect(options);
}
private void subscribe() throws MqttException {
mqttOperation.subscribe(mqttclient,mqttConfig.getTopics().split(","));
}
}
package com.zhonglai.luhui.central.control.service;
import com.ruoyi.system.domain.IotDevice;
import com.zhonglai.luhui.central.control.comm.MqttAnalysisMessageResult;
import com.zhonglai.luhui.central.control.comm.Topic;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 数据解析业务
*/
@Service
public class MqttMessageArrivedService {
@Autowired
private DeviceService deviceService ;
private Logger log = LoggerFactory.getLogger(MqttMessageArrivedService.class);
public MqttAnalysisMessageResult analysisMessage(String topicStr, MqttMessage message)
{
Topic topic = new Topic(topicStr);
if(null == topic)
{
log.error("消息{},解析出来的topic为空,不做解析",topicStr);
return MqttAnalysisMessageResult.TopicException;
}
IotDevice iotDevice = deviceService.getDeviceById(topic.getClientid());
if(null == iotDevice)
{
log.info("设备{}不存在",topic.getClientid());
return MqttAnalysisMessageResult.DeviceDoesNotExist;
}
//消息分发
try {
// messageDistribution();
}catch (Exception e)
{
log.info("消息解析异常",e);
return MqttAnalysisMessageResult.PayloadParsingException;
}
return MqttAnalysisMessageResult.Success;
}
}
package com.zhonglai.luhui.central.control.service;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
@Service
public class MqttOperation {
public void subscribe(MqttClient mqttclient,String[] topicFilters) throws MqttException {
mqttclient.subscribe(topicFilters);
}
public void publish(MqttClient mqttclient,String topic, MqttMessage message) throws MqttException {
mqttclient.publish(topic,message);
}
public void publish(MqttClient mqttclient,String topic, String messageStr) throws MqttException {
MqttMessage message = new MqttMessage();
message.setPayload(messageStr.getBytes());
mqttclient.publish(topic,message);
}
public void closeClient (MqttClient mqttclient,String clientId,String code,String messageStr) throws MqttException {
String topic = "SYSOPERATION/CLOSE";
MqttMessage message = new MqttMessage();
Charset charset = Charset.forName("utf-8");
ByteBuffer payload = charset.encode(clientId+","+code+","+messageStr);
message.setPayload(payload.array());
mqttclient.publish(topic,message);
}
}
package com.zhonglai.luhui.central.control.util;
import java.util.Arrays;
public class ByteUtil {
/**
* byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用
*
* @param src
* byte数组
* @param offset
* 从数组的第offset位开始
* @return int数值
*/
public static long bytesToLongASC(byte[] src, int offset,int lenth) {
int value = 0;
for(int i=0;i<lenth;i++)
{
value = value | ((src[offset+i] & 0xFF)<<(8*i));
}
return value;
}
/**
* 把16进制字符串转换成字节数组
*
* @param hex
* @return
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
/**
* 把16进制字符串转换成字节数组
*
* @param hex
* @return
*/
public static String hexStringToSpace(String hex) {
if (null == hex) {
return null;
} else {
StringBuilder sb = new StringBuilder(hex.length() << 1);
for(int i = 0; i < hex.length(); i+=2) {
sb.append(hex.substring(i,i+2)).append(" ");
}
return sb.toString();
}
}
/**
* 把原数组加点目标数组后面
* @param dest 目标数组
* @param src 原数组
* @return
*/
public static byte[] addBytes(byte[] dest,byte[] src )
{
int dl = dest.length;
int sl = src.length;
dest = Arrays.copyOf(dest, dl+sl);//数组扩容
System.arraycopy(src,0,dest,dl,src.length);
return dest;
}
/**
* 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。 和bytesToInt2()配套使用
*/
public static byte[] intToBytesDESC(long value,int lenth)
{
byte[] src = new byte[lenth];
for(int i=0;i<lenth;i++)
{
src[i] = (byte) ((value>>(8*(lenth-i-1))) & 0xFF);
}
return src;
}
/**
* 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。 和bytesToInt()配套使用
* @param value
* 要转换的int值
* @return byte数组
*/
public static byte[] intToBytesASC( long value,int lenth)
{
byte[] src = new byte[lenth];
for(int i=lenth;i>0;i--)
{
src[i-1] = (byte) ((value>>(8*(i-1))) & 0xFF);
}
return src;
}
public static void main(String[] args) {
System.out.println(ByteUtil.toHexString( ByteUtil.intToBytesASC(2011239256,4)));
}
/**
* ip转化位4byte
* @param ip
* @return
*/
public static byte[] ipTo4Byte(String ip)
{
String[] ips = ip.split(".");
return new byte[]{(byte) Integer.parseInt(ips[0]),(byte) Integer.parseInt(ips[1]),(byte) Integer.parseInt(ips[2]),(byte) Integer.parseInt(ips[3])};
}
/**
* byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。和intToBytes2()配套使用
*/
public static long bytesToLongDESC(byte[] src, int offset,int lenth) {
long value = 0;
for(int i=lenth;i>0;i--)
{
value = value | ((src[offset+(lenth-i)] & 0xFF)<<(8*(i-1)));
}
return value;
}
private static final char[] hex = "0123456789abcdef".toCharArray();
public static String toHexString(byte[] bytes) {
if (null == bytes) {
return null;
} else {
StringBuilder sb = new StringBuilder(bytes.length << 1);
for(int i = 0; i < bytes.length; ++i) {
sb.append(hex[(bytes[i] & 240) >> 4]).append(hex[bytes[i] & 15]);
}
return sb.toString();
}
}
/**
* 计算CRC16/Modbus校验码 低位在前,高位在后
*
* @param str 十六进制字符串
* @return
*/
public static String getCRC16(String str) {
byte[] bytes = hexStringToByte(str);
return getCRC16(bytes);
}
/**
* 计算CRC16/Modbus校验码 低位在前,高位在后
*
* @return
*/
public static String getCRC16( byte[] bytes) {
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;
}
}
}
String crc = Integer.toHexString(CRC);
if (crc.length() == 2) {
crc = "00" + crc;
} else if (crc.length() == 3) {
crc = "0" + crc;
}
crc = crc.substring(2, 4) + crc.substring(0, 2);
return crc.toUpperCase();
}
}