作者 钟来

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

正在显示 16 个修改的文件 包含 96 行增加942 行删除
@@ -11,143 +11,23 @@ @@ -11,143 +11,23 @@
11 11
12 <artifactId>lh-central-control</artifactId> 12 <artifactId>lh-central-control</artifactId>
13 13
14 - <description>  
15 - 中控平台  
16 - </description>  
17 -  
18 <dependencies> 14 <dependencies>
19 - <!-- spring-boot-devtools --> 15 + <!-- spring-boot-devtools -->
20 <dependency> 16 <dependency>
21 <groupId>org.springframework.boot</groupId> 17 <groupId>org.springframework.boot</groupId>
22 <artifactId>spring-boot-devtools</artifactId> 18 <artifactId>spring-boot-devtools</artifactId>
23 <optional>true</optional> <!-- 表示依赖不会传递 --> 19 <optional>true</optional> <!-- 表示依赖不会传递 -->
24 </dependency> 20 </dependency>
25 - <!-- SpringBoot Web容器 -->  
26 - <dependency>  
27 - <groupId>org.springframework.boot</groupId>  
28 - <artifactId>spring-boot-starter-web</artifactId>  
29 - </dependency>  
30 <!-- Spring框架基本的核心工具 --> 21 <!-- Spring框架基本的核心工具 -->
31 <dependency> 22 <dependency>
32 <groupId>org.springframework</groupId> 23 <groupId>org.springframework</groupId>
33 <artifactId>spring-context-support</artifactId> 24 <artifactId>spring-context-support</artifactId>
34 </dependency> 25 </dependency>
35 - <!-- SpringWeb模块 -->  
36 - <dependency>  
37 - <groupId>org.springframework</groupId>  
38 - <artifactId>spring-web</artifactId>  
39 - </dependency>  
40 - <!-- servlet包 -->  
41 - <dependency>  
42 - <groupId>javax.servlet</groupId>  
43 - <artifactId>javax.servlet-api</artifactId>  
44 - </dependency>  
45 - <dependency>  
46 - <groupId>org.apache.commons</groupId>  
47 - <artifactId>commons-text</artifactId>  
48 - </dependency>  
49 -  
50 - <!-- 文档 -->  
51 - <dependency>  
52 - <groupId>io.springfox</groupId>  
53 - <artifactId>springfox-swagger2</artifactId>  
54 - <version>${swagger.version}</version>  
55 - <exclusions>  
56 - <exclusion>  
57 - <groupId>io.swagger</groupId>  
58 - <artifactId>swagger-models</artifactId>  
59 - </exclusion>  
60 - <exclusion>  
61 - <groupId>com.google.guava</groupId>  
62 - <artifactId>guava</artifactId>  
63 - </exclusion>  
64 - </exclusions>  
65 - </dependency>  
66 - <!--https://mvnrepository.com/artifact/io.swagger/swagger-models-->  
67 - <dependency>  
68 - <groupId>io.swagger</groupId>  
69 - <artifactId>swagger-models</artifactId>  
70 - <version>${swagger-models.version}</version>  
71 - </dependency>  
72 - <dependency>  
73 - <groupId>io.springfox</groupId>  
74 - <artifactId>springfox-swagger-ui</artifactId>  
75 - <version>${swagger.version}</version>  
76 - </dependency>  
77 - <!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui &ndash;&gt;-->  
78 - <dependency>  
79 - <groupId>com.github.xiaoymin</groupId>  
80 - <artifactId>swagger-bootstrap-ui</artifactId>  
81 - <version>${swagger-ui.version}</version>  
82 - </dependency>  
83 -  
84 - <!-- mqtt -->  
85 - <dependency>  
86 - <groupId>org.eclipse.paho</groupId>  
87 - <artifactId>org.eclipse.paho.client.mqttv3</artifactId>  
88 - </dependency>  
89 -  
90 - <dependency>  
91 - <groupId>net.jodah</groupId>  
92 - <artifactId>expiringmap</artifactId>  
93 - </dependency>  
94 -  
95 -  
96 - <!-- 数据库 -->  
97 - <dependency>  
98 - <groupId>commons-dbcp</groupId>  
99 - <artifactId>commons-dbcp</artifactId>  
100 - <version>1.4</version>  
101 - </dependency>  
102 - <dependency>  
103 - <groupId>commons-dbutils</groupId>  
104 - <artifactId>commons-dbutils</artifactId>  
105 - <version>1.6</version>  
106 - </dependency>  
107 - <dependency>  
108 - <groupId>commons-pool</groupId>  
109 - <artifactId>commons-pool</artifactId>  
110 - <version>1.6</version>  
111 - </dependency>  
112 - <dependency>  
113 - <groupId>mysql</groupId>  
114 - <artifactId>mysql-connector-java</artifactId>  
115 - <version>8.0.17</version>  
116 - </dependency>  
117 -  
118 - <!-- 阿里JSON解析器 -->  
119 - <dependency>  
120 - <groupId>com.alibaba</groupId>  
121 - <artifactId>fastjson</artifactId>  
122 - </dependency>  
123 -  
124 - <!--常用工具类 -->  
125 - <dependency>  
126 - <groupId>org.apache.commons</groupId>  
127 - <artifactId>commons-lang3</artifactId>  
128 - </dependency>  
129 -  
130 - <!-- redis 缓存操作 -->  
131 - <dependency>  
132 - <groupId>org.springframework.boot</groupId>  
133 - <artifactId>spring-boot-starter-data-redis</artifactId>  
134 - <exclusions>  
135 - <exclusion>  
136 - <groupId>io.lettuce</groupId>  
137 - <artifactId>lettuce-core</artifactId>  
138 - </exclusion>  
139 - </exclusions>  
140 - </dependency>  
141 - <dependency>  
142 - <groupId>redis.clients</groupId>  
143 - <artifactId>jedis</artifactId>  
144 - </dependency>  
145 -  
146 - <!-- 通用工具--> 26 + <!-- 系统模块-->
147 <dependency> 27 <dependency>
148 <groupId>com.zhonglai.luhui</groupId> 28 <groupId>com.zhonglai.luhui</groupId>
149 - <artifactId>lh-domain</artifactId> 29 + <artifactId>ruoyi-common</artifactId>
150 </dependency> 30 </dependency>
151 -  
152 </dependencies> 31 </dependencies>
  32 +
