作者 钟来

换新的方式实现数据服务

正在显示 51 个修改的文件 包含 1249 行增加813 行删除
@@ -61,7 +61,7 @@ public class IotTerminalController extends BaseController @@ -61,7 +61,7 @@ public class IotTerminalController extends BaseController
61 61
62 @ApiOperation("根据网关获取未分配终端") 62 @ApiOperation("根据网关获取未分配终端")
63 @ApiImplicitParam(value = "网关id",name = "imei") 63 @ApiImplicitParam(value = "网关id",name = "imei")
64 - @GetMapping(value = "/getListByDevice{imei}") 64 + @GetMapping(value = "/getListByDevice/{imei}")
65 public AjaxResult getListByDevice(@PathVariable("imei") String imei) 65 public AjaxResult getListByDevice(@PathVariable("imei") String imei)
66 { 66 {
67 List<IotTerminal> list = iotTerminalService.selectNotUserIotTerminalListByImei(imei); 67 List<IotTerminal> list = iotTerminalService.selectNotUserIotTerminalListByImei(imei);
@@ -25,6 +25,7 @@ public class IotDevice implements Serializable @@ -25,6 +25,7 @@ public class IotDevice implements Serializable
25 private Integer active_time; 25 private Integer active_time;
26 26
27 /** 主键 */ 27 /** 主键 */
  28 + @PublicSQLConfig(isPrimarykey = true)
28 @ApiModelProperty("主键") 29 @ApiModelProperty("主键")
29 private String client_id; 30 private String client_id;
30 31
@@ -51,10 +51,54 @@ public class IotTerminal implements Serializable @@ -51,10 +51,54 @@ public class IotTerminal implements Serializable
51 @ApiModelProperty("数据更新时间") 51 @ApiModelProperty("数据更新时间")
52 private Integer data_update_time; 52 private Integer data_update_time;
53 53
  54 + @ApiModelProperty("关联用户")
  55 + private Integer user_info_id;
  56 +
  57 + @ApiModelProperty("创建时间")
  58 + private Integer create_time;
  59 +
  60 + @ApiModelProperty("终端编号")
  61 + private String sensor_number;
  62 +
  63 + @ApiModelProperty("在线状态")
  64 + private Integer online;
  65 +
54 private UserTerminalGroupRelation userTerminalGroupRelation; 66 private UserTerminalGroupRelation userTerminalGroupRelation;
55 67
56 private IotDevice iotDevice; 68 private IotDevice iotDevice;
57 69
  70 + public Integer getOnline() {
  71 + return online;
  72 + }
  73 +
  74 + public void setOnline(Integer online) {
  75 + this.online = online;
  76 + }
  77 +
  78 + public Integer getUser_info_id() {
  79 + return user_info_id;
  80 + }
  81 +
  82 + public void setUser_info_id(Integer user_info_id) {
  83 + this.user_info_id = user_info_id;
  84 + }
  85 +
  86 + public Integer getCreate_time() {
  87 + return create_time;
  88 + }
  89 +
  90 + public void setCreate_time(Integer create_time) {
  91 + this.create_time = create_time;
  92 + }
  93 +
  94 + public String getSensor_number() {
  95 + return sensor_number;
  96 + }
  97 +
  98 + public void setSensor_number(String sensor_number) {
  99 + this.sensor_number = sensor_number;
  100 + }
  101 +
58 public IotDevice getIotDevice() { 102 public IotDevice getIotDevice() {
59 return iotDevice; 103 return iotDevice;
60 } 104 }
@@ -10,4 +10,5 @@ import java.lang.annotation.Target; @@ -10,4 +10,5 @@ import java.lang.annotation.Target;
10 @Retention(RetentionPolicy.RUNTIME) 10 @Retention(RetentionPolicy.RUNTIME)
11 public @interface PublicSQLConfig { 11 public @interface PublicSQLConfig {
12 boolean isSelect() default true; 12 boolean isSelect() default true;
  13 + boolean isPrimarykey() default false;
13 } 14 }
@@ -167,6 +167,11 @@ @@ -167,6 +167,11 @@
167 <artifactId>lh-domain</artifactId> 167 <artifactId>lh-domain</artifactId>
168 </dependency> 168 </dependency>
169 169
  170 + <dependency>
  171 + <groupId>org.apache.rocketmq</groupId>
  172 + <artifactId>rocketmq-spring-boot-starter</artifactId>
  173 + </dependency>
  174 +
170 </dependencies> 175 </dependencies>
171 176
172 <build> 177 <build>
@@ -11,6 +11,7 @@ import org.springframework.context.annotation.ComponentScan; @@ -11,6 +11,7 @@ import org.springframework.context.annotation.ComponentScan;
11 "com.zhonglai.luhui.mqtt.comm.config", 11 "com.zhonglai.luhui.mqtt.comm.config",
12 "com.zhonglai.luhui.mqtt.comm.agreement", 12 "com.zhonglai.luhui.mqtt.comm.agreement",
13 "com.zhonglai.luhui.mqtt.comm.service", 13 "com.zhonglai.luhui.mqtt.comm.service",
  14 + "com.zhonglai.luhui.mqtt.comm.rocketMq",
14 "com.zhonglai.luhui.mqtt.config", 15 "com.zhonglai.luhui.mqtt.config",
15 "com.zhonglai.luhui.mqtt.service", 16 "com.zhonglai.luhui.mqtt.service",
16 "com.zhonglai.luhui.mqtt.controller", 17 "com.zhonglai.luhui.mqtt.controller",
1 package com.zhonglai.luhui.mqtt.comm.clien; 1 package com.zhonglai.luhui.mqtt.comm.clien;
2 2
3 3
4 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent; 4 +import com.zhonglai.luhui.mqtt.comm.dto.ApiClientRePlyDto;
5 import com.zhonglai.luhui.mqtt.dto.Message; 5 import com.zhonglai.luhui.mqtt.dto.Message;
6 6
7 /** 7 /**
@@ -12,9 +12,8 @@ public interface ClienConnection { @@ -12,9 +12,8 @@ public interface ClienConnection {
12 12
13 /** 13 /**
14 * 回复 14 * 回复
15 - * @param agreementContent  
16 */ 15 */
17 - public void reply(ServerAgreementContent agreementContent); 16 + public void reply(ApiClientRePlyDto apiClientRePlyDto);
18 17
19 /** 18 /**
20 * 回复 19 * 回复
@@ -2,7 +2,7 @@ package com.zhonglai.luhui.mqtt.comm.clien.impl; @@ -2,7 +2,7 @@ package com.zhonglai.luhui.mqtt.comm.clien.impl;
2 2
3 3
4 import com.zhonglai.luhui.mqtt.comm.clien.ClienConnection; 4 import com.zhonglai.luhui.mqtt.comm.clien.ClienConnection;
5 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent; 5 +import com.zhonglai.luhui.mqtt.comm.dto.ApiClientRePlyDto;
6 import com.zhonglai.luhui.mqtt.dto.Message; 6 import com.zhonglai.luhui.mqtt.dto.Message;
7 import com.zhonglai.luhui.mqtt.dto.MessageCode; 7 import com.zhonglai.luhui.mqtt.dto.MessageCode;
8 import com.zhonglai.luhui.mqtt.dto.MessageCodeType; 8 import com.zhonglai.luhui.mqtt.dto.MessageCodeType;
@@ -18,8 +18,8 @@ public class ClienConnectionImpl implements ClienConnection { @@ -18,8 +18,8 @@ public class ClienConnectionImpl implements ClienConnection {
18 } 18 }
19 19
20 @Override 20 @Override
21 - public void reply(ServerAgreementContent agreementContent) {  
22 - agreementContent.setReplyMessage(message); 21 + public void reply(ApiClientRePlyDto apiClientRePlyDto) {
  22 + apiClientRePlyDto.setReplyMessage(message);
23 this.notify(); 23 this.notify();
24 } 24 }
25 25
  1 +package com.zhonglai.luhui.mqtt.comm.config;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.alibaba.fastjson.serializer.SerializerFeature;
  5 +import com.fasterxml.jackson.databind.JavaType;
  6 +import com.fasterxml.jackson.databind.ObjectMapper;
  7 +import com.fasterxml.jackson.databind.type.TypeFactory;
  8 +import org.springframework.data.redis.serializer.RedisSerializer;
  9 +import org.springframework.data.redis.serializer.SerializationException;
  10 +import org.springframework.util.Assert;
  11 +
  12 +import java.nio.charset.Charset;
  13 +
  14 +/**
  15 + * Redis使用FastJson序列化
  16 + *
  17 + * @author ruoyi
  18 + */
  19 +public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
  20 +{
  21 + @SuppressWarnings("unused")
  22 + private ObjectMapper objectMapper = new ObjectMapper();
  23 +
  24 + public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  25 +
  26 + private Class<T> clazz;
  27 +
  28 + public FastJson2JsonRedisSerializer(Class<T> clazz)
  29 + {
  30 + super();
  31 + this.clazz = clazz;
  32 + }
  33 +
  34 + @Override
  35 + public byte[] serialize(T t) throws SerializationException
  36 + {
  37 + if (t == null)
  38 + {
  39 + return new byte[0];
  40 + }
  41 + //SerializerFeature.DisableCircularReferenceDetect解决重复引用的问题
  42 + return JSON.toJSONString(t, SerializerFeature.WriteClassName,SerializerFeature.DisableCircularReferenceDetect).getBytes(DEFAULT_CHARSET);
  43 + }
  44 +
  45 + @Override
  46 + public T deserialize(byte[] bytes) throws SerializationException
  47 + {
  48 + if (bytes == null || bytes.length <= 0)
  49 + {
  50 + return null;
  51 + }
  52 + String str = new String(bytes, DEFAULT_CHARSET);
  53 +
  54 + return JSON.parseObject(str, clazz);
  55 + }
  56 +
  57 + public void setObjectMapper(ObjectMapper objectMapper)
  58 + {
  59 + Assert.notNull(objectMapper, "'objectMapper' must not be null");
  60 + this.objectMapper = objectMapper;
  61 + }
  62 +
  63 + protected JavaType getJavaType(Class<?> clazz)
  64 + {
  65 + return TypeFactory.defaultInstance().constructType(clazz);
  66 + }
  67 +}
1 package com.zhonglai.luhui.mqtt.comm.config; 1 package com.zhonglai.luhui.mqtt.comm.config;
2 2
  3 +import com.alibaba.fastjson.parser.ParserConfig;
3 import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 import com.fasterxml.jackson.annotation.JsonAutoDetect;
4 import com.fasterxml.jackson.annotation.JsonTypeInfo; 5 import com.fasterxml.jackson.annotation.JsonTypeInfo;
5 import com.fasterxml.jackson.annotation.PropertyAccessor; 6 import com.fasterxml.jackson.annotation.PropertyAccessor;
6 import com.fasterxml.jackson.databind.ObjectMapper; 7 import com.fasterxml.jackson.databind.ObjectMapper;
  8 +import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
7 import org.springframework.beans.factory.annotation.Value; 9 import org.springframework.beans.factory.annotation.Value;
8 import org.springframework.context.annotation.Bean; 10 import org.springframework.context.annotation.Bean;
9 import org.springframework.context.annotation.Configuration; 11 import org.springframework.context.annotation.Configuration;
  12 +import org.springframework.data.redis.connection.RedisConnection;
10 import org.springframework.data.redis.connection.RedisConnectionFactory; 13 import org.springframework.data.redis.connection.RedisConnectionFactory;
11 import org.springframework.data.redis.core.RedisTemplate; 14 import org.springframework.data.redis.core.RedisTemplate;
12 import org.springframework.data.redis.listener.PatternTopic; 15 import org.springframework.data.redis.listener.PatternTopic;
@@ -14,8 +17,10 @@ import org.springframework.data.redis.listener.RedisMessageListenerContainer; @@ -14,8 +17,10 @@ import org.springframework.data.redis.listener.RedisMessageListenerContainer;
14 import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; 17 import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
15 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 18 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
16 import org.springframework.data.redis.serializer.StringRedisSerializer; 19 import org.springframework.data.redis.serializer.StringRedisSerializer;
  20 +import org.springframework.util.StringUtils;
17 21
18 import javax.annotation.PostConstruct; 22 import javax.annotation.PostConstruct;
  23 +import java.util.Properties;
19 24
20 @Configuration 25 @Configuration
21 public class RedisConfig { 26 public class RedisConfig {
@@ -33,55 +38,62 @@ public class RedisConfig { @@ -33,55 +38,62 @@ public class RedisConfig {
33 RedisConfig.FIELD = sysRedisField; 38 RedisConfig.FIELD = sysRedisField;
34 } 39 }
35 40
36 -  
37 @Bean 41 @Bean
38 - public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){  
39 - RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();  
40 - //设置工厂链接  
41 - redisTemplate.setConnectionFactory(redisConnectionFactory);  
42 - //设置自定义序列化方式  
43 - setSerializeConfig(redisTemplate, redisConnectionFactory);  
44 - return redisTemplate;  
45 - } 42 + @SuppressWarnings(value = { "unchecked", "rawtypes" })
  43 + public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
  44 + {
  45 + RedisTemplate<Object, Object> template = new RedisTemplate<>();
  46 + template.setConnectionFactory(connectionFactory);
46 47
47 - private void setSerializeConfig(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory redisConnectionFactory) {  
48 - //对字符串采取普通的序列化方式 适用于key 因为我们一般采取简单字符串作为key  
49 - StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();  
50 - //普通的string类型的key采用 普通序列化方式  
51 - redisTemplate.setKeySerializer(stringRedisSerializer);  
52 - //普通hash类型的key也使用 普通序列化方式  
53 - redisTemplate.setHashKeySerializer(stringRedisSerializer);  
54 - //解决查询缓存转换异常的问题 大家不能理解就直接用就可以了 这是springboot自带的jackson序列化类,但是会有一定问题  
55 - Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);  
56 - ObjectMapper om = new ObjectMapper();  
57 - om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
58 - om.activateDefaultTyping(om.getPolymorphicTypeValidator(),ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);  
59 - jackson2JsonRedisSerializer.setObjectMapper(om);  
60 - //普通的值采用jackson方式自动序列化  
61 - redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);  
62 - //hash类型的值也采用jackson方式序列化  
63 - redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);  
64 - //属性设置完成afterPropertiesSet就会被调用,可以对设置不成功的做一些默认处理  
65 - redisTemplate.afterPropertiesSet();  
66 - } 48 + //配置
  49 + ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
  50 + FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
67 51
  52 + ObjectMapper mapper = new ObjectMapper();
  53 + mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  54 + mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
  55 + serializer.setObjectMapper(mapper);
68 56
69 - /**  
70 - * redis消息监听  
71 - * @param connectionFactory  
72 - * @return  
73 - */  
74 - @Bean  
75 - public RedisMessageListenerContainer messageListenerContainer(RedisConnectionFactory connectionFactory) {  
76 - RedisMessageListenerContainer container = new RedisMessageListenerContainer();  
77 - container.setConnectionFactory(connectionFactory);  
78 - container.addMessageListener(new MessageListenerAdapter(), new PatternTopic(getRedisKeyPath()+"**")); 57 + // 使用StringRedisSerializer来序列化和反序列化redis的key值
  58 + template.setKeySerializer(new StringRedisSerializer());
  59 + template.setValueSerializer(serializer);
79 60
80 - return container;  
81 - } 61 + // Hash的key也采用StringRedisSerializer的序列化方式
  62 + template.setHashKeySerializer(new StringRedisSerializer());
  63 + template.setHashValueSerializer(serializer);
82 64
83 - public static String getRedisKeyPath()  
84 - {  
85 - return FIELD+ RedisKeyMqttUser.ROLEID+":"+ RedisKeyMqttUser.USERNAME+":"; 65 + template.afterPropertiesSet();
  66 + return template;
86 } 67 }
  68 +// @Bean
  69 +// public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
  70 +// RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
  71 +// //设置工厂链接
  72 +// redisTemplate.setConnectionFactory(redisConnectionFactory);
  73 +// //设置自定义序列化方式
  74 +// setSerializeConfig(redisTemplate, redisConnectionFactory);
  75 +// return redisTemplate;
  76 +// }
  77 +//
  78 +// private void setSerializeConfig(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory redisConnectionFactory) {
  79 +// //对字符串采取普通的序列化方式 适用于key 因为我们一般采取简单字符串作为key
  80 +// StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  81 +// //普通的string类型的key采用 普通序列化方式
  82 +// redisTemplate.setKeySerializer(stringRedisSerializer);
  83 +// //普通hash类型的key也使用 普通序列化方式
  84 +// redisTemplate.setHashKeySerializer(stringRedisSerializer);
  85 +// //解决查询缓存转换异常的问题 大家不能理解就直接用就可以了 这是springboot自带的jackson序列化类,但是会有一定问题
  86 +// Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  87 +// ObjectMapper om = new ObjectMapper();
  88 +// om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  89 +// om.activateDefaultTyping(om.getPolymorphicTypeValidator(),ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
  90 +// jackson2JsonRedisSerializer.setObjectMapper(om);
  91 +// //普通的值采用jackson方式自动序列化
  92 +// redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
  93 +// //hash类型的值也采用jackson方式序列化
  94 +// redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
  95 +// //属性设置完成afterPropertiesSet就会被调用,可以对设置不成功的做一些默认处理
  96 +// redisTemplate.afterPropertiesSet();
  97 +// }
  98 +
87 } 99 }
1 package com.zhonglai.luhui.mqtt.comm.dao; 1 package com.zhonglai.luhui.mqtt.comm.dao;
2 2
3 import com.alibaba.fastjson.JSONArray; 3 import com.alibaba.fastjson.JSONArray;
  4 +import com.ruoyi.system.domain.tool.PublicSQLConfig;