153 </project> 33 </project>
  1 +package com.zhonglai.luhui.central.control;
  2 +
  3 +import com.alibaba.fastjson.JSONObject;
  4 +import com.ruoyi.common.core.domain.Message;
  5 +import com.ruoyi.common.core.domain.MessageCode;
  6 +import com.ruoyi.common.core.redis.RedisCache;
  7 +import com.ruoyi.common.utils.StringUtils;
  8 +import com.ruoyi.common.utils.html.HttpUtils;
  9 +import com.ruoyi.system.domain.IotDevice;
  10 +import okhttp3.Response;
  11 +import org.springframework.beans.factory.annotation.Autowired;
  12 +import org.springframework.stereotype.Service;
  13 +
  14 +import java.io.IOException;
  15 +import java.util.HashMap;
  16 +import java.util.Map;
  17 +
  18 +@Service
  19 +public class DeviceControlService {
  20 + @Autowired
  21 + private RedisCache redisCache;
  22 + private String redisHostPath = "luhui:mqttservice:device:device:";
  23 + private IotDevice getRedisIotDevice(String imei)
  24 + {
  25 + return (IotDevice)redisCache.getCacheObject(redisHostPath+imei);
  26 + }
  27 +
  28 + private String getServiceAdrres(String imei) {
  29 + IotDevice iotDevice = getRedisIotDevice(imei);
  30 + if(null == iotDevice || StringUtils.isEmpty(iotDevice.getListen_service_ip()))
  31 + {
  32 + return null;
  33 + }
  34 + return "http://"+iotDevice.getListen_service_ip()+"device/control/"+imei;
  35 + }
  36 +
  37 + /**
  38 + * 固件版本更新
  39 + * @param imei 主机imei
  40 + * @param firmwareVersion 版本号
  41 + * @param code 版本码
  42 + * @return
  43 + */
  44 + public Message firmwareUp(String imei,String firmwareVersion,Integer code)
  45 + {
  46 + String url = getServiceAdrres(imei);
  47 + if(null == url)
  48 + {
  49 + return null;
  50 + }
  51 + Map<String,Object> valueMap = new HashMap<>();
  52 + valueMap.put("firmwareVersion",firmwareVersion);
  53 + valueMap.put("code",code);
  54 + return post(url, jsonObject -> jsonObject.put("0",valueMap));
  55 + }
  56 +
  57 + /**
  58 + * 设备重启
  59 + * @param imei 主机imei
  60 + * @param restart 1重启,2复位,3恢复出厂值
  61 + * @return
  62 + */
  63 + public Message restart(String imei ,Integer restart)
  64 + {
  65 + String url = getServiceAdrres(imei);
  66 + if(null == url)
  67 + {
  68 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"设备不在线");
  69 + }
  70 + Map<String,Object> map = new HashMap<>();
  71 + Map<String,Object> valueMap = new HashMap<>();
  72 + valueMap.put("restart",restart);
  73 + return post(url, jsonObject -> jsonObject.put("0",valueMap));
  74 + }
  75 +
  76 +
  77 + private Message post(String url, HttpUtils.JsonBody jsonBody)
  78 + {
  79 + Response response = null;
  80 + try {
  81 + response = HttpUtils.postJsonBody(url, jsonBody);
  82 + if(null != response.body() && StringUtils.isNotEmpty(response.body().string()))
  83 + {
  84 + Message message = com.alibaba.fastjson.JSONObject.parseObject(response.body().string(),Message.class);
  85 + return message;
  86 + }
  87 + } catch (IOException e) {
  88 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"指令转发失败请联系管理员");
  89 + }
  90 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"指令执行失败请稍后重试");
  91 + }
  92 +}
1 -package com.zhonglai.luhui.central.control;  
2 -  
3 -public class LhCentralControlApplication {  
4 -}  
1 -package com.zhonglai.luhui.central.control.comm;  
2 -  
3 -  
4 -public class Message {  
5 - private int code;  
6 - private String message;  
7 - private Object data;  
8 -  
9 - public Message() {  
10 - }  
11 -  
12 - public Message(MessageCodeType code, String message, Object data) {  
13 - this.code = code.getCode();  
14 - this.message = message;  
15 - if (null == message || "".equals(message)) {  
16 - this.message = code.getMessage();  
17 - }  
18 -  
19 - this.data = data;  
20 - }  
21 -  
22 - public Message(MessageCodeType code, Object data) {  
23 - this.code = code.getCode();  
24 - this.message = code.getMessage();  
25 - this.data = data;  
26 - }  
27 -  
28 - public Message(MessageCodeType code, String message) {  
29 - this.code = code.getCode();  
30 - this.message = message;  
31 - this.data = null;  
32 - }  
33 -  
34 - public Message(MessageCodeType code) {  
35 - this.code = code.getCode();  
36 - this.message = code.getMessage();  
37 - }  
38 -  
39 - public void setCode(MessageCode messageCode )  
40 - {  
41 - code = messageCode.code;  
42 - }  
43 -  
44 - public void setCode(MessageCodeType code) {  
45 - this.code = code.getCode();  
46 - }  
47 -  
48 - public int getCode() {  
49 - return code;  
50 - }  
51 -  
52 - public void setCode(int code) {  
53 - this.code = code;  
54 - }  
55 -  
56 - public String getMessage() {  
57 - return message;  
58 - }  
59 -  
60 - public void setMessage(String message) {  
61 - this.message = message;  
62 - }  
63 -  
64 - public Object getData() {  
65 - return data;  
66 - }  
67 -  
68 - public void setData(Object data) {  
69 - this.data = data;  
70 - }  
71 -}  
1 -package com.zhonglai.luhui.central.control.comm;  
2 -  
3 -public enum MessageCode implements MessageCodeType{  
4 - DEFAULT_FAIL_CODE(0, "请求失败"),  
5 - DEFAULT_SUCCESS_CODE(1, "请求成功"),  
6 - SESSION_TIME_OUT(2, "会话超时,请刷新令牌"),  
7 - USER_INVALID(4, "用户失效,请重新登录"),  
8 - SYS_ERROR(3, "已知系统错误"),  
9 - REQUEST_METHOD_ERROR(6, "请求方式错误"),  
10 - REQUEST_PATH_ERROR(7, "请求路径错误"),  
11 - UNKNOWN_SYS_ERROR(5, "未知系统错误");  
12 -  
13 - public int code;  
14 - public String message;  
15 -  
16 - public int getCode() {  
17 - return this.code;  
18 - }  
19 -  
20 - public String getMessage() {  
21 - return this.message;  
22 - }  
23 -  
24 - private MessageCode(int code, String message) {  
25 - this.code = code;  
26 - this.message = message;  
27 - }  
28 -}  
1 -package com.zhonglai.luhui.central.control.comm;  
2 -  
3 -public interface MessageCodeType {  
4 - int getCode();  
5 -  
6 - String getMessage();  
7 -}  
1 -package com.zhonglai.luhui.central.control.comm;  
2 -  
3 -/**  
4 - * mqtt消息解析结果  
5 - */  
6 -public enum MqttAnalysisMessageResult {  
7 - /**  
8 - * 成功  
9 - */  
10 - Success,  
11 -  
12 - /**  
13 - * 失败  
14 - */  
15 - Fail,  
16 - /**  
17 - *topic异常  
18 - */  
19 - TopicException,  
20 -  
21 - /**  
22 - *设备不存在  
23 - */  
24 - DeviceDoesNotExist,  
25 -  
26 - /**  
27 - *payload解析异常  
28 - */  
29 - PayloadParsingException  
30 -}  
1 -package com.zhonglai.luhui.central.control.comm;  
2 -  
3 -  
4 -public class MyException extends RuntimeException{  
5 - private static final long serialVersionUID = 8827598182853467258L;  
6 - private Message errmge;  
7 -  
8 - public MyException(Message myMessage) {  
9 - super(myMessage.getMessage());  
10 - this.errmge = myMessage;  
11 - }  
12 -  
13 - public MyException(String message, Throwable cause) {  
14 - super(message, cause);  
15 - }  
16 - public MyException(String message) {  
17 - super(message);  
18 - }  
19 -  
20 -}  
1 -package com.zhonglai.luhui.central.control.comm;  
2 -  
3 -import org.slf4j.Logger;  
4 -import org.slf4j.LoggerFactory;  
5 -import org.springframework.beans.factory.annotation.Value;  
6 -import org.springframework.context.annotation.Configuration;  
7 -  
8 -import javax.annotation.PostConstruct;  
9 -  
10 -@Configuration  
11 -public class SysParameter {  
12 - private static Logger log = LoggerFactory.getLogger(SysParameter.class);  
13 -  
14 - public static String service_ip = ""; //服务所在地址  
15 -  
16 - @Value("${mqtt.topicconfig:/{{roleid}}/{{username}}/{{clientid}}/{{topicType}}/{{messageid}}}")  
17 - public String tempTopicconfig ; //topic 配置  
18 -  
19 - @Value("${mqtt.topics")  
20 - public String topics ; //topic  
21 -  
22 - public static String topicconfig ; //topic 配置  
23 -  
24 -  
25 - @PostConstruct  
26 - public void init() {  
27 - inittopicconfig();  
28 - }  
29 -  
30 - public void inittopicconfig()  
31 - {  
32 - topicconfig = tempTopicconfig;  
33 - }  
34 -  
35 -}  
1 -package com.zhonglai.luhui.central.control.comm;  
2 -  
3 -import org.apache.commons.lang3.StringUtils;  
4 -import org.slf4j.Logger;  
5 -import org.slf4j.LoggerFactory;  
6 -  
7 -import java.lang.reflect.Field;  
8 -import java.util.Optional;  
9 -  
10 -public class Topic {  
11 - private static final Logger log = LoggerFactory.getLogger(Topic.class);  
12 -  
13 - private String roleid;  
14 - private String username;  
15 - private String clientid;  
16 - private String topicType;  
17 - private String messageid;  
18 - private String payloadtype;  
19 -  
20 - public Topic() {  
21 - }  
22 -  
23 - public Topic(String roleid, String username, String clientid, String topicType, String payloadtype) {  
24 - this.roleid = roleid;  
25 - this.username = username;  
26 - this.clientid = clientid;  
27 - this.topicType = topicType;  
28 - this.payloadtype = payloadtype;  
29 - }  
30 -  
31 - public Topic(String roleid, String username, String clientid, String topicType, String messageid, String payloadtype) {  
32 - this.roleid = roleid;  
33 - this.username = username;  
34 - this.clientid = clientid;  
35 - this.topicType = topicType;  
36 - this.messageid = messageid;  
37 - this.payloadtype = payloadtype;  
38 - }  
39 -  
40 - public Topic(String topic)  
41 - {  
42 - topic = Optional.ofNullable(topic).orElseThrow(()->new MyException("topic为空"));  
43 - String[] sts = topic.split("/");  
44 - String[] config = SysParameter.topicconfig.split("/");  
45 - int number = sts.length;  
46 - if(number>config.length)  
47 - {  
48 - number = config.length;  
49 - }  
50 - for(int i=1;i<number;i++)  
51 - {  
52 - String cf = config[i].replace("{{","").replace("}}","");  
53 - try {  
54 - Field field = this.getClass().getDeclaredField(cf);  
55 - field.set(this,sts[i]);  
56 - } catch (NoSuchFieldException e) {  
57 - log.info("{}生成topic时没有属性{}",topic,cf);  
58 - } catch (IllegalAccessException e) {  
59 - log.info("{}生成topic时无法给{}赋值{}",topic,cf,sts[i]);  
60 - }  
61 - }  
62 -  
63 - if("ONLINE".equals(topicType.toUpperCase()))  
64 - {  
65 - this.payloadtype = "String";  
66 - }  
67 - }  
68 -  
69 - /**  
70 - * 生成缓存关键字  
71 - * @return  
72 - */  
73 - public String generateRedicKey()  
74 - {  
75 - return generate(":");  
76 - }  
77 -  
78 - /**  
79 - * 生成发送消息的topic  
80 - * @return  
81 - */  
82 - public String generateSendMessageTopic()  
83 - {  
84 - return "/"+generate("/");  
85 - }  
86 -  
87 - /**  
88 - * 生成客户端关键字  
89 - * @return  
90 - */  
91 - public String generateClienKey()  
92 - {  
93 - return "/"+generate("/");  
94 - }  
95 -  
96 - private String generate(String division)  
97 - {  
98 - String str = SysParameter.topicconfig;  
99 - if(StringUtils.isEmpty(roleid))  
100 - {  
101 - roleid = "2";  
102 - }  
103 - str = str.replace("/{{roleid}}",roleid+division);  
104 -  
105 - if(StringUtils.isEmpty(username))  
106 - {  
107 - username = "+";  
108 - }  
109 - str = str.replace("/{{username}}",username+division);  
110 -  
111 - if(StringUtils.isEmpty(clientid))  
112 - {  
113 - clientid = "+";  
114 - }  
115 - str = str.replace("/{{clientid}}",clientid+division);  
116 -  
117 - if(StringUtils.isEmpty(payloadtype))  
118 - {  
119 - payloadtype = "String";  
120 - }  
121 - str = str.replace("/{{payloadtype}}",payloadtype+division);  
122 -  
123 - if(StringUtils.isEmpty(topicType))  
124 - {  
125 - topicType = "PUT";  
126 - }  
127 - str = str.replace("/{{topicType}}",topicType+division);  
128 -  
129 - if(StringUtils.isNotEmpty(messageid))  
130 - {  
131 - str = str.replace("/{{messageid}}",messageid);  
132 - }  
133 -  
134 - return str;  
135 - }  
136 -  
137 - public String getRoleid() {  
138 - return roleid;  
139 - }  
140 -  
141 - public void setRoleid(String roleid) {  
142 - this.roleid = roleid;  
143 - }  
144 -  
145 - public String getUsername() {  
146 - return username;  
147 - }  
148 -  
149 - public void setUsername(String username) {  
150 - this.username = username;  
151 - }  
152 -  
153 - public String getClientid() {  
154 - return clientid;  
155 - }  
156 -  
157 - public void setClientid(String clientid) {  
158 - this.clientid = clientid;  
159 - }  
160 -  
161 - public String getTopicType() {  
162 - return topicType;  
163 - }  
164 -  
165 - public void setTopicType(String topicType) {  
166 - this.topicType = topicType;  
167 - }  
168 -  
169 - public String getMessageid() {  
170 - return messageid;  
171 - }  
172 -  
173 - public void setMessageid(String messageid) {  
174 - this.messageid = messageid;  
175 - }  
176 -  
177 - public String getPayloadtype() {  
178 - return payloadtype;  
179 - }  
180 -  
181 - public void setPayloadtype(String payloadtype) {  
182 - this.payloadtype = payloadtype;  
183 - }  
184 -}  
1 -package com.zhonglai.luhui.central.control.config;  
2 -  
3 -import org.springframework.beans.factory.annotation.Value;  
4 -import org.springframework.stereotype.Component;  
5 -  
6 -@Component  
7 -public class MqttConfig {  
8 - @Value("${mqtt.broker}")  
9 - private String broker;  
10 - @Value("${mqtt.clientId}")  
11 - private String clientId;  
12 - @Value("${mqtt.topics}")  
13 - private String topics;  
14 - @Value("${mqtt.username}")  
15 - private String username;  
16 - @Value("${mqtt.password}")  
17 - private String password;  
18 -  
19 - public String getBroker() {  
20 - return broker;  
21 - }  
22 -  
23 - public void setBroker(String broker) {  
24 - this.broker = broker;  
25 - }  
26 -  
27 - public String getClientId() {  
28 - return clientId;  
29 - }  
30 -  
31 - public void setClientId(String clientId) {  
32 - this.clientId = clientId;  
33 - }  
34 -  
35 - public String getTopics() {  
36 - return topics;  
37 - }  
38 -  
39 - public void setTopics(String topics) {  
40 - this.topics = topics;  
41 - }  
42 -  
43 - public String getUsername() {  
44 - return username;  
45 - }  
46 -  
47 - public void setUsername(String username) {  
48 - this.username = username;  
49 - }  
50 -  
51 - public String getPassword() {  
52 - return password;  
53 - }  
54 -  
55 - public void setPassword(String password) {  
56 - this.password = password;  
57 - }  
58 -}  
1 -package com.zhonglai.luhui.central.control.service;  
2 -  
3 -import com.ruoyi.system.domain.IotDevice;  
4 -  
5 -public interface DeviceService {  
6 - IotDevice getDeviceById(String clientId);  
7 -}  
1 -package com.zhonglai.luhui.central.control.service;  
2 -  
3 -import com.zhonglai.luhui.central.control.config.MqttConfig;  
4 -import com.zhonglai.luhui.central.control.util.ByteUtil;  
5 -import org.eclipse.paho.client.mqttv3.*;  
6 -import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;  
7 -import org.slf4j.Logger;  
8 -import org.slf4j.LoggerFactory;  
9 -import org.springframework.beans.factory.annotation.Autowired;  
10 -import org.springframework.stereotype.Service;  
11 -  
12 -import javax.annotation.PostConstruct;  
13 -  
14 -@Service  
15 -public class MqttClientService {  
16 - private Logger log = LoggerFactory.getLogger(MqttClientService.class);  
17 -  
18 - @Autowired  
19 - private MqttConfig mqttConfig;  
20 -  
21 - @Autowired  
22 - private MqttMessageArrivedService mqttMessageArrivedService;  
23 -  
24 - @Autowired  
25 - private MqttOperation mqttOperation;  
26 -  
27 - private MqttClient mqttclient;  
28 -  
29 - private MqttConnectOptions options;  
30 -  
31 - {  
32 - if(null == mqttclient)  
33 - {  
34 - try {  
35 - mqttclient = new MqttClient(mqttConfig.getBroker(), mqttConfig.getClientId(), new MemoryPersistence());  
36 - } catch (MqttException e) {  
37 - e.printStackTrace();  
38 - }  
39 - options = new MqttConnectOptions();  
40 - options.setCleanSession(true);  
41 - options.setConnectionTimeout(15);  
42 - //设置断开后重新连接  
43 - options.setAutomaticReconnect(true);  
44 - mqttclient.setCallback(new MqttCallbackExtended() {  
45 - @Override  
46 - public void connectComplete(boolean b, String s) {  
47 - log.info("连接成功");  
48 - try {  
49 - subscribe();  
50 - } catch (MqttException e) {  
51 - e.printStackTrace();  
52 - }  
53 - }  
54 -  
55 - @Override  
56 - public void connectionLost(Throwable cause) {  
57 - log.error("连接丢失",cause);  
58 - }  
59 -  
60 - @Override  
61 - public void messageArrived(String topic, MqttMessage message) {  
62 - log.info("接收到消息topc:{}, mqttMessage {},payload 十六进制 {}",topic,message, ByteUtil.hexStringToSpace(ByteUtil.toHexString(message.getPayload())));  
63 - mqttMessageArrivedService.analysisMessage(topic,message);  
64 - }  
65 -  
66 - @Override  
67 - public void deliveryComplete(IMqttDeliveryToken token) {  
68 - try {  
69 - log.info("成功发出消息 messageid{}",token.getMessage());  
70 - } catch (MqttException e) {  
71 - e.printStackTrace();  
72 - }  
73 - }  
74 - });  
75 - }  
76 -  
77 - }  
78 -  
79 - @PostConstruct  
80 - public void init() throws MqttException {  
81 - log.info("-----------终端数据模型配置成功--------------------");  
82 - connect();  
83 - log.info("-----------mqtt连接服务器成功--------------------");  
84 - subscribe();  
85 - log.info("-----------订阅{}成功--------------------",mqttConfig.getTopics());  
86 - }  
87 -  
88 - private void connect() throws MqttException {  
89 - options.setUserName(mqttConfig.getUsername());  
90 - options.setPassword(mqttConfig.getPassword().toCharArray());  
91 - mqttclient.connect(options);  
92 - }  
93 -  
94 - private void subscribe() throws MqttException {  
95 - mqttOperation.subscribe(mqttclient,mqttConfig.getTopics().split(","));  
96 - }  
97 -  
98 -}  
1 -package com.zhonglai.luhui.central.control.service;  
2 -  
3 -import com.ruoyi.system.domain.IotDevice;  
4 -import com.zhonglai.luhui.central.control.comm.MqttAnalysisMessageResult;  
5 -import com.zhonglai.luhui.central.control.comm.Topic;  
6 -import org.eclipse.paho.client.mqttv3.MqttMessage;  
7 -import org.slf4j.Logger;  
8 -import org.slf4j.LoggerFactory;  
9 -import org.springframework.beans.factory.annotation.Autowired;  
10 -import org.springframework.stereotype.Service;  
11 -  
12 -/**  
13 - * 数据解析业务  
14 - */  
15 -@Service  
16 -public class MqttMessageArrivedService {  
17 - @Autowired  
18 - private DeviceService deviceService ;  
19 -  
20 - private Logger log = LoggerFactory.getLogger(MqttMessageArrivedService.class);  
21 -  
22 - public MqttAnalysisMessageResult analysisMessage(String topicStr, MqttMessage message)  
23 - {  
24 - Topic topic = new Topic(topicStr);  
25 - if(null == topic)  
26 - {  
27 - log.error("消息{},解析出来的topic为空,不做解析",topicStr);  
28 - return MqttAnalysisMessageResult.TopicException;  
29 - }  
30 -  
31 - IotDevice iotDevice = deviceService.getDeviceById(topic.getClientid());  
32 - if(null == iotDevice)  
33 - {  
34 - log.info("设备{}不存在",topic.getClientid());  
35 - return MqttAnalysisMessageResult.DeviceDoesNotExist;  
36 - }  
37 -  
38 - //消息分发  
39 - try {  
40 -// messageDistribution();  
41 - }catch (Exception e)  
42 - {  
43 - log.info("消息解析异常",e);  
44 - return MqttAnalysisMessageResult.PayloadParsingException;  
45 - }  
46 -  
47 - return MqttAnalysisMessageResult.Success;  
48 - }  
49 -  
50 -}  
1 -package com.zhonglai.luhui.central.control.service;  
2 -  
3 -import org.eclipse.paho.client.mqttv3.MqttClient;  
4 -import org.eclipse.paho.client.mqttv3.MqttException;  
5 -import org.eclipse.paho.client.mqttv3.MqttMessage;  
6 -import org.springframework.stereotype.Service;  
7 -  
8 -import java.nio.ByteBuffer;  
9 -import java.nio.charset.Charset;  
10 -  
11 -@Service  
12 -public class MqttOperation {  
13 - public void subscribe(MqttClient mqttclient,String[] topicFilters) throws MqttException {  
14 - mqttclient.subscribe(topicFilters);  
15 - }  
16 -  
17 - public void publish(MqttClient mqttclient,String topic, MqttMessage message) throws MqttException {  
18 - mqttclient.publish(topic,message);  
19 - }  
20 -  
21 - public void publish(MqttClient mqttclient,String topic, String messageStr) throws MqttException {  
22 - MqttMessage message = new MqttMessage();  
23 - message.setPayload(messageStr.getBytes());  
24 - mqttclient.publish(topic,message);  
25 - }  
26 -  
27 - public void closeClient (MqttClient mqttclient,String clientId,String code,String messageStr) throws MqttException {  
28 - String topic = "SYSOPERATION/CLOSE";  
29 - MqttMessage message = new MqttMessage();  
30 - Charset charset = Charset.forName("utf-8");  
31 - ByteBuffer payload = charset.encode(clientId+","+code+","+messageStr);  
32 - message.setPayload(payload.array());  
33 - mqttclient.publish(topic,message);  
34 - }  
35 -}  
1 -package com.zhonglai.luhui.central.control.util;  
2 -  
3 -import java.util.Arrays;  
4 -  
5 -public class ByteUtil {  
6 - /**  
7 - * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用  
8 - *  
9 - * @param src  
10 - * byte数组  
11 - * @param offset  
12 - * 从数组的第offset位开始  
13 - * @return int数值  
14 - */  
15 - public static long bytesToLongASC(byte[] src, int offset,int lenth) {  
16 - int value = 0;  
17 - for(int i=0;i<lenth;i++)  
18 - {  
19 - value = value | ((src[offset+i] & 0xFF)<<(8*i));  
20 - }  
21 - return value;  
22 - }  
23 -  
24 - /**  
25 - * 把16进制字符串转换成字节数组  
26 - *  
27 - * @param hex  
28 - * @return  
29 - */  
30 - public static byte[] hexStringToByte(String hex) {  
31 - int len = (hex.length() / 2);  
32 - byte[] result = new byte[len];  
33 - char[] achar = hex.toCharArray();  
34 - for (int i = 0; i < len; i++) {  
35 - int pos = i * 2;  
36 - result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));  
37 - }  
38 - return result;  
39 - }  
40 - private static byte toByte(char c) {  
41 - byte b = (byte) "0123456789ABCDEF".indexOf(c);  
42 - return b;  
43 - }  
44 -  
45 - /**  
46 - * 把16进制字符串转换成字节数组  
47 - *  
48 - * @param hex  
49 - * @return  
50 - */  
51 - public static String hexStringToSpace(String hex) {  
52 - if (null == hex) {  
53 - return null;  
54 - } else {  
55 - StringBuilder sb = new StringBuilder(hex.length() << 1);  
56 -  
57 - for(int i = 0; i < hex.length(); i+=2) {  
58 - sb.append(hex.substring(i,i+2)).append(" ");  
59 - }  
60 - return sb.toString();  
61 - }  
62 - }  
63 -  
64 - /**  
65 - * 把原数组加点目标数组后面  
66 - * @param dest 目标数组  
67 - * @param src 原数组  
68 - * @return  
69 - */  
70 - public static byte[] addBytes(byte[] dest,byte[] src )  
71 - {  
72 - int dl = dest.length;  
73 - int sl = src.length;  
74 - dest = Arrays.copyOf(dest, dl+sl);//数组扩容  
75 - System.arraycopy(src,0,dest,dl,src.length);  
76 - return dest;  
77 - }  
78 -  
79 - /**  
80 - * 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。 和bytesToInt2()配套使用  
81 - */  
82 - public static byte[] intToBytesDESC(long value,int lenth)  
83 - {  
84 - byte[] src = new byte[lenth];  
85 - for(int i=0;i<lenth;i++)  
86 - {  
87 - src[i] = (byte) ((value>>(8*(lenth-i-1))) & 0xFF);  
88 - }  
89 - return src;  
90 - }  
91 -  
92 - /**  
93 - * 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。 和bytesToInt()配套使用  
94 - * @param value  
95 - * 要转换的int值  
96 - * @return byte数组  
97 - */  
98 - public static byte[] intToBytesASC( long value,int lenth)  
99 - {  
100 - byte[] src = new byte[lenth];  
101 - for(int i=lenth;i>0;i--)  
102 - {  
103 - src[i-1] = (byte) ((value>>(8*(i-1))) & 0xFF);  
104 - }  
105 - return src;  
106 - }  
107 -  
108 - public static void main(String[] args) {  
109 - System.out.println(ByteUtil.toHexString( ByteUtil.intToBytesASC(2011239256,4)));  
110 - }  
111 -  
112 - /**  
113 - * ip转化位4byte  
114 - * @param ip  
115 - * @return  
116 - */  
117 - public static byte[] ipTo4Byte(String ip)  
118 - {  
119 - String[] ips = ip.split(".");  
120 - return new byte[]{(byte) Integer.parseInt(ips[0]),(byte) Integer.parseInt(ips[1]),(byte) Integer.parseInt(ips[2]),(byte) Integer.parseInt(ips[3])};  
121 - }  
122 -  
123 - /**  
124 - * byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。和intToBytes2()配套使用  
125 - */  
126 - public static long bytesToLongDESC(byte[] src, int offset,int lenth) {  
127 - long value = 0;  
128 - for(int i=lenth;i>0;i--)  
129 - {  
130 - value = value | ((src[offset+(lenth-i)] & 0xFF)<<(8*(i-1)));  
131 - }  
132 - return value;  
133 - }  
134 -  
135 - private static final char[] hex = "0123456789abcdef".toCharArray();  
136 - public static String toHexString(byte[] bytes) {  
137 - if (null == bytes) {  
138 - return null;  
139 - } else {  
140 - StringBuilder sb = new StringBuilder(bytes.length << 1);  
141 -  
142 - for(int i = 0; i < bytes.length; ++i) {  
143 - sb.append(hex[(bytes[i] & 240) >> 4]).append(hex[bytes[i] & 15]);  
144 - }  
145 -  
146 - return sb.toString();  
147 - }  
148 - }  
149 -  
150 - /**  
151 - * 计算CRC16/Modbus校验码 低位在前,高位在后  
152 - *  
153 - * @param str 十六进制字符串  
154 - * @return  
155 - */  
156 - public static String getCRC16(String str) {  
157 - byte[] bytes = hexStringToByte(str);  
158 - return getCRC16(bytes);  
159 - }  
160 -  
161 - /**  
162 - * 计算CRC16/Modbus校验码 低位在前,高位在后  
163 - *  
164 - * @return  
165 - */  
166 - public static String getCRC16( byte[] bytes) {  
167 - int CRC = 0x0000ffff;  
168 - int POLYNOMIAL = 0x0000a001;  
169 -  
170 - int i, j;  
171 - for (i = 0; i < bytes.length; i++) {  
172 - CRC ^= ((int) bytes[i] & 0x000000ff);  
173 - for (j = 0; j < 8; j++) {  
174 - if ((CRC & 0x00000001) != 0) {  
175 - CRC >>= 1;  
176 - CRC ^= POLYNOMIAL;  
177 - } else {  
178 - CRC >>= 1;  
179 - }  
180 - }  
181 - }  
182 - String crc = Integer.toHexString(CRC);  
183 - if (crc.length() == 2) {  
184 - crc = "00" + crc;  
185 - } else if (crc.length() == 3) {  
186 - crc = "0" + crc;  
187 - }  
188 - crc = crc.substring(2, 4) + crc.substring(0, 2);  
189 - return crc.toUpperCase();  
190 - }  
191 -}