4 import org.apache.commons.dbutils.*; 5 import org.apache.commons.dbutils.*;
5 import org.apache.commons.dbutils.handlers.BeanHandler; 6 import org.apache.commons.dbutils.handlers.BeanHandler;
6 import org.apache.commons.dbutils.handlers.BeanListHandler; 7 import org.apache.commons.dbutils.handlers.BeanListHandler;
@@ -59,7 +60,7 @@ public class BaseDao { @@ -59,7 +60,7 @@ public class BaseDao {
59 sql += ","; 60 sql += ",";
60 values += ","; 61 values += ",";
61 } 62 }
62 - sql += "`"+changTableNameFromObject(field.getName())+"`"; 63 + sql += "`"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`";
63 values += "?"; 64 values += "?";
64 valueList.add(value); 65 valueList.add(value);
65 } 66 }
@@ -119,7 +120,7 @@ public class BaseDao { @@ -119,7 +120,7 @@ public class BaseDao {
119 String sql = "insert into "; 120 String sql = "insert into ";
120 if(StringUtils.isBlank(tableName)) 121 if(StringUtils.isBlank(tableName))
121 { 122 {
122 - tableName = changTableNameFromObject(object.getClass().getSimpleName()); 123 + tableName = com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(object.getClass().getSimpleName());
123 } 124 }
124 125
125 List<Object> valueList = new ArrayList<Object>(); 126 List<Object> valueList = new ArrayList<Object>();
@@ -303,10 +304,20 @@ public class BaseDao { @@ -303,10 +304,20 @@ public class BaseDao {
303 }else{ 304 }else{
304 Method method = null; 305 Method method = null;
305 try { 306 try {
306 - method = object.getClass().getMethod("get"+ com.zhonglai.luhui.mqtt.comm.util.StringUtils.getName("id")); 307 + String idName = "id";
  308 + for(Field field:fields)
  309 + {
  310 + PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
  311 + if(null != publicSQLConfig && publicSQLConfig.isPrimarykey())
  312 + {
  313 + idName = field.getName();
  314 + }
  315 + }
  316 + method = object.getClass().getMethod("get"+ com.zhonglai.luhui.mqtt.comm.util.StringUtils.getName(idName));
307 Object value = method.invoke(object); 317 Object value = method.invoke(object);
308 sql += " and "; 318 sql += " and ";
309 - sql += "id=?"; 319 +
  320 + sql += idName+"=?";
310 valueList.add(value); 321 valueList.add(value);
311 } catch (NoSuchMethodException e) { 322 } catch (NoSuchMethodException e) {
312 e.printStackTrace(); 323 e.printStackTrace();
@@ -337,7 +348,7 @@ public class BaseDao { @@ -337,7 +348,7 @@ public class BaseDao {
337 { 348 {
338 QueryRunner runner = new QueryRunner(dBFactory.getDataSource()); 349 QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
339 350
340 - String tableName = changTableNameFromObject(clas.getSimpleName()); 351 + String tableName = com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(clas.getSimpleName());
341 352
342 String sql = "select * from "+tableName+" where 1=1 "; 353 String sql = "select * from "+tableName+" where 1=1 ";
343 try { 354 try {
@@ -383,12 +394,22 @@ public class BaseDao { @@ -383,12 +394,22 @@ public class BaseDao {
383 { 394 {
384 QueryRunner runner = new QueryRunner(dBFactory.getDataSource()); 395 QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
385 396
386 - String tableName = changTableNameFromObject(clas.getSimpleName()); 397 + String tableName = com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(clas.getSimpleName());
387 398
388 String sql = "select * from "+tableName+" where 1=1 "; 399 String sql = "select * from "+tableName+" where 1=1 ";
  400 + String idName = "id";
  401 + Field[] fields = clas.getDeclaredFields();
  402 + for(Field field:fields)
  403 + {
  404 + PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
  405 + if(null != publicSQLConfig && publicSQLConfig.isPrimarykey())
  406 + {
  407 + idName = field.getName();
  408 + }
  409 + }
389 410
390 try { 411 try {
391 - sql += " and id=?"; 412 + sql += " and "+idName+"=?";
392 Object[] params = {id}; 413 Object[] params = {id};
393 return runner.query(sql, new BeanHandler<T>(clas, getRowProcessor()),params); 414 return runner.query(sql, new BeanHandler<T>(clas, getRowProcessor()),params);
394 } catch (SQLException e) { 415 } catch (SQLException e) {
@@ -407,7 +428,7 @@ public class BaseDao { @@ -407,7 +428,7 @@ public class BaseDao {
407 { 428 {
408 QueryRunner runner = new QueryRunner(dBFactory.getDataSource()); 429 QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
409 430
410 - String tableName = changTableNameFromObject(clas.getSimpleName()); 431 + String tableName = com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(clas.getSimpleName());
411 String sql = "DELETE FROM "+tableName+" WHERE 1=1 "; 432 String sql = "DELETE FROM "+tableName+" WHERE 1=1 ";
412 try { 433 try {
413 List<Object> valueList = new ArrayList<Object>(); 434 List<Object> valueList = new ArrayList<Object>();
@@ -440,7 +461,7 @@ public class BaseDao { @@ -440,7 +461,7 @@ public class BaseDao {
440 461
441 if(StringUtils.isBlank(tableName)) 462 if(StringUtils.isBlank(tableName))
442 { 463 {
443 - tableName = changTableNameFromObject(clas.getSimpleName()); 464 + tableName = com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(clas.getSimpleName());
444 } 465 }
445 String sql = "DELETE FROM "+tableName+" WHERE 1=1 "; 466 String sql = "DELETE FROM "+tableName+" WHERE 1=1 ";
446 try { 467 try {
@@ -705,17 +726,17 @@ public class BaseDao { @@ -705,17 +726,17 @@ public class BaseDao {
705 if("like".equals(s)) 726 if("like".equals(s))
706 { 727 {
707 value = "%"+value+"%"; 728 value = "%"+value+"%";
708 - like += " or " + "`"+changTableNameFromObject(field.getName())+"`"+s+" ?"+orther ; 729 + like += " or " + "`"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" ?"+orther ;
709 valueList.add(value); 730 valueList.add(value);
710 continue; 731 continue;
711 } 732 }
712 if("time".equals(s)) 733 if("time".equals(s))
713 { 734 {
714 s = ">"; 735 s = ">";
715 - orther = " and `"+changTableNameFromObject(field.getName())+"`< '"+whereMap.get("end_"+field.getName())+"'"; 736 + orther = " and `"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`< '"+whereMap.get("end_"+field.getName())+"'";
716 } 737 }
717 } 738 }
718 - where += " and `"+changTableNameFromObject(field.getName())+"`"+s+" ?"+orther; 739 + where += " and `"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" ?"+orther;
719 valueList.add(value); 740 valueList.add(value);
720 } 741 }
721 } catch (NoSuchMethodException e) { 742 } catch (NoSuchMethodException e) {
@@ -829,8 +850,8 @@ public class BaseDao { @@ -829,8 +850,8 @@ public class BaseDao {
829 sb.append(","); 850 sb.append(",");
830 update += ","; 851 update += ",";
831 } 852 }
832 - sb.append("`"+changTableNameFromObject(field.getName())+"`");  
833 - update += "`"+changTableNameFromObject(field.getName())+"`"+"=VALUES("+"`"+changTableNameFromObject(field.getName())+"`)"; 853 + sb.append("`"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`");
  854 + update += "`"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`"+"=VALUES("+"`"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`)";
834 } 855 }
835 sb.append(")"); 856 sb.append(")");
836 sb.append("VALUES "); 857 sb.append("VALUES ");
@@ -901,7 +922,7 @@ public class BaseDao { @@ -901,7 +922,7 @@ public class BaseDao {
901 { 922 {
902 Object value = mapwhere.get(key); 923 Object value = mapwhere.get(key);
903 where += " and "; 924 where += " and ";
904 - where += changTableNameFromObject(key) + "=?"; 925 + where += com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(key) + "=?";
905 valueList.add(value); 926 valueList.add(value);
906 } 927 }
907 return where; 928 return where;
  1 +package com.zhonglai.luhui.mqtt.comm.dto;
  2 +
  3 +import com.zhonglai.luhui.mqtt.dto.Message;
  4 +
  5 +/**
  6 + * 回复给前端的消息
  7 + */
  8 +public interface ApiClientRePlyDto {
  9 + void setReplyMessage(Message message);
  10 +}
1 package com.zhonglai.luhui.mqtt.comm.dto; 1 package com.zhonglai.luhui.mqtt.comm.dto;
2 2
3 3
  4 +import com.ruoyi.system.domain.IotDevice;
  5 +import com.ruoyi.system.domain.IotTerminal;
  6 +
4 import java.util.List; 7 import java.util.List;
5 8
6 -public interface ServerDto {  
7 - ServerAgreementContent getServerAgreementContent();  
8 - boolean isReplyMessage();  
9 - List<DeviceSensorData> getDeviceSensorData();  
10 - List<LogDeviceOperation> getOperationLog(); 9 +public abstract class ServerDto {
  10 + private IotDevice iotDevice;
  11 + private List<IotTerminal> iotTerminalList;
  12 + private List<DeviceSensorData> deviceSensorDataList;
  13 + private List<LogDeviceOperation> logDeviceOperationList;
  14 +
  15 + public IotDevice getIotDevice() {
  16 + return iotDevice;
  17 + }
  18 +
  19 + public void setIotDevice(IotDevice iotDevice) {
  20 + this.iotDevice = iotDevice;
  21 + }
  22 +
  23 + public List<IotTerminal> getIotTerminalList() {
  24 + return iotTerminalList;
  25 + }
  26 +
  27 + public void setIotTerminalList(List<IotTerminal> iotTerminalList) {
  28 + this.iotTerminalList = iotTerminalList;
  29 + }
  30 +
  31 + public List<DeviceSensorData> getDeviceSensorDataList() {
  32 + return deviceSensorDataList;
  33 + }
  34 +
  35 + public void setDeviceSensorDataList(List<DeviceSensorData> deviceSensorDataList) {
  36 + this.deviceSensorDataList = deviceSensorDataList;
  37 + }
  38 +
  39 + public List<LogDeviceOperation> getLogDeviceOperationList() {
  40 + return logDeviceOperationList;
  41 + }
  42 +
  43 + public void setLogDeviceOperationList(List<LogDeviceOperation> logDeviceOperationList) {
  44 + this.logDeviceOperationList = logDeviceOperationList;
  45 + }
11 } 46 }
1 package com.zhonglai.luhui.mqtt.comm.dto; 1 package com.zhonglai.luhui.mqtt.comm.dto;
2 2
3 -  
4 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 3 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
5 -import com.zhonglai.luhui.mqtt.dto.Message;  
6 4
7 -public interface ServerAgreementContent { 5 +/**
  6 + * 回复给终端的消息
  7 + */
  8 +public interface TerminalClientRePlyDto {
8 byte[] getCommd(); 9 byte[] getCommd();
9 String getReplyCommdTopic(Topic topic); 10 String getReplyCommdTopic(Topic topic);
10 - void setReplyMessage(Message message);  
11 } 11 }
  1 +package com.zhonglai.luhui.mqtt.comm.rocketMq;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.zhonglai.luhui.mqtt.comm.service.MqttCallback;
  5 +import com.zhonglai.luhui.mqtt.dto.DeviceCommandApi;
  6 +import com.zhonglai.luhui.mqtt.dto.Message;
  7 +import com.zhonglai.luhui.mqtt.dto.MessageCode;
  8 +import com.zhonglai.luhui.mqtt.service.db.DeviceService;
  9 +import org.apache.rocketmq.common.message.MessageExt;
  10 +import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
  11 +import org.apache.rocketmq.spring.core.RocketMQReplyListener;
  12 +import org.slf4j.Logger;
  13 +import org.slf4j.LoggerFactory;
  14 +import org.springframework.beans.factory.annotation.Autowired;
  15 +import org.springframework.stereotype.Service;
  16 +
  17 +
  18 +@Service
  19 +@RocketMQMessageListener(consumerGroup = "deviceCommand", topic = "lh-mqtt-service-deviceCommand")
  20 +public class RocketMqService implements RocketMQReplyListener<MessageExt, Message> {
  21 + private static final Logger log = LoggerFactory.getLogger(MqttCallback.class);
  22 +
  23 + @Autowired
  24 + private DeviceService deviceService ;
  25 +
  26 + @Override
  27 + public Message onMessage(MessageExt messageExt) {
  28 + log.info("监听到消息{}",messageExt);
  29 +// String clint = MessageUtil.getReplyToClient(messageExt);
  30 +
  31 + String str = new String(messageExt.getBody());
  32 + DeviceCommandApi deviceCommandApi = JSON.parseObject(str, DeviceCommandApi.class);
  33 + try {
  34 + return deviceCommandApi.invokeApi(deviceService);
  35 + } catch (Exception e) {
  36 + log.error("执行异常",e);
  37 + }
  38 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"服务器玩脱了");
  39 + }
  40 +
  41 +
  42 +}
@@ -6,10 +6,13 @@ import com.ruoyi.system.domain.IotTerminal; @@ -6,10 +6,13 @@ import com.ruoyi.system.domain.IotTerminal;
6 import com.zhonglai.luhui.mqtt.comm.config.SysParameter; 6 import com.zhonglai.luhui.mqtt.comm.config.SysParameter;
7 import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData; 7 import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;
8 import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation; 8 import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;
  9 +import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
9 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 10 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
10 import com.zhonglai.luhui.mqtt.comm.util.DateUtils; 11 import com.zhonglai.luhui.mqtt.comm.util.DateUtils;
11 import com.zhonglai.luhui.mqtt.dto.SaveDataDto; 12 import com.zhonglai.luhui.mqtt.dto.SaveDataDto;
12 import com.zhonglai.luhui.mqtt.dto.topic.AddPostDto; 13 import com.zhonglai.luhui.mqtt.dto.topic.AddPostDto;
  14 +import com.zhonglai.luhui.mqtt.dto.topic.AllPostDto;
  15 +import com.zhonglai.luhui.mqtt.service.CacheServiceImpl;
13 import com.zhonglai.luhui.mqtt.service.db.DeviceService; 16 import com.zhonglai.luhui.mqtt.service.db.DeviceService;
14 import org.slf4j.Logger; 17 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory; 18 import org.slf4j.LoggerFactory;
@@ -34,10 +37,14 @@ public class BusinessDataUpdateService { @@ -34,10 +37,14 @@ public class BusinessDataUpdateService {
34 @Autowired 37 @Autowired
35 private DataModeAnalysisService dataModeAnalysisService ; 38 private DataModeAnalysisService dataModeAnalysisService ;
36 @Autowired 39 @Autowired
37 - private DeviceLogService deviceLogService ;  
38 - @Autowired  
39 private DeviceService deviceService ; 40 private DeviceService deviceService ;
40 41
  42 + @Autowired
  43 + private CacheServiceImpl cacheService ;
  44 +
  45 + @Autowired
  46 + private DeviceLogService deviceLogService;
  47 +
41 @Value("${server.port}") 48 @Value("${server.port}")
42 private long port; 49 private long port;
43 50
@@ -50,11 +57,21 @@ public class BusinessDataUpdateService { @@ -50,11 +57,21 @@ public class BusinessDataUpdateService {
50 * 更新数据 57 * 更新数据
51 * @param type 58 * @param type
52 * @param topic 59 * @param topic
53 - * @param data  
54 */ 60 */
55 - public void updataDta(Type type,Topic topic, JSONObject data,boolean isOperLog,List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list) 61 + public void updataDta(Type type, Topic topic, boolean isOperLog, ServerDto serverDto)
56 { 62 {
57 - IotDevice olddevice = deviceService.getRedicDevice(topic.getClientid()); 63 + IotDevice olddevice = cacheService.getIotDevice(topic.getClientid());
  64 +
  65 + JSONObject data = new JSONObject();
  66 + switch (type)
  67 + {
  68 + case ADD:
  69 + data = ((AddPostDto)serverDto).getData();
  70 + break;
  71 + case ALL:
  72 + data = ((AllPostDto)serverDto).getData();
  73 + break;
  74 + }
58 75
59 for(String key:data.keySet()) 76 for(String key:data.keySet())
60 { 77 {
@@ -64,7 +81,7 @@ public class BusinessDataUpdateService { @@ -64,7 +81,7 @@ public class BusinessDataUpdateService {
64 JSONObject jsData = data.getJSONObject(key); 81 JSONObject jsData = data.getJSONObject(key);
65 if("0".equals(key)) //主机 82 if("0".equals(key)) //主机
66 { 83 {
67 - IotDevice iotDevice = translateDevice(type,olddevice,jsData,isOperLog,operateHisList,list); 84 + IotDevice iotDevice = translateDevice(type,olddevice,jsData,isOperLog,serverDto);
68 if(isText) 85 if(isText)
69 { 86 {
70 iotDevice.setListen_service_ip("127.0.0.1"+":"+port+contextPath); 87 iotDevice.setListen_service_ip("127.0.0.1"+":"+port+contextPath);
@@ -79,12 +96,12 @@ public class BusinessDataUpdateService { @@ -79,12 +96,12 @@ public class BusinessDataUpdateService {
79 iotDevice.setDevice_life(olddevice.getDevice_life()); 96 iotDevice.setDevice_life(olddevice.getDevice_life());
80 iotDevice.setData_update_time(DateUtils.getNowTimeMilly()); 97 iotDevice.setData_update_time(DateUtils.getNowTimeMilly());
81 iotDevice.setName(olddevice.getName()); 98 iotDevice.setName(olddevice.getName());
82 - deviceService.updataDevice(iotDevice); 99 + serverDto.setIotDevice(iotDevice);
83 }else{ //终端 100 }else{ //终端
84 - IotTerminal iotTerminal = translateTerminal(type,key,olddevice,jsData,isOperLog,operateHisList,list); 101 + IotTerminal iotTerminal = translateTerminal(type,key,olddevice,jsData,isOperLog,serverDto);
85 logger.info("更新终端数据{}",iotTerminal); 102 logger.info("更新终端数据{}",iotTerminal);
86 iotTerminal.setData_update_time(DateUtils.getNowTimeMilly()); 103 iotTerminal.setData_update_time(DateUtils.getNowTimeMilly());
87 - deviceService.updataTerminal(iotTerminal,olddevice.getDevice_life()); 104 + serverDto.getIotTerminalList().add(iotTerminal);
88 } 105 }
89 } 106 }
90 } 107 }
@@ -95,17 +112,17 @@ public class BusinessDataUpdateService { @@ -95,17 +112,17 @@ public class BusinessDataUpdateService {
95 * @param type 112 * @param type
96 * @param olddevice 113 * @param olddevice
97 * @param jsData 114 * @param jsData
98 - * @param operateHisList 115 + * @param serverDto
99 * @return 116 * @return
100 */ 117 */
101 - private IotDevice translateDevice(Type type, IotDevice olddevice , JSONObject jsData,boolean isOperLog, List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list) 118 + private IotDevice translateDevice(Type type, IotDevice olddevice , JSONObject jsData,boolean isOperLog, ServerDto serverDto)
102 { 119 {
103 JSONObject summaryObjec = null; 120 JSONObject summaryObjec = null;
104 if(jsData.containsKey("summary") && null != jsData.get("summary") && jsData.get("summary") instanceof JSONObject) 121 if(jsData.containsKey("summary") && null != jsData.get("summary") && jsData.get("summary") instanceof JSONObject)
105 { 122 {
106 summaryObjec = jsData.getJSONObject("summary"); 123 summaryObjec = jsData.getJSONObject("summary");
107 //记录summary内容变更日志 124 //记录summary内容变更日志
108 - operateHisList.add(deviceLogService.newLogDeviceOperation(olddevice.getClient_id(),summaryObjec.toString(),olddevice.getSummary(),"主机本地summary状态更新",jsData.toJSONString())); 125 + serverDto.getLogDeviceOperationList().add(deviceLogService.newLogDeviceOperation(olddevice.getClient_id(),summaryObjec.toString(),olddevice.getSummary(),"主机本地summary状态更新",jsData.toJSONString()));
109 jsData.remove("summary"); 126 jsData.remove("summary");
110 } 127 }
111 IotDevice device = JSONObject.parseObject(JSONObject.toJSONString(jsData),IotDevice.class); 128 IotDevice device = JSONObject.parseObject(JSONObject.toJSONString(jsData),IotDevice.class);
@@ -115,7 +132,7 @@ public class BusinessDataUpdateService { @@ -115,7 +132,7 @@ public class BusinessDataUpdateService {
115 device.setSummary(summaryObjec.toString()); 132 device.setSummary(summaryObjec.toString());
116 } 133 }
117 134
118 - SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( olddevice.getClient_id(),olddevice.getMqtt_username(),jsData,"主机本地",isOperLog,operateHisList,list); 135 + SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( olddevice.getClient_id(),olddevice.getMqtt_username(),jsData,"主机本地",isOperLog,serverDto);
119 //更新数据 136 //更新数据
120 if(null != olddevice && ("ADD".equals(type.name())|| "READ".equals(type.name()))) 137 if(null != olddevice && ("ADD".equals(type.name())|| "READ".equals(type.name())))
121 { 138 {
@@ -139,30 +156,20 @@ public class BusinessDataUpdateService { @@ -139,30 +156,20 @@ public class BusinessDataUpdateService {
139 * @param key 156 * @param key
140 * @param olddevice 157 * @param olddevice
141 * @param jsData 158 * @param jsData
142 - * @param operateHisList 159 + * @param serverDto
143 * @return 160 * @return
144 */ 161 */
145 - private IotTerminal translateTerminal(Type type,String key, IotDevice olddevice , JSONObject jsData,boolean isOperLog, List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list) 162 + private IotTerminal translateTerminal(Type type,String key, IotDevice olddevice , JSONObject jsData,boolean isOperLog,ServerDto serverDto)
146 { 163 {
147 String id = olddevice.getClient_id()+"_"+key; 164 String id = olddevice.getClient_id()+"_"+key;
148 - SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( id,olddevice.getMqtt_username(),jsData,"终端本地",isOperLog,operateHisList,list); 165 + SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( id,olddevice.getMqtt_username(),jsData,"终端本地",isOperLog,serverDto);
149 IotTerminal terminal = new IotTerminal(); 166 IotTerminal terminal = new IotTerminal();
150 terminal.setId(id); 167 terminal.setId(id);
151 terminal.setDevice_id(olddevice.getClient_id()); 168 terminal.setDevice_id(olddevice.getClient_id());
152 terminal.setProduct_id(olddevice.getProduct_id()); 169 terminal.setProduct_id(olddevice.getProduct_id());
153 terminal.setMqtt_username(olddevice.getMqtt_username()); 170 terminal.setMqtt_username(olddevice.getMqtt_username());
154 //更新数据 171 //更新数据
155 - IotTerminal oldterminal = deviceService.getRedicTerminal(id);  
156 - if(null == oldterminal)  
157 - {  
158 - oldterminal = new IotTerminal();  
159 - oldterminal.setDevice_id(olddevice.getClient_id());  
160 - oldterminal.setId(id);  
161 - oldterminal.setMqtt_username(olddevice.getMqtt_username());  
162 - oldterminal.setName(olddevice.getMqtt_username()+"终端"+key);  
163 - oldterminal.setProduct_id(olddevice.getProduct_id());  
164 - deviceService.updataTerminal(oldterminal,olddevice.getDevice_life());  
165 - } 172 + IotTerminal oldterminal = cacheService.getIotTerminal(id);
166 if(null != oldterminal && ("ADD".equals(type.name())|| "READ".equals(type.name()))) 173 if(null != oldterminal && ("ADD".equals(type.name())|| "READ".equals(type.name())))
167 { 174 {
168 String str = oldterminal.getThings_model_value(); 175 String str = oldterminal.getThings_model_value();
1 package com.zhonglai.luhui.mqtt.comm.service; 1 package com.zhonglai.luhui.mqtt.comm.service;
2 2
3 3
  4 +import com.ruoyi.system.domain.IotDevice;
  5 +import com.ruoyi.system.domain.IotTerminal;
4 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 6 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
5 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 7 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
6 8
@@ -9,4 +11,6 @@ import com.zhonglai.luhui.mqtt.comm.factory.Topic; @@ -9,4 +11,6 @@ import com.zhonglai.luhui.mqtt.comm.factory.Topic;
9 */ 11 */
10 public interface CacheService { 12 public interface CacheService {
11 boolean updateCache(Topic topic, ServerDto dto); //返回是否需要持久化 13 boolean updateCache(Topic topic, ServerDto dto); //返回是否需要持久化
  14 + IotDevice getIotDevice(String id);
  15 + IotTerminal getIotTerminal(String id);
12 } 16 }
1 package com.zhonglai.luhui.mqtt.comm.service; 1 package com.zhonglai.luhui.mqtt.comm.service;
2 2
3 -import com.mysql.cj.x.protobuf.MysqlxDatatypes;  
4 import com.zhonglai.luhui.mqtt.comm.clien.ClienConnection; 3 import com.zhonglai.luhui.mqtt.comm.clien.ClienConnection;
5 import com.zhonglai.luhui.mqtt.comm.clien.impl.ClienConnectionImpl; 4 import com.zhonglai.luhui.mqtt.comm.clien.impl.ClienConnectionImpl;
6 -import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 5 +import com.zhonglai.luhui.mqtt.comm.dto.ApiClientRePlyDto;
  6 +import com.zhonglai.luhui.mqtt.comm.dto.TerminalClientRePlyDto;
7 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 7 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
8 import com.zhonglai.luhui.mqtt.comm.util.ByteUtil; 8 import com.zhonglai.luhui.mqtt.comm.util.ByteUtil;
9 import com.zhonglai.luhui.mqtt.dto.Message; 9 import com.zhonglai.luhui.mqtt.dto.Message;
@@ -91,34 +91,39 @@ public class ClienNoticeService { @@ -91,34 +91,39 @@ public class ClienNoticeService {
91 return clienConnectionMap.get(topic.generateClienKey()); 91 return clienConnectionMap.get(topic.generateClienKey());
92 } 92 }
93 93
94 - public void replySendMessage(Topic topic, ServerDto dto) 94 + /**
  95 + * 通知给api操作端
  96 + * @param topic
  97 + * @param apiClientRePlyDto
  98 + */
  99 + public void replySendMessage(Topic topic, ApiClientRePlyDto apiClientRePlyDto)
95 { 100 {
96 - log.info("开始通知{},数据:{}",topic,dto); 101 + log.info("开始通知{},数据:{}",topic,apiClientRePlyDto);
97 //判断有没有需要回复的客户端,如果有就回复 102 //判断有没有需要回复的客户端,如果有就回复
98 - if(dto.isReplyMessage()) 103 + ClienConnection clienConnection = getClienConnection(topic);
  104 + if(null != clienConnection)
99 { 105 {
100 - ClienConnection clienConnection = getClienConnection(topic);  
101 - if(null != clienConnection) 106 + synchronized(clienConnection)
102 { 107 {
103 - synchronized(clienConnection)  
104 - {  
105 - log.info("正在通知{},通知结果{}",topic,dto);  
106 - clienConnection.reply(dto.getServerAgreementContent());  
107 - } 108 + log.info("正在通知{},通知结果{}",topic,apiClientRePlyDto);
  109 + clienConnection.reply(apiClientRePlyDto);
108 } 110 }
109 } 111 }
110 log.info("结束通知{}",topic); 112 log.info("结束通知{}",topic);
111 } 113 }
112 114
113 - public void replyTerminalMessage(Topic topic, ServerDto dto) throws MqttException {  
114 - if(dto.isReplyMessage() && null != dto.getServerAgreementContent().getReplyCommdTopic(topic))  
115 - {  
116 - String tc = dto.getServerAgreementContent().getReplyCommdTopic(topic);  
117 - MqttMessage mqttMessage = new MqttMessage();  
118 - mqttMessage.setPayload(dto.getServerAgreementContent().getCommd());  
119 - log.info("回复终端{}的消息{}",tc,new String(mqttMessage.getPayload()));  
120 - terminalService.publish(dto.getServerAgreementContent().getReplyCommdTopic(topic),mqttMessage);  
121 - } 115 + /**
  116 + * 通知给下位机终端
  117 + * @param topic
  118 + * @param terminalClientRePlyDto
  119 + * @throws MqttException
  120 + */
  121 + public void replyTerminalMessage(Topic topic, TerminalClientRePlyDto terminalClientRePlyDto) throws MqttException {
  122 + String tc = terminalClientRePlyDto.getReplyCommdTopic(topic);
  123 + MqttMessage mqttMessage = new MqttMessage();
  124 + mqttMessage.setPayload(terminalClientRePlyDto.getCommd());
  125 + log.info("回复终端{}的消息{}",tc,new String(mqttMessage.getPayload()));
  126 + terminalService.publish(terminalClientRePlyDto.getReplyCommdTopic(topic),mqttMessage);
122 127
123 } 128 }
124 } 129 }
@@ -6,6 +6,7 @@ import com.ruoyi.system.domain.IotThingsModel; @@ -6,6 +6,7 @@ import com.ruoyi.system.domain.IotThingsModel;
6 import com.zhonglai.luhui.mqtt.comm.dao.BaseDao; 6 import com.zhonglai.luhui.mqtt.comm.dao.BaseDao;
7 import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData; 7 import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;
8 import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation; 8 import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;
  9 +import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
9 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelBase; 10 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelBase;
10 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelDataTypeEnum; 11 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelDataTypeEnum;
11 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelItemBase; 12 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelItemBase;
@@ -19,6 +20,7 @@ import org.slf4j.LoggerFactory; @@ -19,6 +20,7 @@ import org.slf4j.LoggerFactory;
19 import org.springframework.beans.factory.annotation.Autowired; 20 import org.springframework.beans.factory.annotation.Autowired;
20 import org.springframework.stereotype.Service; 21 import org.springframework.stereotype.Service;
21 22
  23 +import java.util.ArrayList;
22 import java.util.List; 24 import java.util.List;
23 25
24 /** 26 /**
@@ -39,26 +41,30 @@ public class DataModeAnalysisService { @@ -39,26 +41,30 @@ public class DataModeAnalysisService {
39 /** 41 /**
40 * 初始化物模型数据 42 * 初始化物模型数据
41 */ 43 */
42 - public void initDataThingsMode(String roleIds,String usernames) 44 + public void initDataThingsMode(List<String> roleIds,List<String> usernames)
43 { 45 {
44 - String sql = "SELECT a.*,b.mqtt_username mqtt_username FROM `mqtt_broker`.`iot_things_model` a LEFT JOIN `mqtt_broker`.`iot_product` b ON a.`product_id`=b.`id` WHERE a.del_flag=0 "; 46 + StringBuffer sql = new StringBuffer("SELECT a.*,b.mqtt_username mqtt_username FROM `mqtt_broker`.`iot_things_model` a LEFT JOIN `mqtt_broker`.`iot_product` b ON a.`product_id`=b.`id` WHERE a.del_flag=0 ");
45 if(StringUtils.isNotEmpty(roleIds)) 47 if(StringUtils.isNotEmpty(roleIds))
46 { 48 {
47 - sql += " AND b.`role_id` IN("+roleIds+")"; 49 + sql.append(" AND b.`role_id` IN(");
  50 + sql.append(StringUtils.join(roleIds,","));
  51 + sql.append(")");
48 } 52 }
49 53
50 if(StringUtils.isNotEmpty(usernames)) 54 if(StringUtils.isNotEmpty(usernames))
51 { 55 {
52 - sql += " AND b.`username` IN("+usernames+")"; 56 + sql.append(" AND b.`mqtt_username` IN('");
  57 + sql.append(StringUtils.join(usernames,"','"));
  58 + sql.append("')");
53 } 59 }
54 - List<IotThingsModel> list = baseDao.findBysql(sql, IotThingsModel.class); 60 + List<IotThingsModel> list = baseDao.findBysql(sql.toString(), IotThingsModel.class);
55 terminalDataThingsModeService.saveIotThingsModelToUser(list); 61 terminalDataThingsModeService.saveIotThingsModelToUser(list);
56 } 62 }
57 63
58 /** 64 /**
59 * 解析物模型数据 65 * 解析物模型数据
60 */ 66 */
61 - public SaveDataDto analysisThingsModelValue(String id,String userName ,JSONObject jsData,String controlModel,boolean isOperLog, List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list) 67 + public SaveDataDto analysisThingsModelValue(String id,String userName ,JSONObject jsData,String controlModel,boolean isOperLog, ServerDto serverDto)
62 { 68 {
63 if(null != jsData && jsData.size() != 0 ) 69 if(null != jsData && jsData.size() != 0 )
64 { 70 {
@@ -96,7 +102,7 @@ public class DataModeAnalysisService { @@ -96,7 +102,7 @@ public class DataModeAnalysisService {
96 102
97 ThingsModelItemBase thingsModelItemBase = (ThingsModelItemBase) thingsModelBase; 103 ThingsModelItemBase thingsModelItemBase = (ThingsModelItemBase) thingsModelBase;
98 //记录数据日志 104 //记录数据日志
99 - if(1==thingsModelItemBase.getIs_save_log() && null != list) 105 + if(1==thingsModelItemBase.getIs_save_log() && null != serverDto.getDeviceSensorDataList())
100 { 106 {
101 DeviceSensorData sensorData = new DeviceSensorData(); 107 DeviceSensorData sensorData = new DeviceSensorData();
102 sensorData.setDataType(key); 108 sensorData.setDataType(key);
@@ -104,13 +110,13 @@ public class DataModeAnalysisService { @@ -104,13 +110,13 @@ public class DataModeAnalysisService {
104 sensorData.setCreatTime(DateUtils.getNowTimeMilly()); 110 sensorData.setCreatTime(DateUtils.getNowTimeMilly());
105 sensorData.setDeviceModel(userName); 111 sensorData.setDeviceModel(userName);
106 sensorData.setDeviceInfoId(id); 112 sensorData.setDeviceInfoId(id);
107 - list.add(sensorData); 113 + serverDto.getDeviceSensorDataList().add(sensorData);
108 } 114 }
109 115
110 //记录操作日志 116 //记录操作日志
111 - if(isOperLog && null != operateHisList) 117 + if(isOperLog && null != serverDto.getLogDeviceOperationList())
112 { 118 {
113 - operateHisList.add(dviceLogService.newLogDeviceOperation(id,thingsModelBase.getSaveView(),null,controlModel+thingsModelItemBase.getName()+"为"+thingsModelBase.getView(),jsData.toString())); 119 + serverDto.getLogDeviceOperationList().add(dviceLogService.newLogDeviceOperation(id,thingsModelBase.getSaveView(),null,controlModel+thingsModelItemBase.getName()+"为"+thingsModelBase.getView(),jsData.toString()));
114 } 120 }
115 121
116 122
@@ -19,30 +19,6 @@ public abstract class DataPersistenceService { @@ -19,30 +19,6 @@ public abstract class DataPersistenceService {
19 public abstract void persistence(Topic topic, ServerDto serverDto); 19 public abstract void persistence(Topic topic, ServerDto serverDto);
20 20
21 /** 21 /**
22 - * 记录操作日志  
23 - * @param deviceOperationTypeEnum  
24 - * @param deviceNewState  
25 - */  
26 - public void logDeviceOperation(String deviceInfoId, DeviceOperationTypeEnum deviceOperationTypeEnum, String deviceNewState)  
27 - {  
28 - List<Object> operateHisList = new ArrayList<>();  
29 - //如果老的和新的不一致,记录日志  
30 - LogDeviceOperation operateHis = new LogDeviceOperation();  
31 - operateHis.setDeviceInfoId(deviceInfoId);  
32 - deviceOperationTypeEnum.setDeviceOperationLog(operateHis);  
33 - if(StringUtils.isNoneBlank(deviceNewState))  
34 - {  
35 - operateHis.setDeviceNewState(deviceNewState);  
36 - }  
37 - operateHis.setIsStateChange(1);  
38 - operateHis.setDeviceOperationTime(DateUtils.getNowTimeMilly());  
39 -  
40 - operateHisList.add(operateHis);  
41 - baseDao.insertList(operateHisList, TableGenerateSqlEnum.LogDeviceOperation.getNowTableName());  
42 -  
43 - }  
44 -  
45 - /**  
46 * 离线处理 22 * 离线处理
47 * @param imei 23 * @param imei
48 */ 24 */
1 package com.zhonglai.luhui.mqtt.comm.service; 1 package com.zhonglai.luhui.mqtt.comm.service;
2 2
3 -import com.zhonglai.luhui.mqtt.comm.config.RedisConfig;  
4 -import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService;  
5 import com.zhonglai.luhui.mqtt.service.db.DeviceService; 3 import com.zhonglai.luhui.mqtt.service.db.DeviceService;
6 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.data.redis.connection.Message; 5 import org.springframework.data.redis.connection.Message;
@@ -26,20 +24,20 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene @@ -26,20 +24,20 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
26 24
27 @Override 25 @Override
28 public void onMessage(Message message, byte[] pattern) { 26 public void onMessage(Message message, byte[] pattern) {
29 - String expiredKey = message.toString();  
30 -  
31 - String devicePath = deviceService.getRedicDeviceKeyPath();  
32 - String terminalPath = deviceService.getRedicTerminalKeyPath();  
33 - if(expiredKey.startsWith(devicePath)) //如果是主机  
34 - {  
35 - String imei = expiredKey.replace(devicePath,"").replace(":","");  
36 - dtaPersistenceService.offLine(imei);  
37 - }  
38 -  
39 - if(expiredKey.startsWith(terminalPath)) //如果是终端  
40 - {  
41 - String imei = expiredKey.replace(devicePath,"").replace(":","");  
42 - dtaPersistenceService.offLine(imei);  
43 - } 27 +// String expiredKey = message.toString();
  28 +//
  29 +// String devicePath = deviceService.getRedicDeviceKeyPath();
  30 +// String terminalPath = deviceService.getRedicTerminalKeyPath();
  31 +// if(expiredKey.startsWith(devicePath)) //如果是主机
  32 +// {
  33 +// String imei = expiredKey.replace(devicePath,"").replace(":","");
  34 +// dtaPersistenceService.offLine(imei);
  35 +// }
  36 +//
  37 +// if(expiredKey.startsWith(terminalPath)) //如果是终端
  38 +// {
  39 +// String imei = expiredKey.replace(devicePath,"").replace(":","");
  40 +// dtaPersistenceService.offLine(imei);
  41 +// }
44 } 42 }
45 } 43 }
@@ -17,6 +17,8 @@ import org.springframework.stereotype.Service; @@ -17,6 +17,8 @@ import org.springframework.stereotype.Service;
17 import javax.annotation.PostConstruct; 17 import javax.annotation.PostConstruct;
18 import java.nio.ByteBuffer; 18 import java.nio.ByteBuffer;
19 import java.nio.charset.Charset; 19 import java.nio.charset.Charset;
  20 +import java.util.ArrayList;
  21 +import java.util.List;
20 import java.util.concurrent.ExecutorService; 22 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.LinkedBlockingQueue; 23 import java.util.concurrent.LinkedBlockingQueue;
22 import java.util.concurrent.ThreadPoolExecutor; 24 import java.util.concurrent.ThreadPoolExecutor;
@@ -99,30 +101,22 @@ public class TerminalService { @@ -99,30 +101,22 @@ public class TerminalService {
99 101
100 private void initDataThingsMode() 102 private void initDataThingsMode()
101 { 103 {
102 - String roleids="";  
103 - String usernames=""; 104 + List<String> roleids=new ArrayList<>();
  105 + List<String> usernames= new ArrayList<>();
104 for(String topicstr:topics.split(",")) 106 for(String topicstr:topics.split(","))
105 { 107 {
106 Topic topic = new Topic(topicstr); 108 Topic topic = new Topic(topicstr);
107 if(null != topic) 109 if(null != topic)
108 { 110 {
109 String rild = topic.getRoleid(); 111 String rild = topic.getRoleid();
110 - if(StringUtils.isNoneBlank(rild) && !"+".equals(rild)) 112 + if(StringUtils.isNoneBlank(rild) && !"+".equals(rild) && !roleids.contains(rild))
111 { 113 {
112 - if(!"".equals(roleids))  
113 - {  
114 - roleids +=",";  
115 - }  
116 - roleids +=rild; 114 + roleids.add(rild) ;
117 } 115 }
118 String username = topic.getUsername(); 116 String username = topic.getUsername();
119 - if(StringUtils.isNoneBlank(username) && !"+".equals(username)) 117 + if(StringUtils.isNoneBlank(username) && !"+".equals(username) && !usernames.contains(username))
120 { 118 {
121 - if(!"".equals(usernames))  
122 - {  
123 - usernames +=",";  
124 - }  
125 - usernames +="'"+username+"'"; 119 + usernames.add(username);
126 } 120 }
127 } 121 }
128 } 122 }
@@ -30,148 +30,55 @@ import java.util.Map; @@ -30,148 +30,55 @@ import java.util.Map;
30 @RestController 30 @RestController
31 @RequestMapping("/device") 31 @RequestMapping("/device")
32 public class DeviceController { 32 public class DeviceController {
33 - @Autowired  
34 - private ClienNoticeService clienNoticeService;  
35 -  
36 - @Autowired  
37 - private TerminalDataThingsModeService terminalDataThingsModeService;  
38 -  
39 - private BaseDao baseDao = new BaseDao();  
40 33
41 @Autowired 34 @Autowired
42 private DeviceService deviceService ; 35 private DeviceService deviceService ;
  36 + @Autowired
  37 + private TerminalDataThingsModeService terminalDataThingsModeService;
43 38
44 @ApiOperation("控制发16进制指令") 39 @ApiOperation("控制发16进制指令")
45 @RequestMapping(value = "controlHex/{clienid}",method = RequestMethod.POST) 40 @RequestMapping(value = "controlHex/{clienid}",method = RequestMethod.POST)
46 public Message controlHex(@PathVariable String clienid, String data) throws MqttException, InterruptedException { 41 public Message controlHex(@PathVariable String clienid, String data) throws MqttException, InterruptedException {
47 -  
48 - Topic topic = getTopicFromDb(clienid);  
49 - if(null == topic)  
50 - {  
51 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");  
52 - }  
53 - topic.setTopicType("PUT");  
54 - topic.setMessageid(DateUtils.getNowTimeMilly()+"");  
55 -  
56 - MqttMessage mqttMessage = new MqttMessage();  
57 - byte[] bs = hexStringToByte(data.trim().toUpperCase());  
58 - mqttMessage.setPayload(bs);  
59 -  
60 - Message message = clienNoticeService.sendMessage(topic,mqttMessage);  
61 - return message; 42 + return deviceService.controlHex(clienid,data);
62 } 43 }
63 44
64 @ApiOperation("读") 45 @ApiOperation("读")
65 @RequestMapping(value = "read/{clienid}",method = RequestMethod.POST) 46 @RequestMapping(value = "read/{clienid}",method = RequestMethod.POST)
66 public Message read(@PathVariable String clienid,@RequestBody Map<String,Object> map) throws MqttException, InterruptedException { 47 public Message read(@PathVariable String clienid,@RequestBody Map<String,Object> map) throws MqttException, InterruptedException {
67 -  
68 - if(null == map || map.size() ==0)  
69 - {  
70 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"参数验证失败");  
71 - }  
72 -  
73 - Topic topic = getTopicFromDb(clienid);  
74 - if(null == topic)  
75 - {  
76 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");  
77 - }  
78 - topic.setTopicType("READ");  
79 - topic.setMessageid(DateUtils.getNowTimeMilly()+"");  
80 - MqttMessage mqttMessage = new MqttMessage();  
81 - mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());  
82 - Message message = clienNoticeService.sendMessage(topic,mqttMessage);  
83 - return message; 48 + return deviceService.read(clienid,map);
84 } 49 }
85 50
86 @ApiOperation("强行断开链接") 51 @ApiOperation("强行断开链接")
87 @RequestMapping(value = "closeSession/{clienid}",method = RequestMethod.POST) 52 @RequestMapping(value = "closeSession/{clienid}",method = RequestMethod.POST)
88 public Message closeSession(@PathVariable String clienid) throws MqttException, InterruptedException { 53 public Message closeSession(@PathVariable String clienid) throws MqttException, InterruptedException {
89 -  
90 - MqttMessage mqttMessage = new MqttMessage();  
91 - byte[] bs = hexStringToByte(clienid.trim().toUpperCase());  
92 - mqttMessage.setPayload(bs);  
93 -  
94 - clienNoticeService.sendMessage("CLOSE",mqttMessage);  
95 - return new Message(MessageCode.DEFAULT_SUCCESS_CODE,"端口请求已发送"); 54 + return deviceService.closeSession(clienid);
96 } 55 }
97 56
98 @ApiOperation("删除主机") 57 @ApiOperation("删除主机")
99 @Transactional 58 @Transactional
100 @RequestMapping(value = "delIotDevice/{client_id}",method = RequestMethod.POST) 59 @RequestMapping(value = "delIotDevice/{client_id}",method = RequestMethod.POST)
101 public Message delIotDevice(@PathVariable String client_id) throws MqttException, InterruptedException { 60 public Message delIotDevice(@PathVariable String client_id) throws MqttException, InterruptedException {
102 - closeSession(client_id); //强制下线  
103 - deviceService.deletRedisDevice(client_id);  
104 - return new Message(MessageCode.DEFAULT_SUCCESS_CODE); 61 + return deviceService.delIotDevice(client_id);
105 } 62 }
106 63
107 @ApiOperation("删除终端") 64 @ApiOperation("删除终端")
108 @Transactional 65 @Transactional
109 @RequestMapping(value = "delIotTerminal/{client_id}/{number}",method = RequestMethod.POST) 66 @RequestMapping(value = "delIotTerminal/{client_id}/{number}",method = RequestMethod.POST)
110 public Message delIotTerminal(@PathVariable String client_id,@PathVariable String number) throws MqttException, InterruptedException { 67 public Message delIotTerminal(@PathVariable String client_id,@PathVariable String number) throws MqttException, InterruptedException {
111 - closeSession(client_id); //强制下线  
112 - deviceService.deletRedisTerminal(client_id+"_"+number);  
113 - return new Message(MessageCode.DEFAULT_SUCCESS_CODE); 68 + return deviceService.delIotTerminal(client_id,number);
114 } 69 }
115 70
116 @ApiOperation("控制发json") 71 @ApiOperation("控制发json")
117 @RequestMapping(value = "control/{clienid}",method = RequestMethod.POST) 72 @RequestMapping(value = "control/{clienid}",method = RequestMethod.POST)
118 public Message control(@PathVariable String clienid,@RequestBody Map<String,Object> map) throws MqttException, InterruptedException { 73 public Message control(@PathVariable String clienid,@RequestBody Map<String,Object> map) throws MqttException, InterruptedException {
119 -  
120 - if(null == map || map.size() ==0)  
121 - {  
122 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"参数验证失败");  
123 - }  
124 -  
125 - Topic topic = getTopicFromDb(clienid);  
126 - if(null == topic)  
127 - {  
128 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");  
129 - }  
130 - topic.setTopicType("PUT");  
131 - topic.setMessageid(DateUtils.getNowTimeMilly()+"");  
132 -  
133 - for(String key:map.keySet())  
134 - {  
135 - Object sendMap = map.get(key);  
136 - JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(sendMap));  
137 - for(String skey:jsonObject.keySet())  
138 - {  
139 - IotThingsModel thingsModel = terminalDataThingsModeService.getIotThingsModel(topic.getUsername(),skey);  
140 - if(null == thingsModel) //没有配置的 都按字符串处理  
141 - {  
142 - thingsModel = new IotThingsModel();  
143 - thingsModel.setData_type(ThingsModelDataTypeEnum.STRING.name());  
144 - thingsModel.setIdentifier(key);  
145 - thingsModel.setModel_name(key);  
146 - thingsModel.setIs_top(0);  
147 - thingsModel.setIs_monitor(0);  
148 - thingsModel.setIs_save_log(0);  
149 - thingsModel.setIs_config(0);  
150 - JSONObject spes = new JSONObject();  
151 - spes.put("maxLength",255);  
152 - thingsModel.setSpecs(spes.toString());  
153 - }  
154 - String data_type = thingsModel.getData_type().toUpperCase();  
155 - Class<ThingsModelBase> aClass = Enum.valueOf(ThingsModelDataTypeEnum.class,data_type).getaClass();  
156 - ThingsModelBase thingsModelBase = JSON.parseObject(thingsModel.getSpecs(),aClass);  
157 - jsonObject.put(skey,thingsModelBase.getCmdView(jsonObject.get(skey)));  
158 - }  
159 -  
160 - map.put(key,jsonObject);  
161 - }  
162 -  
163 - MqttMessage mqttMessage = new MqttMessage();  
164 - mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());  
165 - Message message = clienNoticeService.sendMessage(topic,mqttMessage);  
166 - return message; 74 + return deviceService.control(clienid,map);
167 } 75 }
168 76
169 @ApiOperation("获取指定设备版本信息") 77 @ApiOperation("获取指定设备版本信息")
170 @RequestMapping(value = "getFirmwareVersion/{app_type}",method = RequestMethod.POST) 78 @RequestMapping(value = "getFirmwareVersion/{app_type}",method = RequestMethod.POST)
171 public Message getFirmwareVersion(@PathVariable String app_type) 79 public Message getFirmwareVersion(@PathVariable String app_type)
172 { 80 {
173 - List list = baseDao.findListBysql("SELECT md5str,upload_file_path uploadFilePath,version_number versionNumber,code FROM liu_yu_le.`app_file_upgrade` WHERE app_type='"+app_type+"' ORDER BY id DESC limit 5");  
174 - return new Message(MessageCode.DEFAULT_SUCCESS_CODE,list); 81 + return deviceService.getFirmwareVersion(app_type);
175 } 82 }
176 83
177 @ApiOperation("测试") 84 @ApiOperation("测试")
@@ -182,42 +89,4 @@ public class DeviceController { @@ -182,42 +89,4 @@ public class DeviceController {
182 return new Message(MessageCode.DEFAULT_SUCCESS_CODE,map); 89 return new Message(MessageCode.DEFAULT_SUCCESS_CODE,map);
183 } 90 }
184 91
185 - /**  
186 - * 通过数据获取发送消息的topic  
187 - * @param clienid  
188 - * @return  
189 - */  
190 - private Topic getTopicFromDb(String clienid)  
191 - {  
192 - JSONArray jsonArray = baseDao.findBysql("SELECT b.`role_id` roleid,b.`mqtt_username` username,a.`client_id` clientid,a.`payload_type` payloadtype FROM `iot_device` a LEFT JOIN `iot_product` b ON a.`product_id`=b.`id` WHERE client_id='"+clienid+"'");  
193 - if(null == jsonArray || jsonArray.size()==0 || null == jsonArray.getJSONObject(0).get("username"))  
194 - {  
195 - return null;  
196 - }  
197 - Topic topic = JSON.parseObject( jsonArray.getJSONObject(0).toJSONString(),Topic.class);  
198 - topic.setTopicType("PUT");  
199 - topic.setMessageid(DateUtils.getNowTimeMilly()+"");  
200 - return topic;  
201 - }  
202 - /**  
203 - * 把16进制字符串转换成字节数组  
204 - *  
205 - * @param hex  
206 - * @return  
207 - */  
208 - public static byte[] hexStringToByte(String hex) {  
209 - int len = (hex.length() / 2);  
210 - byte[] result = new byte[len];  
211 - char[] achar = hex.toCharArray();  
212 - for (int i = 0; i < len; i++) {  
213 - int pos = i * 2;  
214 - result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));  
215 - }  
216 - return result;  
217 - }  
218 - private static byte toByte(char c) {  
219 - byte b = (byte) "0123456789ABCDEF".indexOf(c);  
220 - return b;  
221 - }  
222 -  
223 } 92 }
  1 +package com.zhonglai.luhui.mqtt.dto;
  2 +
  3 +public enum ApiName {
  4 + controlHex,
  5 + read,
  6 + closeSession,
  7 + delIotDevice,
  8 + delIotTerminal,
  9 + control,
  10 + getFirmwareVersion,
  11 +}
  1 +package com.zhonglai.luhui.mqtt.dto;
  2 +
  3 +import com.zhonglai.luhui.mqtt.service.db.DeviceService;
  4 +import org.eclipse.paho.client.mqttv3.MqttException;
  5 +
  6 +/**
  7 + * 设备指令接口
  8 + */
  9 +public class DeviceCommandApi {
  10 + private ApiName apiName; //指令接口名称
  11 + private DeviceCommandApiParameter deviceCommandApiParameter; //参数
  12 +
  13 + public Message invokeApi(DeviceService deviceService) throws MqttException, InterruptedException {
  14 + switch (apiName)
  15 + {
  16 + case read:
  17 + return deviceService.read(deviceCommandApiParameter.getClient_id(),deviceCommandApiParameter.getMap());
  18 + case control:
  19 + return deviceService.control(deviceCommandApiParameter.getClient_id(), deviceCommandApiParameter.getMap());
  20 + case controlHex:
  21 + return deviceService.controlHex(deviceCommandApiParameter.getClient_id(),deviceCommandApiParameter.getData());
  22 + case closeSession:
  23 + return deviceService.closeSession(deviceCommandApiParameter.getClient_id());
  24 + case delIotDevice:
  25 + return deviceService.delIotDevice(deviceCommandApiParameter.getClient_id());
  26 + case delIotTerminal:
  27 + return deviceService.delIotTerminal(deviceCommandApiParameter.getClient_id(),deviceCommandApiParameter.getNumber());
  28 + case getFirmwareVersion:
  29 + return deviceService.getFirmwareVersion(deviceCommandApiParameter.getData());
  30 + default:
  31 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"接口不存在");
  32 + }
  33 +
  34 + }
  35 +
  36 + public ApiName getApiName() {
  37 + return apiName;
  38 + }
  39 +
  40 + public void setApiName(ApiName apiName) {
  41 + this.apiName = apiName;
  42 + }
  43 +
  44 + public DeviceCommandApiParameter getDeviceCommandApiParameter() {
  45 + return deviceCommandApiParameter;
  46 + }
  47 +
  48 + public void setDeviceCommandApiParameter(DeviceCommandApiParameter deviceCommandApiParameter) {
  49 + this.deviceCommandApiParameter = deviceCommandApiParameter;
  50 + }
  51 +}
  1 +package com.zhonglai.luhui.mqtt.dto;
  2 +
  3 +import java.util.Map;
  4 +
  5 +public class DeviceCommandApiParameter {
  6 + private String client_id;
  7 + private Map<String, Object> map;
  8 + private String data;
  9 + private String number;
  10 +
  11 + public String getClient_id() {
  12 + return client_id;
  13 + }
  14 +
  15 + public void setClient_id(String client_id) {
  16 + this.client_id = client_id;
  17 + }
  18 +
  19 + public Map<String, Object> getMap() {
  20 + return map;
  21 + }
  22 +
  23 + public void setMap(Map<String, Object> map) {
  24 + this.map = map;
  25 + }
  26 +
  27 + public String getData() {
  28 + return data;
  29 + }
  30 +
  31 + public void setData(String data) {
  32 + this.data = data;
  33 + }
  34 +
  35 + public String getNumber() {
  36 + return number;
  37 + }
  38 +
  39 + public void setNumber(String number) {
  40 + this.number = number;
  41 + }
  42 +}
1 package com.zhonglai.luhui.mqtt.dto.topic; 1 package com.zhonglai.luhui.mqtt.dto.topic;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;  
5 -import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;  
6 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent;  
7 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 4 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
8 -import lombok.Data;  
9 -import lombok.experimental.Accessors;  
10 5
11 -import java.util.ArrayList;  
12 -import java.util.List;  
13 -  
14 -@Data  
15 -@Accessors(chain = true)  
16 -public class AddPostDto implements ServerDto {  
17 - private List<LogDeviceOperation> operateHisList = new ArrayList<>();  
18 - private List<DeviceSensorData> list = new ArrayList<>(); 6 +public class AddPostDto extends ServerDto {
19 private JSONObject data; 7 private JSONObject data;
20 - @Override  
21 - public ServerAgreementContent getServerAgreementContent() {  
22 - return null;  
23 - }  
24 -  
25 - @Override  
26 - public boolean isReplyMessage() {  
27 - return false;  
28 - }  
29 8
30 - @Override  
31 - public List<DeviceSensorData> getDeviceSensorData() {  
32 - return list; 9 + public JSONObject getData() {
  10 + return data;
33 } 11 }
34 12
35 - @Override  
36 - public List<LogDeviceOperation> getOperationLog() {  
37 - return operateHisList; 13 + public void setData(JSONObject data) {
  14 + this.data = data;
38 } 15 }
39 } 16 }
1 package com.zhonglai.luhui.mqtt.dto.topic; 1 package com.zhonglai.luhui.mqtt.dto.topic;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;  
5 -import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;  
6 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent;  
7 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 4 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
8 -import lombok.Data;  
9 -import lombok.experimental.Accessors;  
10 5
11 -import java.util.ArrayList;  
12 -import java.util.List;  
13 -  
14 -@Data  
15 -@Accessors(chain = true)  
16 -public class AllPostDto implements ServerDto {  
17 - private List<LogDeviceOperation> operateHisList = new ArrayList<>();  
18 - private List<DeviceSensorData> list = new ArrayList<>(); 6 +public class AllPostDto extends ServerDto {
19 private JSONObject data; 7 private JSONObject data;
20 - @Override  
21 - public ServerAgreementContent getServerAgreementContent() {  
22 - return null;  
23 - }  
24 -  
25 - @Override  
26 - public boolean isReplyMessage() {  
27 - return false;  
28 - }  
29 8
30 - @Override  
31 - public List<DeviceSensorData> getDeviceSensorData() {  
32 - return list; 9 + public JSONObject getData() {
  10 + return data;
33 } 11 }
34 12
35 - @Override  
36 - public List<LogDeviceOperation> getOperationLog() {  
37 - return operateHisList; 13 + public void setData(JSONObject data) {
  14 + this.data = data;
38 } 15 }
39 } 16 }
1 -package com.zhonglai.luhui.mqtt.dto.topic;  
2 -  
3 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;  
4 -import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;  
5 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent;  
6 -import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;  
7 -import lombok.Data;  
8 -import lombok.experimental.Accessors;  
9 -  
10 -import java.util.List;  
11 -  
12 -@Data  
13 -@Accessors(chain = true)  
14 -public class DbDistributeDto implements ServerDto {  
15 - @Override  
16 - public ServerAgreementContent getServerAgreementContent() {  
17 - return null;  
18 - }  
19 -  
20 - @Override  
21 - public boolean isReplyMessage() {  
22 - return false;  
23 - }  
24 -  
25 - @Override  
26 - public List<DeviceSensorData> getDeviceSensorData() {  
27 - return null;  
28 - }  
29 -  
30 - @Override  
31 - public List<LogDeviceOperation> getOperationLog() {  
32 - return null;  
33 - }  
34 -}  
1 package com.zhonglai.luhui.mqtt.dto.topic; 1 package com.zhonglai.luhui.mqtt.dto.topic;
2 2
3 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;  
4 -import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;  
5 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent;  
6 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 3 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
7 -import lombok.Data;  
8 -import lombok.experimental.Accessors;  
9 4
10 -import java.util.List;  
11 -  
12 -@Data  
13 -@Accessors(chain = true)  
14 -public class GetDto implements ServerDto {  
15 - @Override  
16 - public ServerAgreementContent getServerAgreementContent() {  
17 - return null;  
18 - }  
19 -  
20 - @Override  
21 - public boolean isReplyMessage() {  
22 - return false;  
23 - }  
24 -  
25 - @Override  
26 - public List<DeviceSensorData> getDeviceSensorData() {  
27 - return null;  
28 - }  
29 -  
30 - @Override  
31 - public List<LogDeviceOperation> getOperationLog() {  
32 - return null;  
33 - } 5 +public class GetDto extends ServerDto {
34 } 6 }
1 package com.zhonglai.luhui.mqtt.dto.topic; 1 package com.zhonglai.luhui.mqtt.dto.topic;
2 2
3 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;  
4 -import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;  
5 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent;  
6 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 3 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
7 -import lombok.Data;  
8 -import lombok.experimental.Accessors;  
9 4
10 -import java.util.List;  
11 -  
12 -@Data  
13 -@Accessors(chain = true)  
14 -public class GetReqDto implements ServerDto {  
15 - @Override  
16 - public ServerAgreementContent getServerAgreementContent() {  
17 - return null;  
18 - }  
19 -  
20 - @Override  
21 - public boolean isReplyMessage() {  
22 - return false;  
23 - }  
24 -  
25 - @Override  
26 - public List<DeviceSensorData> getDeviceSensorData() {  
27 - return null;  
28 - }  
29 -  
30 - @Override  
31 - public List<LogDeviceOperation> getOperationLog() {  
32 - return null;  
33 - } 5 +public class GetReqDto extends ServerDto {
34 } 6 }
1 package com.zhonglai.luhui.mqtt.dto.topic; 1 package com.zhonglai.luhui.mqtt.dto.topic;
2 2
3 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;  
4 -import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;  
5 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent;  
6 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 3 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
7 -import lombok.Data;  
8 -import lombok.experimental.Accessors;  
9 4
10 -import java.util.List;  
11 -  
12 -@Data  
13 -@Accessors(chain = true)  
14 -public class OnlineDto implements ServerDto { 5 +public class OnlineDto extends ServerDto {
15 private Integer state; 6 private Integer state;
16 - @Override  
17 - public ServerAgreementContent getServerAgreementContent() {  
18 - return null;  
19 - }  
20 -  
21 - @Override  
22 - public boolean isReplyMessage() {  
23 - return false;  
24 - }  
25 7
26 - @Override  
27 - public List<DeviceSensorData> getDeviceSensorData() {  
28 - return null; 8 + public Integer getState() {
  9 + return state;
29 } 10 }
30 11
31 - @Override  
32 - public List<LogDeviceOperation> getOperationLog() {  
33 - return null; 12 + public void setState(Integer state) {
  13 + this.state = state;
34 } 14 }
35 } 15 }
1 package com.zhonglai.luhui.mqtt.dto.topic; 1 package com.zhonglai.luhui.mqtt.dto.topic;
2 2
3 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;  
4 -import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;  
5 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent;  
6 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 3 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
7 -import lombok.Data;  
8 -import lombok.experimental.Accessors;  
9 -  
10 -import java.util.List;  
11 4
12 /** 5 /**
13 * 服务器下发数据 6 * 服务器下发数据
14 */ 7 */
15 -@Data  
16 -@Accessors(chain = true)  
17 -public class PutDto implements ServerDto { 8 +public class PutDto extends ServerDto {
18 private Object data; 9 private Object data;
19 10
20 - @Override  
21 - public ServerAgreementContent getServerAgreementContent() {  
22 - return null;  
23 - }  
24 -  
25 - @Override  
26 - public boolean isReplyMessage() {  
27 - return false;  
28 - }  
29 -  
30 - @Override  
31 - public List<DeviceSensorData> getDeviceSensorData() {  
32 - return null; 11 + public Object getData() {
  12 + return data;
33 } 13 }
34 14
35 - @Override  
36 - public List<LogDeviceOperation> getOperationLog() {  
37 - return null; 15 + public void setData(Object data) {
  16 + this.data = data;
38 } 17 }
39 } 18 }
1 package com.zhonglai.luhui.mqtt.dto.topic; 1 package com.zhonglai.luhui.mqtt.dto.topic;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;  
5 -import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;  
6 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent;  
7 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 4 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
8 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 5 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
9 import com.zhonglai.luhui.mqtt.dto.Message; 6 import com.zhonglai.luhui.mqtt.dto.Message;
10 -import com.zhonglai.luhui.mqtt.dto.MessageCode;  
11 -import lombok.Data;  
12 -import lombok.experimental.Accessors;  
13 7
14 -import java.util.List;  
15 -  
16 -@Data  
17 -@Accessors(chain = true)  
18 -public class PutReqDto implements ServerDto { 8 +public class PutReqDto extends ServerDto {
19 private Integer code; 9 private Integer code;
20 private String data; 10 private String data;
21 private String messageid; 11 private String messageid;
22 12
23 - @Override  
24 - public ServerAgreementContent getServerAgreementContent() {  
25 - PutReqDto putReqDto = this;  
26 - return new ServerAgreementContent() {  
27 -  
28 - @Override  
29 - public byte[] getCommd() {  
30 - JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(putReqDto));  
31 - jsonObject.remove("messageid");  
32 - return jsonObject.toJSONString().getBytes();  
33 - } 13 + public Integer getCode() {
  14 + return code;
  15 + }
34 16
35 - @Override  
36 - public String getReplyCommdTopic(Topic topic) {  
37 - return null;  
38 - } 17 + public void setCode(Integer code) {
  18 + this.code = code;
  19 + }
39 20
40 - @Override  
41 - public void setReplyMessage(Message message) {  
42 - message.setData(data);  
43 - message.setCode(MessageCode.DEFAULT_SUCCESS_CODE);  
44 - message.setMessage("成功");  
45 - switch (code)  
46 - {  
47 - case 0:  
48 - message.setCode(MessageCode.DEFAULT_FAIL_CODE);  
49 - message.setMessage("失败");  
50 - break;  
51 - }  
52 - }  
53 - }; 21 + public String getData() {
  22 + return data;
54 } 23 }
55 24
56 - @Override  
57 - public boolean isReplyMessage() {  
58 - return true; 25 + public void setData(String data) {
  26 + this.data = data;
59 } 27 }
60 28
61 - @Override  
62 - public List<DeviceSensorData> getDeviceSensorData() {  
63 - return null; 29 + public String getMessageid() {
  30 + return messageid;
64 } 31 }
65 32
66 - @Override  
67 - public List<LogDeviceOperation> getOperationLog() {  
68 - return null; 33 + public void setMessageid(String messageid) {
  34 + this.messageid = messageid;
69 } 35 }
  36 +
70 } 37 }
1 package com.zhonglai.luhui.mqtt.dto.topic; 1 package com.zhonglai.luhui.mqtt.dto.topic;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;  
5 -import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;  
6 -import com.zhonglai.luhui.mqtt.comm.dto.ServerAgreementContent;  
7 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 4 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
8 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 5 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
9 import com.zhonglai.luhui.mqtt.dto.Message; 6 import com.zhonglai.luhui.mqtt.dto.Message;
10 import com.zhonglai.luhui.mqtt.dto.MessageCode; 7 import com.zhonglai.luhui.mqtt.dto.MessageCode;
11 -import lombok.Data;  
12 -import lombok.experimental.Accessors;  
13 8
14 -import java.util.ArrayList;  
15 import java.util.HashMap; 9 import java.util.HashMap;
16 -import java.util.List;  
17 10
18 -@Data  
19 -@Accessors(chain = true)  
20 -public class ReadReqDto implements ServerDto { 11 +public class ReadReqDto extends ServerDto {
21 private Integer code; 12 private Integer code;
22 private JSONObject data; 13 private JSONObject data;
23 private String messageid; 14 private String messageid;
24 - private List<LogDeviceOperation> operateHisList = new ArrayList<>();  
25 - private List<DeviceSensorData> list = new ArrayList<>();  
26 - @Override  
27 - public ServerAgreementContent getServerAgreementContent() {  
28 - ReadReqDto readReqDto = this;  
29 - return new ServerAgreementContent() {  
30 15
31 - @Override  
32 - public byte[] getCommd() {  
33 - JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(readReqDto));  
34 - jsonObject.remove("messageid");  
35 - return jsonObject.toJSONString().getBytes();  
36 - } 16 + public Integer getCode() {
  17 + return code;
  18 + }
37 19
38 - @Override  
39 - public String getReplyCommdTopic(Topic topic) {  
40 - return null;  
41 - } 20 + public void setCode(Integer code) {
  21 + this.code = code;
  22 + }
42 23
43 - @Override  
44 - public void setReplyMessage(Message message) {  
45 - if(null != readReqDto.data)  
46 - {  
47 - message.setData(JSONObject.parseObject(readReqDto.data.toJSONString(), HashMap.class));  
48 - }  
49 - message.setCode(MessageCode.DEFAULT_SUCCESS_CODE);  
50 - message.setMessage("成功");  
51 - switch (code)  
52 - {  
53 - case 0:  
54 - message.setCode(MessageCode.DEFAULT_FAIL_CODE);  
55 - message.setMessage("失败");  
56 - break;  
57 - }  
58 - }  
59 - }; 24 + public JSONObject getData() {
  25 + return data;
60 } 26 }
61 27
62 - @Override  
63 - public boolean isReplyMessage() {  
64 - return true; 28 + public void setData(JSONObject data) {
  29 + this.data = data;
65 } 30 }
66 31
67 - @Override  
68 - public List<DeviceSensorData> getDeviceSensorData() {  
69 - return null; 32 + public String getMessageid() {
  33 + return messageid;
70 } 34 }
71 35
72 - @Override  
73 - public List<LogDeviceOperation> getOperationLog() {  
74 - return null; 36 + public void setMessageid(String messageid) {
  37 + this.messageid = messageid;
75 } 38 }
  39 +
76 } 40 }
1 package com.zhonglai.luhui.mqtt.service; 1 package com.zhonglai.luhui.mqtt.service;
2 2
  3 +import com.alibaba.fastjson.JSONObject;
  4 +import com.ruoyi.system.domain.IotDevice;
  5 +import com.ruoyi.system.domain.IotTerminal;
  6 +import com.zhonglai.luhui.mqtt.comm.config.RedisConfig;
  7 +import com.zhonglai.luhui.mqtt.comm.dao.BaseDao;
3 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 8 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
4 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 9 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
5 import com.zhonglai.luhui.mqtt.comm.service.CacheService; 10 import com.zhonglai.luhui.mqtt.comm.service.CacheService;
6 -import com.zhonglai.luhui.mqtt.dto.topic.PutReqDto; 11 +import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService;
  12 +import com.zhonglai.luhui.mqtt.comm.util.DateUtils;
  13 +import com.zhonglai.luhui.mqtt.service.redis.RedisDeleteListener;
  14 +import com.zhonglai.luhui.mqtt.service.redis.RedisExpiredListener;
  15 +import org.slf4j.Logger;
  16 +import org.slf4j.LoggerFactory;
  17 +import org.springframework.beans.factory.annotation.Autowired;
  18 +import org.springframework.context.annotation.Bean;
  19 +import org.springframework.data.redis.connection.RedisConnection;
  20 +import org.springframework.data.redis.connection.RedisConnectionFactory;
  21 +import org.springframework.data.redis.listener.RedisMessageListenerContainer;
7 import org.springframework.stereotype.Service; 22 import org.springframework.stereotype.Service;
  23 +import org.springframework.util.StringUtils;
  24 +
  25 +import java.util.List;
  26 +import java.util.Map;
  27 +import java.util.Properties;
  28 +import java.util.Set;
8 29
9 @Service 30 @Service
10 public class CacheServiceImpl implements CacheService { 31 public class CacheServiceImpl implements CacheService {
  32 + private static final Logger log = LoggerFactory.getLogger(CacheServiceImpl.class);
  33 +
  34 + @Autowired
  35 + private RedisService redisService ;
  36 +
  37 + private BaseDao baseDao = new BaseDao();
  38 +
11 @Override 39 @Override
12 public boolean updateCache(Topic topic, ServerDto serverDto) { 40 public boolean updateCache(Topic topic, ServerDto serverDto) {
  41 + IotDevice iotDevice = serverDto.getIotDevice();
  42 + if(null == iotDevice)
  43 + {
  44 + return false;
  45 + }
  46 + setIotDeviceToRedis(iotDevice);
  47 + log.info("{} 缓存更新 {}",topic,iotDevice);
  48 +
  49 + List<IotTerminal> list = serverDto.getIotTerminalList();
  50 + if(null != list && list.size() != 0 )
  51 + {
  52 + for (IotTerminal iotTerminal:list)
  53 + {
  54 + setIotTerminalToRedis(iotTerminal);
  55 + }
  56 + }
  57 + log.info("{} 缓存更新 {}",topic,list);
13 return true; 58 return true;
14 } 59 }
  60 +
  61 + @Override
  62 + public IotDevice getIotDevice(String id) {
  63 + IotDevice deviceHost = getIotDeviceFromRedis(id);
  64 + if(null == deviceHost)
  65 + {
  66 + deviceHost = (IotDevice) baseDao.get(IotDevice.class,id);
  67 + if(null == deviceHost)
  68 + {
  69 + return null;
  70 + }
  71 + }
  72 + return deviceHost;
  73 + }
  74 +
  75 + @Override
  76 + public IotTerminal getIotTerminal(String id) {
  77 + IotTerminal iotTerminal = getIotTerminalFromRedis(id);
  78 + if(null == iotTerminal)
  79 + {
  80 + iotTerminal = (IotTerminal) baseDao.get(IotTerminal.class,id);
  81 + if(null == iotTerminal)
  82 + {
  83 + String imei = id.split("_")[0];
  84 + IotDevice iotDevice = getIotDevice(id);
  85 + if(null == iotDevice)
  86 + {
  87 + return null;
  88 + }
  89 + int time = DateUtils.getNowTimeMilly();
  90 + iotTerminal = new IotTerminal();
  91 + iotTerminal.setId(id);
  92 + iotTerminal.setDevice_id(imei);
  93 + iotTerminal.setSensor_number(id.replace(imei+"_",""));
  94 + iotTerminal.setName(iotDevice.getMqtt_username()+"设备的第"+iotTerminal.getSensor_number()+"号终端");
  95 + iotTerminal.setUpdate_time(time);
  96 + iotTerminal.setProduct_id(iotDevice.getProduct_id());
  97 + iotTerminal.setMqtt_username(iotDevice.getMqtt_username());
  98 + iotTerminal.setData_update_time(time);
  99 + iotTerminal.setOnline(3);
  100 + iotTerminal.setCreate_time(time);
  101 + baseDao.insert(iotTerminal);
  102 + }
  103 + }
  104 + return iotTerminal;
  105 + }
  106 +
  107 + /**
  108 + * 获取主机
  109 + * @param id
  110 + * @return
  111 + */
  112 + public IotDevice getIotDeviceFromRedis(String id)
  113 + {
  114 + String key =getRedicDeviceKey(id);
  115 + if(redisService.hasKey(key))
  116 + {
  117 + Map<Object, Object> map = redisService.hmget(key);
  118 + IotDevice iotDevice = JSONObject.parseObject(JSONObject.toJSONString(map),IotDevice.class);
  119 + return iotDevice;
  120 + }
  121 + return null;
  122 + }
  123 +
  124 + /**
  125 + * 获取终端
  126 + * @param id
  127 + * @return
  128 + */
  129 + public IotTerminal getIotTerminalFromRedis(String id)
  130 + {
  131 + String key =getRedicTerminalKey(id);
  132 + if(redisService.hasKey(key))
  133 + {
  134 + Map<Object, Object> map = redisService.hmget(key);
  135 + IotTerminal iotTerminal = JSONObject.parseObject(JSONObject.toJSONString(map),IotTerminal.class);
  136 + return iotTerminal;
  137 + }
  138 + return null;
  139 + }
  140 +
  141 + /**
  142 + * 设置缓存主机
  143 + * @param iotDevice
  144 + */
  145 + private void setIotDeviceToRedis(IotDevice iotDevice)
  146 + {
  147 + redisService.hmset(getRedicDeviceKey(iotDevice.getClient_id()),iotDevice);
  148 + }
  149 +
  150 + /**
  151 + * 设置缓存终端
  152 + * @param iotTerminal
  153 + */
  154 + private void setIotTerminalToRedis(IotTerminal iotTerminal)
  155 + {
  156 + redisService.hmset(getRedicTerminalKey(iotTerminal.getId()),iotTerminal);
  157 + }
  158 +
  159 + /**
  160 + * 删除缓存主机
  161 + * @param client_id
  162 + */
  163 + public void deletRedisDevice(String client_id)
  164 + {
  165 + Set<String> keys = getRedicTerminalFromClientId(client_id);
  166 + if(null != keys && keys.size() != 0)
  167 + {
  168 + redisService.del(keys.toArray(new String[keys.size()]));
  169 + }
  170 + }
  171 +
  172 + /**
  173 + * 删除缓存终端
  174 + * @param client_ids
  175 + */
  176 + public void deletRedisTerminal(String... client_ids)
  177 + {
  178 + String[] keys = new String[client_ids.length];
  179 + for (int i=0;i<client_ids.length;i++)
  180 + {
  181 + keys[i] = getRedicTerminalKey(client_ids[i]);
  182 + }
  183 + redisService.del(keys);
  184 + }
  185 +
  186 + /**
  187 + * 获取缓存主机key
  188 + * @param client_id
  189 + * @return
  190 + */
  191 + private String getRedicDeviceKey(String client_id)
  192 + {
  193 + return getRedicDeviceKeyPath()+client_id;
  194 + }
  195 +
  196 + /**
  197 + * 终端key集合规则
  198 + * @param client_id
  199 + * @return
  200 + */
  201 + public Set<String> getRedicTerminalFromClientId(String client_id)
  202 + {
  203 + Set<String> keys = redisService.keys(RedisConfig.FIELD+RedisConfig.TERMINAL+client_id+"*");
  204 + return keys;
  205 + }
  206 +
  207 + /**
  208 + * 主机kry路径
  209 + * @return
  210 + */
  211 + private String getRedicDeviceKeyPath()
  212 + {
  213 + return RedisConfig.FIELD+RedisConfig.DEVICE;
  214 + }
  215 +
  216 + /**
  217 + * 终端key
  218 + * @param terminal_id
  219 + * @return
  220 + */
  221 + private String getRedicTerminalKey(String terminal_id)
  222 + {
  223 + return getRedicTerminalKeyPath()+terminal_id;
  224 + }
  225 +
  226 + /**
  227 + * 终端key路径
  228 + * @return
  229 + */
  230 + private String getRedicTerminalKeyPath()
  231 + {
  232 + return RedisConfig.FIELD+RedisConfig.TERMINAL;
  233 + }
  234 +
  235 + private String keyspaceNotificationsConfigParameter = "KEA";
  236 +
  237 + @Autowired
  238 + private RedisDeleteListener redisDeleteListener ;
  239 + @Autowired
  240 + private RedisExpiredListener redisExpiredListener ;
  241 + @Bean
  242 + RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
  243 + RedisConnection connection = connectionFactory.getConnection();
  244 + Properties config = connection.info("notify-keyspace-events");
  245 +
  246 + if (!StringUtils.hasText(config.getProperty("notify-keyspace-events"))) {
  247 + connection.setConfig("notify-keyspace-events", keyspaceNotificationsConfigParameter);
  248 + }
  249 + RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  250 + container.setConnectionFactory(connectionFactory);
  251 + //监听所有key的删除事件
  252 + container.addMessageListener(redisDeleteListener,redisDeleteListener.getTopic());
  253 + //监听所有key的过期事件
  254 + container.addMessageListener(redisExpiredListener,redisExpiredListener.getTopic());
  255 + return container;
  256 + }
15 } 257 }
1 package com.zhonglai.luhui.mqtt.service; 1 package com.zhonglai.luhui.mqtt.service;
2 2
  3 +import com.ruoyi.system.domain.IotDevice;
  4 +import com.ruoyi.system.domain.IotTerminal;
3 import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData; 5 import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;
4 import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation; 6 import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;
5 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 7 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
@@ -23,20 +25,38 @@ public class DataPersistenceServiceImpl extends DataPersistenceService { @@ -23,20 +25,38 @@ public class DataPersistenceServiceImpl extends DataPersistenceService {
23 private DeviceLogService dviceLogService; 25 private DeviceLogService dviceLogService;
24 @Override 26 @Override
25 public void persistence(Topic topic, ServerDto serverDto) { 27 public void persistence(Topic topic, ServerDto serverDto) {
  28 + IotDevice iotDevice = serverDto.getIotDevice();
  29 + if(null == iotDevice)
  30 + {
  31 + return ;
  32 + }
  33 + log.info("更新网关数据{}",iotDevice);
  34 + baseDao.update(iotDevice);
26 35
  36 + List<IotTerminal> list = serverDto.getIotTerminalList();
  37 + if(null != list && list.size() != 0 )
  38 + {
  39 + for (IotTerminal iotTerminal:list)
  40 + {
  41 + log.info("更新终端数据{}",iotTerminal);
  42 + baseDao.update(iotTerminal);
  43 + }
  44 + }
27 //曲线数据入库 45 //曲线数据入库
28 - List<DeviceSensorData> dsdList = serverDto.getDeviceSensorData(); 46 + List<DeviceSensorData> dsdList = serverDto.getDeviceSensorDataList();
29 if(null != dsdList && dsdList.size() != 0) 47 if(null != dsdList && dsdList.size() != 0)
30 { 48 {
31 dviceLogService.saveDeviceSensorDataLog(dsdList); 49 dviceLogService.saveDeviceSensorDataLog(dsdList);
32 } 50 }
33 51
34 //日志入库 52 //日志入库
35 - List<LogDeviceOperation> doList = serverDto.getOperationLog(); 53 + List<LogDeviceOperation> doList = serverDto.getLogDeviceOperationList();
36 if(null != doList && doList.size() != 0) 54 if(null != doList && doList.size() != 0)
37 { 55 {
38 dviceLogService.saveOperationLog(doList); 56 dviceLogService.saveOperationLog(doList);
39 } 57 }
  58 +
  59 +
40 } 60 }
41 61
42 @Override 62 @Override
1 package com.zhonglai.luhui.mqtt.service.db; 1 package com.zhonglai.luhui.mqtt.service.db;
2 2
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.alibaba.fastjson.JSONArray;
3 import com.alibaba.fastjson.JSONObject; 5 import com.alibaba.fastjson.JSONObject;
4 import com.ruoyi.system.domain.IotDevice; 6 import com.ruoyi.system.domain.IotDevice;
5 import com.ruoyi.system.domain.IotTerminal; 7 import com.ruoyi.system.domain.IotTerminal;
  8 +import com.ruoyi.system.domain.IotThingsModel;
6 import com.zhonglai.luhui.mqtt.comm.config.RedisConfig; 9 import com.zhonglai.luhui.mqtt.comm.config.RedisConfig;
7 import com.zhonglai.luhui.mqtt.comm.dao.BaseDao; 10 import com.zhonglai.luhui.mqtt.comm.dao.BaseDao;
  11 +import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelBase;
  12 +import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelDataTypeEnum;
  13 +import com.zhonglai.luhui.mqtt.comm.factory.Topic;
  14 +import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService;
8 import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService; 15 import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService;
  16 +import com.zhonglai.luhui.mqtt.comm.util.DateUtils;
  17 +import com.zhonglai.luhui.mqtt.dto.Message;
  18 +import com.zhonglai.luhui.mqtt.dto.MessageCode;
  19 +import com.zhonglai.luhui.mqtt.service.CacheServiceImpl;
  20 +import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService;
9 import org.apache.commons.lang3.StringUtils; 21 import org.apache.commons.lang3.StringUtils;
  22 +import org.eclipse.paho.client.mqttv3.MqttException;
  23 +import org.eclipse.paho.client.mqttv3.MqttMessage;
10 import org.springframework.beans.factory.annotation.Autowired; 24 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.stereotype.Service; 25 import org.springframework.stereotype.Service;
12 26
  27 +import java.util.Arrays;
13 import java.util.List; 28 import java.util.List;
  29 +import java.util.Map;
14 import java.util.Set; 30 import java.util.Set;
15 31
16 @Service 32 @Service
17 public class DeviceService { 33 public class DeviceService {
  34 +
  35 + @Autowired
  36 + private ClienNoticeService clienNoticeService;
  37 +
18 @Autowired 38 @Autowired
19 - private RedisService redisService ; 39 + private TerminalDataThingsModeService terminalDataThingsModeService;
  40 +
  41 + @Autowired
  42 + private CacheServiceImpl cacheServiceImpl;
  43 +
20 private BaseDao baseDao = new BaseDao(); 44 private BaseDao baseDao = new BaseDao();
21 45
22 /** 46 /**
@@ -51,146 +75,251 @@ public class DeviceService { @@ -51,146 +75,251 @@ public class DeviceService {
51 75
52 76
53 /** 77 /**
54 - * 获取缓存网关信息  
55 - * @param id 78 + * 增量更新数据
  79 + * @param oldstr
  80 + * @param saveJson
56 * @return 81 * @return
57 */ 82 */
58 - public IotDevice getRedicDevice(String id) 83 + public JSONObject getNewAdddate(String oldstr, JSONObject saveJson)
59 { 84 {
60 - Object object = redisService.get(getRedicDeviceKey(id));  
61 - if(null != object) 85 + JSONObject oldjs = new JSONObject();
  86 + if(StringUtils.isNoneBlank(oldstr))
  87 + {
  88 + oldjs = JSONObject.parseObject(oldstr);
  89 + }
  90 + for (String sk:saveJson.keySet())
62 { 91 {
63 - return (IotDevice)object;  
64 - }else{  
65 - IotDevice iotDevice = getDeviceById(id);  
66 - setRedicDevice(iotDevice);  
67 - return iotDevice; 92 + oldjs.put(sk,saveJson.get(sk));
68 } 93 }
  94 + return oldjs;
69 } 95 }
70 96
71 - public void updataDevice(IotDevice iotDevice) 97 +
  98 +
  99 + public void deviceOffLine(String clientId)
72 { 100 {
73 - setRedicDevice(iotDevice); 101 + cacheServiceImpl.deletRedisDevice(clientId);
  102 + IotDevice iotDevice = new IotDevice();
  103 + iotDevice.setClient_id(clientId);
  104 + iotDevice.setStatus(4);
74 baseDao.update(iotDevice,"client_id"); 105 baseDao.update(iotDevice,"client_id");
  106 +
  107 + Set<String> keys = cacheServiceImpl.getRedicTerminalFromClientId(clientId);
  108 + if(null != keys && keys.size() != 0)
  109 + {
  110 + terminalOffLine(keys.toArray(new String[keys.size()]));
  111 + }
  112 + }
  113 +
  114 + public void terminalOffLine(String... terminalIds)
  115 + {
  116 + baseDao.updateBySql("update iot_terminal set online=0 where id in(?)",Arrays.asList(terminalIds));
  117 + cacheServiceImpl.deletRedisTerminal(terminalIds);
75 } 118 }
76 119
77 /** 120 /**
78 - * 设置缓存网关信息  
79 - * @param device 121 + * 控制发16进制指令
  122 + * @param clienid
  123 + * @param data
80 * @return 124 * @return
  125 + * @throws MqttException
  126 + * @throws InterruptedException
81 */ 127 */
82 - private boolean setRedicDevice(IotDevice device)  
83 - {  
84 - System.out.println("更新 "+device.getClient_id()+" 缓存,生命周期为 "+device.getDevice_life());  
85 - return redisService.setexDevice(getRedicDeviceKey(device.getClient_id()),device.getDevice_life(),device);  
86 - } 128 + public Message controlHex(String clienid, String data) throws MqttException, InterruptedException {
87 129
88 - public String getRedicDeviceKey(String client_id)  
89 - {  
90 - return getRedicDeviceKeyPath()+client_id;  
91 - } 130 + Topic topic = getTopicFromDb(clienid);
  131 + if(null == topic)
  132 + {
  133 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");
  134 + }
  135 + topic.setTopicType("PUT");
  136 + topic.setMessageid(DateUtils.getNowTimeMilly()+"");
92 137
93 - public String getRedicTerminalFromClientId(String client_id)  
94 - {  
95 - return RedisConfig.FIELD+"*:"+client_id+"*";  
96 - } 138 + MqttMessage mqttMessage = new MqttMessage();
  139 + byte[] bs = hexStringToByte(data.trim().toUpperCase());
  140 + mqttMessage.setPayload(bs);
97 141
98 - public String getRedicDeviceKeyPath()  
99 - {  
100 - return RedisConfig.FIELD+RedisConfig.DEVICE; 142 + Message message = clienNoticeService.sendMessage(topic,mqttMessage);
  143 + return message;
101 } 144 }
102 145
103 /** 146 /**
104 - * 获取缓存终端信息  
105 - * @param id 147 + * 读
  148 + * @param clienid
  149 + * @param map
106 * @return 150 * @return
  151 + * @throws MqttException
  152 + * @throws InterruptedException
107 */ 153 */
108 - public IotTerminal getRedicTerminal(String id)  
109 - {  
110 - Object object = redisService.get(getRedicTerminalKey(id));  
111 - if(null == object) 154 + public Message read(String clienid,Map<String,Object> map) throws MqttException, InterruptedException {
  155 +
  156 + if(null == map || map.size() ==0)
112 { 157 {
113 - IotTerminal terminal = getTerminalById(id); 158 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"参数验证失败");
  159 + }
114 160
115 - if(null == terminal)  
116 - {  
117 - return null;  
118 - }else{  
119 - return terminal;  
120 - } 161 + Topic topic = getTopicFromDb(clienid);
  162 + if(null == topic)
  163 + {
  164 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");
121 } 165 }
122 - return (IotTerminal)object; 166 + topic.setTopicType("READ");
  167 + topic.setMessageid(DateUtils.getNowTimeMilly()+"");
  168 + MqttMessage mqttMessage = new MqttMessage();
  169 + mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());
  170 + Message message = clienNoticeService.sendMessage(topic,mqttMessage);
  171 + return message;
123 } 172 }
  173 +
124 /** 174 /**
125 - * 设置缓存终端信息  
126 - * @param terminal 175 + * 强行断开链接
  176 + * @param clienid
127 * @return 177 * @return
  178 + * @throws MqttException
  179 + * @throws InterruptedException
128 */ 180 */
129 - private boolean setRedicTerminal(IotTerminal terminal,long device_life)  
130 - {  
131 - return redisService.setexDevice(getRedicTerminalKey(terminal.getId()),device_life,terminal);  
132 - } 181 + public Message closeSession(String clienid) throws MqttException, InterruptedException {
133 182
134 - public String getRedicTerminalKey(String terminal_id)  
135 - {  
136 - return getRedicTerminalKeyPath()+terminal_id; 183 + MqttMessage mqttMessage = new MqttMessage();
  184 + byte[] bs = hexStringToByte(clienid.trim().toUpperCase());
  185 + mqttMessage.setPayload(bs);
  186 +
  187 + clienNoticeService.sendMessage("CLOSE",mqttMessage);
  188 + return new Message(MessageCode.DEFAULT_SUCCESS_CODE,"端口请求已发送");
137 } 189 }
138 190
139 - public String getRedicTerminalKeyPath()  
140 - {  
141 - return RedisConfig.FIELD+RedisConfig.TERMINAL; 191 + /**
  192 + * 删除主机
  193 + * @param client_id
  194 + * @return
  195 + * @throws MqttException
  196 + * @throws InterruptedException
  197 + */
  198 + public Message delIotDevice(String client_id) throws MqttException, InterruptedException {
  199 + closeSession(client_id); //强制下线
  200 + cacheServiceImpl.deletRedisDevice(client_id);
  201 + return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
142 } 202 }
143 203
144 - public void updataTerminal(IotTerminal terminal,long device_life)  
145 - {  
146 - setRedicTerminal(terminal,device_life);  
147 - baseDao.saveOrUpdateObject(terminal); 204 + /**
  205 + * 删除终端
  206 + * @param client_id
  207 + * @param number
  208 + * @return
  209 + * @throws MqttException
  210 + * @throws InterruptedException
  211 + */
  212 + public Message delIotTerminal(String client_id,String number) throws MqttException, InterruptedException {
  213 + closeSession(client_id); //强制下线
  214 + cacheServiceImpl.deletRedisTerminal(client_id+"_"+number);
  215 + return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
148 } 216 }
149 217
150 /** 218 /**
151 - * 增量更新数据  
152 - * @param oldstr  
153 - * @param saveJson 219 + * 控制发json
  220 + * @param clienid
  221 + * @param map
154 * @return 222 * @return
  223 + * @throws MqttException
  224 + * @throws InterruptedException
155 */ 225 */
156 - public JSONObject getNewAdddate(String oldstr, JSONObject saveJson)  
157 - {  
158 - JSONObject oldjs = new JSONObject();  
159 - if(StringUtils.isNoneBlank(oldstr)) 226 + public Message control(String clienid,Map<String,Object> map) throws MqttException, InterruptedException {
  227 +
  228 + if(null == map || map.size() ==0)
160 { 229 {
161 - oldjs = JSONObject.parseObject(oldstr); 230 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"参数验证失败");
162 } 231 }
163 - for (String sk:saveJson.keySet()) 232 +
  233 + Topic topic = getTopicFromDb(clienid);
  234 + if(null == topic)
164 { 235 {
165 - oldjs.put(sk,saveJson.get(sk)); 236 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");
166 } 237 }
167 - return oldjs; 238 + topic.setTopicType("PUT");
  239 + topic.setMessageid(DateUtils.getNowTimeMilly()+"");
  240 +
  241 + for(String key:map.keySet())
  242 + {
  243 + Object sendMap = map.get(key);
  244 + JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(sendMap));
  245 + for(String skey:jsonObject.keySet())
  246 + {
  247 + IotThingsModel thingsModel = terminalDataThingsModeService.getIotThingsModel(topic.getUsername(),skey);
  248 + if(null == thingsModel) //没有配置的 都按字符串处理
  249 + {
  250 + thingsModel = new IotThingsModel();
  251 + thingsModel.setData_type(ThingsModelDataTypeEnum.STRING.name());
  252 + thingsModel.setIdentifier(key);
  253 + thingsModel.setModel_name(key);
  254 + thingsModel.setIs_top(0);
  255 + thingsModel.setIs_monitor(0);
  256 + thingsModel.setIs_save_log(0);
  257 + thingsModel.setIs_config(0);
  258 + JSONObject spes = new JSONObject();
  259 + spes.put("maxLength",255);
  260 + thingsModel.setSpecs(spes.toString());
  261 + }
  262 + String data_type = thingsModel.getData_type().toUpperCase();
  263 + Class<ThingsModelBase> aClass = Enum.valueOf(ThingsModelDataTypeEnum.class,data_type).getaClass();
  264 + ThingsModelBase thingsModelBase = JSON.parseObject(thingsModel.getSpecs(),aClass);
  265 + jsonObject.put(skey,thingsModelBase.getCmdView(jsonObject.get(skey)));
  266 + }
  267 +
  268 + map.put(key,jsonObject);
  269 + }
  270 +
  271 + MqttMessage mqttMessage = new MqttMessage();
  272 + mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());
  273 + Message message = clienNoticeService.sendMessage(topic,mqttMessage);
  274 + return message;
168 } 275 }
169 276
170 /** 277 /**
171 - * 删除主机  
172 - * @param client_id 278 + * 获取指定设备版本信息
  279 + * @param app_type
  280 + * @return
173 */ 281 */
174 - public void deletRedisDevice(String client_id) 282 + public Message getFirmwareVersion(String app_type)
175 { 283 {
176 - Set<String> keys = redisService.keys(getRedicTerminalFromClientId(client_id));  
177 - if(null != keys && keys.size() != 0)  
178 - {  
179 - redisService.del(keys.toArray(new String[keys.size()]));  
180 - } 284 + List list = baseDao.findListBysql("SELECT md5str,upload_file_path uploadFilePath,version_number versionNumber,code FROM liu_yu_le.`app_file_upgrade` WHERE app_type='"+app_type+"' ORDER BY id DESC limit 5");
  285 + return new Message(MessageCode.DEFAULT_SUCCESS_CODE,list);
181 } 286 }
182 287
183 /** 288 /**
184 - * 删除终端  
185 - * @param client_ids 289 + * 通过数据获取发送消息的topic
  290 + * @param clienid
  291 + * @return
186 */ 292 */
187 - public void deletRedisTerminal(String... client_ids) 293 + private Topic getTopicFromDb(String clienid)
188 { 294 {
189 - String[] keys = new String[client_ids.length];  
190 - for (int i=0;i<client_ids.length;i++) 295 + JSONArray jsonArray = baseDao.findBysql("SELECT b.`role_id` roleid,b.`mqtt_username` username,a.`client_id` clientid,a.`payload_type` payloadtype FROM `iot_device` a LEFT JOIN `iot_product` b ON a.`product_id`=b.`id` WHERE client_id='"+clienid+"'");
  296 + if(null == jsonArray || jsonArray.size()==0 || null == jsonArray.getJSONObject(0).get("username"))
191 { 297 {
192 - keys[i] = getRedicTerminalKey(client_ids[i]); 298 + return null;
193 } 299 }
194 - redisService.del(keys); 300 + Topic topic = JSON.parseObject( jsonArray.getJSONObject(0).toJSONString(),Topic.class);
  301 + topic.setTopicType("PUT");
  302 + topic.setMessageid(DateUtils.getNowTimeMilly()+"");
  303 + return topic;
  304 + }
  305 + /**
  306 + * 把16进制字符串转换成字节数组
  307 + *
  308 + * @param hex
  309 + * @return
  310 + */
  311 + private byte[] hexStringToByte(String hex) {
  312 + int len = (hex.length() / 2);
  313 + byte[] result = new byte[len];
  314 + char[] achar = hex.toCharArray();
  315 + for (int i = 0; i < len; i++) {
  316 + int pos = i * 2;
  317 + result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
  318 + }
  319 + return result;
  320 + }
  321 + private byte toByte(char c) {
  322 + byte b = (byte) "0123456789ABCDEF".indexOf(c);
  323 + return b;
195 } 324 }
196 } 325 }
1 package com.zhonglai.luhui.mqtt.service.db.mode; 1 package com.zhonglai.luhui.mqtt.service.db.mode;
2 2
  3 +import com.alibaba.fastjson.JSONObject;
3 import com.ruoyi.system.domain.IotThingsModel; 4 import com.ruoyi.system.domain.IotThingsModel;
4 import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService; 5 import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService;
5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.beans.factory.annotation.Autowired;
@@ -50,10 +51,10 @@ public class TerminalDataThingsModeService { @@ -50,10 +51,10 @@ public class TerminalDataThingsModeService {
50 { 51 {
51 if(null != iotThingsModels && iotThingsModels.size() !=0) 52 if(null != iotThingsModels && iotThingsModels.size() !=0)
52 { 53 {
53 - Map<String,Map<Object,Object>> all = new HashMap<>(); 54 + Map<String,Map<String,IotThingsModel>> all = new HashMap<>();
54 for(IotThingsModel iotThingsModel:iotThingsModels) 55 for(IotThingsModel iotThingsModel:iotThingsModels)
55 { 56 {
56 - Map<Object,Object> map = all.get(iotThingsModel.getMqtt_username()); 57 + Map<String,IotThingsModel> map = all.get(iotThingsModel.getMqtt_username());
57 if(null == map) 58 if(null == map)
58 { 59 {
59 map = new HashMap<>(); 60 map = new HashMap<>();
@@ -81,7 +82,7 @@ public class TerminalDataThingsModeService { @@ -81,7 +82,7 @@ public class TerminalDataThingsModeService {
81 { 82 {
82 if(redisService.hHashKey(deviceTypeKeyPath+mqtt_username,identifier)) 83 if(redisService.hHashKey(deviceTypeKeyPath+mqtt_username,identifier))
83 { 84 {
84 - return (IotThingsModel) redisService.hget(deviceTypeKeyPath+mqtt_username,identifier); 85 + return JSONObject.parseObject(JSONObject.toJSONString(redisService.hget(deviceTypeKeyPath+mqtt_username,identifier)),IotThingsModel.class);
85 } 86 }
86 return null; 87 return null;
87 } 88 }
  1 +package com.zhonglai.luhui.mqtt.service.redis;
  2 +
  3 +import com.zhonglai.luhui.mqtt.comm.service.BusinessDataUpdateService;
  4 +import org.slf4j.Logger;
  5 +import org.slf4j.LoggerFactory;
  6 +import org.springframework.data.redis.connection.Message;
  7 +import org.springframework.data.redis.connection.MessageListener;
  8 +import org.springframework.data.redis.listener.PatternTopic;
  9 +import org.springframework.stereotype.Component;
  10 +
  11 +@Component
  12 +public class RedisDeleteListener implements MessageListener {
  13 + private static final Logger logger = LoggerFactory.getLogger(RedisDeleteListener.class);
  14 +
  15 + //监听的主题
  16 + private final PatternTopic topic = new PatternTopic("__keyevent@1__:del"); //#是对db2数据库,key前缀为order所有键的键空间通知
  17 +
  18 + @Override
  19 + public void onMessage(Message message, byte[] pattern){
  20 + String topic = new String(pattern);
  21 + String msg = new String(message.getBody());
  22 + logger.info("收到key删除,消息主题是:"+ topic+",消息内容是:"+msg);
  23 + }
  24 +
  25 + public PatternTopic getTopic() {
  26 + return topic;
  27 + }
  28 +}
  1 +package com.zhonglai.luhui.mqtt.service.redis;
  2 +
  3 +import org.slf4j.Logger;
  4 +import org.slf4j.LoggerFactory;
  5 +import org.springframework.data.redis.connection.Message;
  6 +import org.springframework.data.redis.connection.MessageListener;
  7 +import org.springframework.data.redis.listener.PatternTopic;
  8 +import org.springframework.stereotype.Component;
  9 +
  10 +@Component
  11 +public class RedisExpiredListener implements MessageListener {
  12 + private static final Logger logger = LoggerFactory.getLogger(RedisExpiredListener.class);
  13 + //监听的主题
  14 + private final PatternTopic topic = new PatternTopic("__keyevent@1__:expired");
  15 +
  16 + @Override
  17 + public void onMessage(Message message, byte[] pattern){
  18 + String topic = new String(pattern);
  19 + String msg = new String(message.getBody());
  20 + logger.info("收到key失效,消息主题是:"+ topic+",消息内容是:"+msg);
  21 + }
  22 + public PatternTopic getTopic() {
  23 + return topic;
  24 + }
  25 +}
@@ -10,6 +10,7 @@ import com.zhonglai.luhui.mqtt.dto.topic.AddPostDto; @@ -10,6 +10,7 @@ import com.zhonglai.luhui.mqtt.dto.topic.AddPostDto;
10 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.stereotype.Service; 11 import org.springframework.stereotype.Service;
12 12
  13 +import java.util.ArrayList;
13 14
14 15
15 /** 16 /**
@@ -21,14 +22,18 @@ public class AddPostTopic implements BusinessAgreement<AddPostDto> { @@ -21,14 +22,18 @@ public class AddPostTopic implements BusinessAgreement<AddPostDto> {
21 private BusinessDataUpdateService businessDataUpdateService ; 22 private BusinessDataUpdateService businessDataUpdateService ;
22 @Override 23 @Override
23 public ServerDto analysis(Topic topic, AddPostDto data) { 24 public ServerDto analysis(Topic topic, AddPostDto data) {
24 - businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ADD,topic,data.getData(),true,data.getOperateHisList(),data.getList()); 25 + businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ADD,topic,true,data);
25 return data; 26 return data;
26 } 27 }
27 28
28 @Override 29 @Override
29 public ServerDto toData(BusinessDto data) { 30 public ServerDto toData(BusinessDto data) {
30 AddPostDto serverDto = new AddPostDto(); 31 AddPostDto serverDto = new AddPostDto();
31 - return serverDto.setData((JSONObject) data.getContentData()); 32 + serverDto.setData((JSONObject) data.getContentData());
  33 + serverDto.setIotTerminalList(new ArrayList<>());
  34 + serverDto.setDeviceSensorDataList(new ArrayList<>());
  35 + serverDto.setLogDeviceOperationList(new ArrayList<>());
  36 + return serverDto;
32 } 37 }
33 38
34 } 39 }
@@ -11,6 +11,8 @@ import com.zhonglai.luhui.mqtt.dto.topic.AllPostDto; @@ -11,6 +11,8 @@ import com.zhonglai.luhui.mqtt.dto.topic.AllPostDto;
11 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.stereotype.Service; 12 import org.springframework.stereotype.Service;
13 13
  14 +import java.util.ArrayList;
  15 +
14 16
15 /** 17 /**
16 * 全量上报数据,不需要返回 18 * 全量上报数据,不需要返回
@@ -21,20 +23,26 @@ public class AllPostTopic implements BusinessAgreement<AllPostDto> { @@ -21,20 +23,26 @@ public class AllPostTopic implements BusinessAgreement<AllPostDto> {
21 private BusinessDataUpdateService businessDataUpdateService ; 23 private BusinessDataUpdateService businessDataUpdateService ;
22 @Override 24 @Override
23 public ServerDto analysis(Topic topic, AllPostDto data) throws Exception { 25 public ServerDto analysis(Topic topic, AllPostDto data) throws Exception {
24 - businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ALL,topic,data.getData(),false,data.getOperateHisList(),data.getList()); 26 + businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ALL,topic,false,data);
25 return data; 27 return data;
26 } 28 }
27 29
28 @Override 30 @Override
29 public AllPostDto toData(BusinessDto data) { 31 public AllPostDto toData(BusinessDto data) {
30 AllPostDto serverDto = new AllPostDto(); 32 AllPostDto serverDto = new AllPostDto();
  33 + serverDto.setIotTerminalList(new ArrayList<>());
  34 + serverDto.setDeviceSensorDataList(new ArrayList<>());
  35 + serverDto.setLogDeviceOperationList(new ArrayList<>());
31 if(data.getContentData() instanceof JSONObject) 36 if(data.getContentData() instanceof JSONObject)
32 { 37 {
33 - return serverDto.setData((JSONObject) data.getContentData()); 38 + serverDto.setData((JSONObject) data.getContentData());
  39 + return serverDto;
34 }else if(data.getContentData() instanceof byte[]) 40 }else if(data.getContentData() instanceof byte[])
35 { 41 {
36 - return serverDto.setData(JSONObject.parseObject(new String((byte[]) data.getContentData()))); 42 + serverDto.setData(JSONObject.parseObject(new String((byte[]) data.getContentData())));
  43 + return serverDto;
37 } 44 }
  45 +
38 return null; 46 return null;
39 } 47 }
40 } 48 }
1 -package com.zhonglai.luhui.mqtt.service.topic;  
2 -  
3 -import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;  
4 -import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto;  
5 -import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;  
6 -import com.zhonglai.luhui.mqtt.comm.factory.Topic;  
7 -import com.zhonglai.luhui.mqtt.dto.topic.DbDistributeDto;  
8 -import org.springframework.stereotype.Service;  
9 -  
10 -/**  
11 - * 数据库topic分发  
12 - */  
13 -@Service("DB_TOPIC_DISTRIBUTE")  
14 -public class DbDistributeTopic implements BusinessAgreement<DbDistributeDto> {  
15 - @Override  
16 - public ServerDto analysis(Topic topic, DbDistributeDto data) throws Exception {  
17 - return null;  
18 - }  
19 -  
20 - @Override  
21 - public DbDistributeDto toData(BusinessDto data) {  
22 - return null;  
23 - }  
24 -}  
1 package com.zhonglai.luhui.mqtt.service.topic; 1 package com.zhonglai.luhui.mqtt.service.topic;
2 2
3 -import com.alibaba.fastjson.JSONObject;  
4 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 3 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
  4 +import com.zhonglai.luhui.mqtt.comm.dto.TerminalClientRePlyDto;
5 import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto; 5 import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto;
6 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement; 6 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;
7 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 7 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
8 import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService; 8 import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService;
9 -import com.zhonglai.luhui.mqtt.dto.topic.AllPostDto;  
10 import com.zhonglai.luhui.mqtt.dto.topic.GetDto; 9 import com.zhonglai.luhui.mqtt.dto.topic.GetDto;
11 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.stereotype.Service; 11 import org.springframework.stereotype.Service;
@@ -21,6 +20,18 @@ public class GetTopic implements BusinessAgreement<GetDto> { @@ -21,6 +20,18 @@ public class GetTopic implements BusinessAgreement<GetDto> {
21 20
22 @Override 21 @Override
23 public ServerDto analysis(Topic topic, GetDto data) throws Exception { 22 public ServerDto analysis(Topic topic, GetDto data) throws Exception {
  23 + //回复客户端消息
  24 + clienNoticeService.replyTerminalMessage(topic, new TerminalClientRePlyDto() {
  25 + @Override
  26 + public byte[] getCommd() {
  27 + return new byte[0];
  28 + }
  29 +
  30 + @Override
  31 + public String getReplyCommdTopic(Topic topic) {
  32 + return null;
  33 + }
  34 + });
24 return null; 35 return null;
25 } 36 }
26 37
@@ -30,15 +41,5 @@ public class GetTopic implements BusinessAgreement<GetDto> { @@ -30,15 +41,5 @@ public class GetTopic implements BusinessAgreement<GetDto> {
30 return serverDto; 41 return serverDto;
31 } 42 }
32 43
33 - /**  
34 - * 回复客户端消息  
35 - * @param topic  
36 - * @param dto  
37 - */  
38 - private void replySendMessage(Topic topic,ServerDto dto)  
39 - {  
40 - //回复客户端消息  
41 - clienNoticeService.replySendMessage(topic,dto);  
42 - }  
43 44
44 } 45 }
@@ -5,13 +5,23 @@ import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto; @@ -5,13 +5,23 @@ import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto;
5 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement; 5 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;
6 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 6 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
7 import com.zhonglai.luhui.mqtt.dto.topic.OnlineDto; 7 import com.zhonglai.luhui.mqtt.dto.topic.OnlineDto;
  8 +import com.zhonglai.luhui.mqtt.service.db.DeviceService;
  9 +import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.stereotype.Service; 10 import org.springframework.stereotype.Service;
9 11
10 12
11 @Service("ONLINE") 13 @Service("ONLINE")
12 public class OnlineTopic implements BusinessAgreement<OnlineDto> { 14 public class OnlineTopic implements BusinessAgreement<OnlineDto> {
  15 + @Autowired
  16 + private DeviceService deviceService ;
13 @Override 17 @Override
14 public ServerDto analysis(Topic topic, OnlineDto data) throws Exception { 18 public ServerDto analysis(Topic topic, OnlineDto data) throws Exception {
  19 + if(1==data.getState()) //在线
  20 + {
  21 +
  22 + }else{ //离线
  23 + deviceService.deviceOffLine(topic.getClientid());
  24 + }
15 return data; 25 return data;
16 } 26 }
17 27
@@ -6,9 +6,8 @@ import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto; @@ -6,9 +6,8 @@ import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto;
6 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement; 6 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;
7 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 7 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
8 import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService; 8 import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService;
9 -import com.zhonglai.luhui.mqtt.dto.topic.AllPostDto; 9 +import com.zhonglai.luhui.mqtt.dto.MessageCode;
10 import com.zhonglai.luhui.mqtt.dto.topic.PutReqDto; 10 import com.zhonglai.luhui.mqtt.dto.topic.PutReqDto;
11 -import org.eclipse.paho.client.mqttv3.MqttException;  
12 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.stereotype.Service; 12 import org.springframework.stereotype.Service;
14 13
@@ -17,14 +16,24 @@ import org.springframework.stereotype.Service; @@ -17,14 +16,24 @@ import org.springframework.stereotype.Service;
17 */ 16 */
18 @Service("PUT_REQ") 17 @Service("PUT_REQ")
19 public class PutReqTopic implements BusinessAgreement<PutReqDto> { 18 public class PutReqTopic implements BusinessAgreement<PutReqDto> {
20 -  
21 @Autowired 19 @Autowired
22 private ClienNoticeService clienNoticeService; //客户端通知服务 20 private ClienNoticeService clienNoticeService; //客户端通知服务
23 21
24 @Override 22 @Override
25 public ServerDto analysis(Topic topic, PutReqDto data) throws Exception { 23 public ServerDto analysis(Topic topic, PutReqDto data) throws Exception {
26 data.setMessageid(topic.getMessageid()); 24 data.setMessageid(topic.getMessageid());
27 - clienNoticeService.replySendMessage(topic,data); 25 + clienNoticeService.replySendMessage(topic, message -> {
  26 + message.setData(data.getData());
  27 + message.setCode(MessageCode.DEFAULT_SUCCESS_CODE);
  28 + message.setMessage("成功");
  29 + switch (data.getCode())
  30 + {
  31 + case 0:
  32 + message.setCode(MessageCode.DEFAULT_FAIL_CODE);
  33 + message.setMessage("失败");
  34 + break;
  35 + }
  36 + });
28 return null; 37 return null;
29 } 38 }
30 39
@@ -3,6 +3,7 @@ package com.zhonglai.luhui.mqtt.service.topic; @@ -3,6 +3,7 @@ package com.zhonglai.luhui.mqtt.service.topic;
3 import com.alibaba.fastjson.JSON; 3 import com.alibaba.fastjson.JSON;
4 import com.alibaba.fastjson.JSONObject; 4 import com.alibaba.fastjson.JSONObject;
5 import com.ruoyi.system.domain.IotThingsModel; 5 import com.ruoyi.system.domain.IotThingsModel;
  6 +import com.zhonglai.luhui.mqtt.comm.dto.ApiClientRePlyDto;
6 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 7 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
7 import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto; 8 import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto;
8 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelBase; 9 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelBase;
@@ -11,12 +12,16 @@ import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement; @@ -11,12 +12,16 @@ import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;
11 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 12 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
12 import com.zhonglai.luhui.mqtt.comm.service.BusinessDataUpdateService; 13 import com.zhonglai.luhui.mqtt.comm.service.BusinessDataUpdateService;
13 import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService; 14 import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService;
  15 +import com.zhonglai.luhui.mqtt.dto.Message;
  16 +import com.zhonglai.luhui.mqtt.dto.MessageCode;
14 import com.zhonglai.luhui.mqtt.dto.topic.ReadReqDto; 17 import com.zhonglai.luhui.mqtt.dto.topic.ReadReqDto;
15 import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService; 18 import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService;
16 import org.apache.commons.lang3.EnumUtils; 19 import org.apache.commons.lang3.EnumUtils;
17 import org.springframework.beans.factory.annotation.Autowired; 20 import org.springframework.beans.factory.annotation.Autowired;
18 import org.springframework.stereotype.Service; 21 import org.springframework.stereotype.Service;
19 22
  23 +import java.util.HashMap;
  24 +
20 @Service("READ_REQ") 25 @Service("READ_REQ")
21 public class ReadReqTopic implements BusinessAgreement<ReadReqDto> { 26 public class ReadReqTopic implements BusinessAgreement<ReadReqDto> {
22 @Autowired 27 @Autowired
@@ -24,62 +29,73 @@ public class ReadReqTopic implements BusinessAgreement<ReadReqDto> { @@ -24,62 +29,73 @@ public class ReadReqTopic implements BusinessAgreement<ReadReqDto> {
24 @Autowired 29 @Autowired
25 private BusinessDataUpdateService businessDataUpdateService ; 30 private BusinessDataUpdateService businessDataUpdateService ;
26 31
27 - @Autowired  
28 - private TerminalDataThingsModeService terminalDataThingsModeService;  
29 -  
30 @Override 32 @Override
31 public ServerDto analysis(Topic topic, ReadReqDto data) { 33 public ServerDto analysis(Topic topic, ReadReqDto data) {
32 if(1==data.getCode()) 34 if(1==data.getCode())
33 { 35 {
34 - JSONObject vjsonObject = data.getData().clone();  
35 - businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ADD,topic,data.getData(),true,data.getOperateHisList(),data.getList()); 36 +// JSONObject vjsonObject = data.getData().clone();
  37 + businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ADD,topic,true,data);
36 38
37 - if(null != vjsonObject && vjsonObject.size() !=0 )  
38 - {  
39 - for(String vkey:vjsonObject.keySet()) 39 +// if(null != vjsonObject && vjsonObject.size() !=0 )
  40 +// {
  41 +// for(String vkey:vjsonObject.keySet())
  42 +// {
  43 +// JSONObject jsData = vjsonObject.getJSONObject(vkey);
  44 +// for(String key:jsData.keySet())
  45 +// {
  46 +// IotThingsModel thingsModel = terminalDataThingsModeService.getIotThingsModel(topic.getUsername(),key);
  47 +// if(null == thingsModel) //没有配置的 都按字符串处理
  48 +// {
  49 +// thingsModel = new IotThingsModel();
  50 +// thingsModel.setData_type(ThingsModelDataTypeEnum.STRING.name());
  51 +// thingsModel.setIdentifier(key);
  52 +// thingsModel.setModel_name(key);
  53 +// thingsModel.setIs_top(0);
  54 +// thingsModel.setIs_monitor(0);
  55 +// thingsModel.setIs_save_log(0);
  56 +// thingsModel.setIs_config(0);
  57 +// JSONObject jsonObject = new JSONObject();
  58 +// jsonObject.put("maxLength",255);
  59 +// thingsModel.setSpecs(jsonObject.toString());
  60 +// }
  61 +// String data_type = thingsModel.getData_type().toUpperCase();
  62 +// if(!EnumUtils.isValidEnum(ThingsModelDataTypeEnum.class,data_type))
  63 +// {
  64 +// data_type = ThingsModelDataTypeEnum.STRING.name();
  65 +// }
  66 +// Class<ThingsModelBase> aClass = Enum.valueOf(ThingsModelDataTypeEnum.class,data_type).getaClass();
  67 +// ThingsModelBase thingsModelBase = JSON.parseObject(thingsModel.getSpecs(),aClass);
  68 +// thingsModelBase.conversionThingsModel(thingsModel);
  69 +//
  70 +// thingsModelBase.addValue(jsData.get(key));
  71 +// jsData.put(key,thingsModelBase);
  72 +// }
  73 +// vjsonObject.put(vkey,jsData);
  74 +// }
  75 +// data.setData(vjsonObject);
  76 +// }
  77 + clienNoticeService.replySendMessage(topic, message -> {
  78 + if(null != data.getData())
40 { 79 {
41 - JSONObject jsData = vjsonObject.getJSONObject(vkey);  
42 - for(String key:jsData.keySet())  
43 - {  
44 - IotThingsModel thingsModel = terminalDataThingsModeService.getIotThingsModel(topic.getUsername(),key);  
45 - if(null == thingsModel) //没有配置的 都按字符串处理  
46 - {  
47 - thingsModel = new IotThingsModel();  
48 - thingsModel.setData_type(ThingsModelDataTypeEnum.STRING.name());  
49 - thingsModel.setIdentifier(key);  
50 - thingsModel.setModel_name(key);  
51 - thingsModel.setIs_top(0);  
52 - thingsModel.setIs_monitor(0);  
53 - thingsModel.setIs_save_log(0);  
54 - thingsModel.setIs_config(0);  
55 - JSONObject jsonObject = new JSONObject();  
56 - jsonObject.put("maxLength",255);  
57 - thingsModel.setSpecs(jsonObject.toString());  
58 - }  
59 - String data_type = thingsModel.getData_type().toUpperCase();  
60 - if(!EnumUtils.isValidEnum(ThingsModelDataTypeEnum.class,data_type))  
61 - {  
62 - data_type = ThingsModelDataTypeEnum.STRING.name();  
63 - }  
64 - Class<ThingsModelBase> aClass = Enum.valueOf(ThingsModelDataTypeEnum.class,data_type).getaClass();  
65 - ThingsModelBase thingsModelBase = JSON.parseObject(thingsModel.getSpecs(),aClass);  
66 - thingsModelBase.conversionThingsModel(thingsModel);  
67 -  
68 - thingsModelBase.addValue(jsData.get(key));  
69 - jsData.put(key,thingsModelBase);  
70 - }  
71 - vjsonObject.put(vkey,jsData); 80 + message.setData(JSONObject.parseObject(data.getData().toJSONString(), HashMap.class));
72 } 81 }
73 - data.setData(vjsonObject);  
74 - }  
75 - clienNoticeService.replySendMessage(topic,data); 82 + message.setCode(MessageCode.DEFAULT_SUCCESS_CODE);
  83 + message.setMessage("成功");
  84 + });
76 return data; 85 return data;
77 }else if(0==data.getCode()) 86 }else if(0==data.getCode())
78 { 87 {
79 - clienNoticeService.replySendMessage(topic,data); 88 + clienNoticeService.replySendMessage(topic, message -> {
  89 + if(null != data.getData())
  90 + {
  91 + message.setData(JSONObject.parseObject(data.getData().toJSONString(), HashMap.class));
  92 + }
  93 + message.setCode(MessageCode.DEFAULT_FAIL_CODE);
  94 + message.setMessage("失败");
  95 + });
80 return data; 96 return data;
81 } 97 }
82 - return null; 98 + return data;
83 } 99 }
84 100
85 @Override 101 @Override
@@ -44,7 +44,7 @@ mqtt: @@ -44,7 +44,7 @@ mqtt:
44 #唯一标识 44 #唯一标识
45 clientId: ${random.uuid} 45 clientId: ${random.uuid}
46 #订阅的topic 46 #订阅的topic
47 - topics: "/+/+/+/+/ADD_POST,/+/+/+/+/ALL_POST,/+/+/+/+/DB_TOPIC_DISTRIBUTE,/+/+/+/+/GET/+,/+/+/+/+/online,/+/+/+/+/PUT_REQ/+,/+/+/+/+/READ_REQ/+" 47 + topics: "/2/6_WP/+/+/ADD_POST,/2/6_WP/+/+/ALL_POST,/2/6_WP/+/+/DB_TOPIC_DISTRIBUTE,/2/6_WP/+/+/GET/+,/2/6_WP/+/+/online,/2/6_WP/+/+/PUT_REQ/+,/2/6_WP/+/+/READ_REQ/+"
48 topicconfig: "/{{roleid}}/{{username}}/{{clientid}}/{{payloadtype}}/{{topicType}}/{{messageid}}" 48 topicconfig: "/{{roleid}}/{{username}}/{{clientid}}/{{payloadtype}}/{{topicType}}/{{messageid}}"
49 top_return_map: '{"PUT":"PUT_REQ","READ":"READ_REQ"}' 49 top_return_map: '{"PUT":"PUT_REQ","READ":"READ_REQ"}'
50 username: sysuser 50 username: sysuser
@@ -61,5 +61,10 @@ mqtt: @@ -61,5 +61,10 @@ mqtt:
61 61
62 sys: 62 sys:
63 redis: 63 redis:
64 - field: "luhui:mqttservice:device:" 64 + field: "lh:mqttservice:"
65 isText: false 65 isText: false
  66 +
  67 +#rocketmq配置信息
  68 +rocketmq:
  69 + #nameservice服务器地址(多个以英文逗号隔开)
  70 + name-server: 47.115.144.179:9876
@@ -330,6 +330,12 @@ @@ -330,6 +330,12 @@
330 <artifactId>jedis</artifactId> 330 <artifactId>jedis</artifactId>
331 <version>3.6.3</version> 331 <version>3.6.3</version>
332 </dependency> 332 </dependency>
  333 +
  334 + <dependency>
  335 + <groupId>org.apache.rocketmq</groupId>
  336 + <artifactId>rocketmq-spring-boot-starter</artifactId>
  337 + <version>2.1.1</version>
  338 + </dependency>
333 </dependencies> 339 </dependencies>
334 340
335 341
@@ -107,7 +107,7 @@ public class LoginService { @@ -107,7 +107,7 @@ public class LoginService {
107 */ 107 */
108 public String yu2leTokenLogin(String token) { 108 public String yu2leTokenLogin(String token) {
109 Yu2leLoginToken loginToken = new Yu2leLoginToken(token); 109 Yu2leLoginToken loginToken = new Yu2leLoginToken(token);
110 - Yu2leUserLogin userInfo = publicService.getObjectForTableName(Yu2leUserLogin.class,"id",loginToken.getUserId()+"","`liu_yu_le`.`user_login`"); 110 + Yu2leUserLogin userInfo = publicService.getObjectForTableName(Yu2leUserLogin.class,"user_id",loginToken.getUserId()+"","`liu_yu_le`.`user_login`");
111 return apiLoginByPass(userInfo.getLoginName(),DESUtil.decode(userInfo.getLoginPass(),userInfo.getUserLoginPassKey())); 111 return apiLoginByPass(userInfo.getLoginName(),DESUtil.decode(userInfo.getLoginPass(),userInfo.getUserLoginPassKey()));
112 } 112 }
113 113