作者 钟来

初始提交

正在显示 51 个修改的文件 包含 2817 行增加105 行删除
@@ -10,16 +10,16 @@ import com.ruoyi.common.utils.StringUtils; @@ -10,16 +10,16 @@ import com.ruoyi.common.utils.StringUtils;
10 import com.ruoyi.common.utils.html.HttpUtils; 10 import com.ruoyi.common.utils.html.HttpUtils;
11 import com.ruoyi.system.domain.IotDevice; 11 import com.ruoyi.system.domain.IotDevice;
12 import com.ruoyi.system.service.IIotDeviceService; 12 import com.ruoyi.system.service.IIotDeviceService;
  13 +import com.ruoyi.system.service.IIotTerminalService;
13 import io.swagger.annotations.Api; 14 import io.swagger.annotations.Api;
14 import io.swagger.annotations.ApiImplicitParam; 15 import io.swagger.annotations.ApiImplicitParam;
15 import io.swagger.annotations.ApiImplicitParams; 16 import io.swagger.annotations.ApiImplicitParams;
16 import io.swagger.annotations.ApiOperation; 17 import io.swagger.annotations.ApiOperation;
17 -import okhttp3.FormBody;  
18 -import okhttp3.Request;  
19 import okhttp3.Response; 18 import okhttp3.Response;
20 import org.springframework.beans.factory.annotation.Autowired; 19 import org.springframework.beans.factory.annotation.Autowired;
21 import org.springframework.security.access.prepost.PreAuthorize; 20 import org.springframework.security.access.prepost.PreAuthorize;
22 import org.springframework.stereotype.Controller; 21 import org.springframework.stereotype.Controller;
  22 +import org.springframework.transaction.annotation.Transactional;
23 import org.springframework.web.bind.annotation.*; 23 import org.springframework.web.bind.annotation.*;
24 24
25 import javax.servlet.http.HttpServletResponse; 25 import javax.servlet.http.HttpServletResponse;
@@ -33,7 +33,8 @@ import java.util.Map; @@ -33,7 +33,8 @@ import java.util.Map;
33 public class IotDeviceControlController { 33 public class IotDeviceControlController {
34 @Autowired 34 @Autowired
35 private IIotDeviceService iotDeviceService; 35 private IIotDeviceService iotDeviceService;
36 - 36 + @Autowired
  37 + private IIotTerminalService iIotTerminalService;
37 private String getServiceAdrres(HttpServletResponse response,String imei) throws IOException { 38 private String getServiceAdrres(HttpServletResponse response,String imei) throws IOException {
38 IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei); 39 IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
39 response.setCharacterEncoding("UTF-8"); 40 response.setCharacterEncoding("UTF-8");
@@ -142,22 +143,32 @@ public class IotDeviceControlController { @@ -142,22 +143,32 @@ public class IotDeviceControlController {
142 @ApiImplicitParams({ 143 @ApiImplicitParams({
143 @ApiImplicitParam(value = "主机imei",name = "imei"), 144 @ApiImplicitParam(value = "主机imei",name = "imei"),
144 }) 145 })
  146 + @Transactional
145 @ResponseBody 147 @ResponseBody
146 @PostMapping("/delIotDevice/{imei}") 148 @PostMapping("/delIotDevice/{imei}")
147 - public String delIotDevice(HttpServletResponse response,@PathVariable String imei) throws IOException { 149 + public String delIotDevice(HttpServletResponse response,@PathVariable String imei) {
148 IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei); 150 IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
  151 + iotDeviceService.deleteIotDeviceByClient_id(imei);
  152 + iIotTerminalService.deleteIotTerminalByDeviceId(imei);
149 response.setCharacterEncoding("UTF-8"); 153 response.setCharacterEncoding("UTF-8");
150 if(StringUtils.isEmpty(iotDevice.getListen_service_ip())) 154 if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
151 { 155 {
152 - response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));  
153 - return null; 156 + return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
154 } 157 }
155 String url = "http://"+iotDevice.getListen_service_ip()+"device/delIotDevice/"+imei; 158 String url = "http://"+iotDevice.getListen_service_ip()+"device/delIotDevice/"+imei;
156 159
157 - Response response1 = HttpUtils.postFromBody(url, builder -> {  
158 - }, formBody -> {  
159 - });  
160 - return response1.body().string(); 160 + try {
  161 + String str = HttpUtils.getResponseString(HttpUtils.postFromBody(url, builder -> {
  162 + }, formBody -> {
  163 + }));
  164 + if(null != str)
  165 + {
  166 + return str;
  167 + }
  168 + } catch (IOException e) {
  169 + }
  170 + return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
  171 +
161 } 172 }
162 173
163 @ApiOperation("删除终端") 174 @ApiOperation("删除终端")
@@ -166,20 +177,28 @@ public class IotDeviceControlController { @@ -166,20 +177,28 @@ public class IotDeviceControlController {
166 }) 177 })
167 @ResponseBody 178 @ResponseBody
168 @PostMapping("/delIotTerminal/{imei}/{number}") 179 @PostMapping("/delIotTerminal/{imei}/{number}")
169 - public String delIotTerminal(HttpServletResponse response,@PathVariable String imei,@PathVariable String number) throws IOException { 180 + public String delIotTerminal(HttpServletResponse response,@PathVariable String imei,@PathVariable String number) {
170 IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei); 181 IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
  182 + iIotTerminalService.deleteIotTerminalById(imei+"_"+number);
171 response.setCharacterEncoding("UTF-8"); 183 response.setCharacterEncoding("UTF-8");
172 if(StringUtils.isEmpty(iotDevice.getListen_service_ip())) 184 if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
173 { 185 {
174 - response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));  
175 - return null; 186 + return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
176 } 187 }
177 String url = "http://"+iotDevice.getListen_service_ip()+"device/delIotTerminal/"+imei+"/"+number; 188 String url = "http://"+iotDevice.getListen_service_ip()+"device/delIotTerminal/"+imei+"/"+number;
178 189
179 - Response response1 = HttpUtils.postFromBody(url, builder -> {  
180 - }, formBody -> {  
181 - });  
182 - return response1.body().string(); 190 + String str = null;
  191 + try {
  192 + str = HttpUtils.getResponseString(HttpUtils.postFromBody(url, builder -> {
  193 + }, formBody -> {
  194 + }));
  195 + } catch (IOException e) {
  196 + }
  197 + if(null != str)
  198 + {
  199 + return str;
  200 + }
  201 + return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
183 } 202 }
184 203
185 @ApiOperation(value = "读取属性") 204 @ApiOperation(value = "读取属性")
@@ -41,8 +41,6 @@ public class IotDeviceController extends BaseController @@ -41,8 +41,6 @@ public class IotDeviceController extends BaseController
41 { 41 {
42 @Autowired 42 @Autowired
43 private IIotDeviceService iotDeviceService; 43 private IIotDeviceService iotDeviceService;
44 - @Autowired  
45 - private IIotProductService iIotProductService;  
46 /** 44 /**
47 * 查询主机/网关列表 45 * 查询主机/网关列表
48 */ 46 */
@@ -90,11 +88,8 @@ public class IotDeviceController extends BaseController @@ -90,11 +88,8 @@ public class IotDeviceController extends BaseController
90 @PostMapping("add") 88 @PostMapping("add")
91 public AjaxResult add(@RequestBody IotDevice iotDevice) 89 public AjaxResult add(@RequestBody IotDevice iotDevice)
92 { 90 {
93 -  
94 - IotProduct iotProduct = iIotProductService.selectIotProductById(iotDevice.getProduct_id());  
95 - iotDevice.setMqtt_username(iotProduct.getMqtt_username());  
96 iotDevice.setCreate_by(getUsername()); 91 iotDevice.setCreate_by(getUsername());
97 - iotDevice.setCreate_time(DateUtils.getNowTimeMilly()); 92 + iotDevice.setUpdate_time(DateUtils.getNowTimeMilly());
98 return toAjax(iotDeviceService.insertIotDevice(iotDevice)); 93 return toAjax(iotDeviceService.insertIotDevice(iotDevice));
99 } 94 }
100 95
  1 +package com.zhonglai.luhui.admin.controller.iot;
  2 +
  3 +import java.util.List;
  4 +import javax.servlet.http.HttpServletResponse;
  5 +
  6 +import com.ruoyi.common.core.redis.RedisCache;
  7 +import com.ruoyi.common.utils.DateUtils;
  8 +import io.swagger.annotations.Api;
  9 +import io.swagger.annotations.ApiOperation;
  10 +import org.springframework.security.access.prepost.PreAuthorize;
  11 +import org.springframework.beans.factory.annotation.Autowired;
  12 +import org.springframework.web.bind.annotation.GetMapping;
  13 +import org.springframework.web.bind.annotation.PostMapping;
  14 +import org.springframework.web.bind.annotation.PutMapping;
  15 +import org.springframework.web.bind.annotation.DeleteMapping;
  16 +import org.springframework.web.bind.annotation.PathVariable;
  17 +import org.springframework.web.bind.annotation.RequestBody;
  18 +import org.springframework.web.bind.annotation.RequestMapping;
  19 +import org.springframework.web.bind.annotation.RestController;
  20 +import com.ruoyi.common.annotation.Log;
  21 +import com.ruoyi.common.core.controller.BaseController;
  22 +import com.ruoyi.common.core.domain.AjaxResult;
  23 +import com.ruoyi.common.enums.BusinessType;
  24 +import com.ruoyi.system.domain.IotProductTranslate;
  25 +import com.ruoyi.system.service.IIotProductTranslateService;
  26 +import com.ruoyi.common.utils.poi.ExcelUtil;
  27 +import com.ruoyi.common.core.page.TableDataInfo;
  28 +
  29 +/**
  30 + * 产品指标翻译Controller
  31 + *
  32 + * @author 钟来
  33 + * @date 2022-11-04
  34 + */
  35 +@Api(tags = "产品指标翻译")
  36 +@RestController
  37 +@RequestMapping("/iot/IotProductTranslate")
  38 +public class IotProductTranslateController extends BaseController
  39 +{
  40 + @Autowired
  41 + private IIotProductTranslateService iotProductTranslateService;
  42 +
  43 + /**
  44 + * 查询产品指标翻译列表
  45 + */
  46 + @ApiOperation("查询产品指标翻译列表")
  47 + @PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:list')")
  48 + @GetMapping("/list")
  49 + public TableDataInfo list(IotProductTranslate iotProductTranslate)
  50 + {
  51 + startPage();
  52 + List<IotProductTranslate> list = iotProductTranslateService.selectIotProductTranslateList(iotProductTranslate);
  53 + return getDataTable(list);
  54 + }
  55 +
  56 + /**
  57 + * 导出产品指标翻译列表
  58 + */
  59 + @ApiOperation("导出产品指标翻译列表")
  60 + @PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:export')")
  61 + @Log(title = "产品指标翻译", businessType = BusinessType.EXPORT)
  62 + @PostMapping("/export")
  63 + public void export(HttpServletResponse response, IotProductTranslate iotProductTranslate)
  64 + {
  65 + List<IotProductTranslate> list = iotProductTranslateService.selectIotProductTranslateList(iotProductTranslate);
  66 + ExcelUtil<IotProductTranslate> util = new ExcelUtil<IotProductTranslate>(IotProductTranslate.class);
  67 + util.exportExcel(response, list, "产品指标翻译数据");
  68 + }
  69 +
  70 + /**
  71 + * 获取产品指标翻译详细信息
  72 + */
  73 + @ApiOperation("获取产品指标翻译详细信息")
  74 + @PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:query')")
  75 + @GetMapping(value = "/{id}")
  76 + public AjaxResult getInfo(@PathVariable("id") Integer id)
  77 + {
  78 + return AjaxResult.success(iotProductTranslateService.selectIotProductTranslateById(id));
  79 + }
  80 +
  81 + /**
  82 + * 新增产品指标翻译
  83 + */
  84 + @ApiOperation("新增产品指标翻译")
  85 + @PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:add')")
  86 + @Log(title = "产品指标翻译", businessType = BusinessType.INSERT)
  87 + @PostMapping
  88 + public AjaxResult add(@RequestBody IotProductTranslate iotProductTranslate)
  89 + {
  90 + iotProductTranslate.setCreate_time(DateUtils.getNowTimeMilly());
  91 + return toAjax(iotProductTranslateService.insertIotProductTranslate(iotProductTranslate));
  92 + }
  93 +
  94 + @ApiOperation("批量新增产品指标翻译")
  95 + @PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:addAll')")
  96 + @Log(title = "产品指标翻译", businessType = BusinessType.INSERT)
  97 + @PostMapping("/addAll")
  98 + public AjaxResult addAll(@RequestBody List<IotProductTranslate> list)
  99 + {
  100 + return toAjax(iotProductTranslateService.insertAll(list));
  101 + }
  102 +
  103 + /**
  104 + * 修改产品指标翻译
  105 + */
  106 + @ApiOperation("修改产品指标翻译")
  107 + @PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:edit')")
  108 + @Log(title = "产品指标翻译", businessType = BusinessType.UPDATE)
  109 + @PutMapping
  110 + public AjaxResult edit(@RequestBody IotProductTranslate iotProductTranslate)
  111 + {
  112 + return toAjax(iotProductTranslateService.updateIotProductTranslate(iotProductTranslate));
  113 + }
  114 +
  115 + /**
  116 + * 删除产品指标翻译
  117 + */
  118 + @ApiOperation("删除产品指标翻译")
  119 + @PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:remove')")
  120 + @Log(title = "产品指标翻译", businessType = BusinessType.DELETE)
  121 + @DeleteMapping("/{ids}")
  122 + public AjaxResult remove(@PathVariable Integer[] ids)
  123 + {
  124 + return toAjax(iotProductTranslateService.deleteIotProductTranslateByIds(ids));
  125 + }
  126 +
  127 +}
@@ -3,6 +3,8 @@ package com.zhonglai.luhui.admin.controller.iot; @@ -3,6 +3,8 @@ package com.zhonglai.luhui.admin.controller.iot;
3 import java.util.List; 3 import java.util.List;
4 import javax.servlet.http.HttpServletResponse; 4 import javax.servlet.http.HttpServletResponse;
5 5
  6 +import com.ruoyi.common.utils.DateUtils;
  7 +import com.ruoyi.system.service.IIotProductTranslateService;
6 import io.swagger.annotations.Api; 8 import io.swagger.annotations.Api;
7 import io.swagger.annotations.ApiOperation; 9 import io.swagger.annotations.ApiOperation;
8 import org.springframework.security.access.prepost.PreAuthorize; 10 import org.springframework.security.access.prepost.PreAuthorize;
@@ -97,6 +99,7 @@ public class IotTerminalController extends BaseController @@ -97,6 +99,7 @@ public class IotTerminalController extends BaseController
97 @PutMapping 99 @PutMapping
98 public AjaxResult edit(@RequestBody IotTerminal iotTerminal) 100 public AjaxResult edit(@RequestBody IotTerminal iotTerminal)
99 { 101 {
  102 + iotTerminal.setUpdate_time(DateUtils.getNowTimeMilly());
100 return toAjax(iotTerminalService.updateIotTerminal(iotTerminal)); 103 return toAjax(iotTerminalService.updateIotTerminal(iotTerminal));
101 } 104 }
102 105
1 -# 项目相关配置 jhlt: # 名称 name: zhonglai # 版本 version: 3.8.2 # 版权年份 copyrightYear: 2022 # 实例演示开关 demoEnabled: true # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath) profile: D:/ruoyi/uploadPath # 获取ip地址开关 addressEnabled: false # 验证码类型 math 数组计算 char 字符验证 captchaType: math # 开发环境配置 server: # 服务器的HTTP端口,默认为8080 port: 8080 servlet: # 应用的访问路径 context-path: / tomcat: # tomcat的URI编码 uri-encoding: UTF-8 # 连接数满后的排队数,默认为100 accept-count: 1000 threads: # tomcat最大线程数,默认为200 max: 800 # Tomcat启动初始化的线程数,默认值10 min-spare: 100 # 日志配置 logging: level: com.ruoyi: debug org.springframework: warn # Spring配置 spring: # 资源信息 messages: # 国际化资源文件路径 basename: i18n/messages profiles: active: druid # 文件上传 servlet: multipart: # 单个文件大小 max-file-size: 10MB # 设置总上传的文件大小 max-request-size: 20MB # 服务模块 devtools: restart: # 热部署开关 enabled: true # redis 配置 redis: # 地址 host: 47.112.163.61 # 端口,默认为6379 port: 9527 # 数据库索引 database: 0 # 密码 password: Luhui586 # 连接超时时间 timeout: 10s lettuce: pool: # 连接池中的最小空闲连接 min-idle: 0 # 连接池中的最大空闲连接 max-idle: 8 # 连接池的最大数据库连接数 max-active: 8 # #连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1ms # token配置 token: # 令牌自定义标识 header: Authorization # 令牌密钥 secret: abcdefghijklmnopqrstuvwxyz # 令牌有效期(默认30分钟) expireTime: 1440 # MyBatis配置 mybatis: # 搜索指定包别名 typeAliasesPackage: com.ruoyi.**.domain # 配置mapper的扫描,找到所有的mapper.xml映射文件 mapperLocations: classpath*:mapper/**/*Mapper.xml # 加载全局的配置文件 configLocation: classpath:mybatis/mybatis-config.xml # PageHelper分页插件 pagehelper: helperDialect: mysql supportMethodsArguments: true params: count=countSql # Swagger配置 swagger: # 是否开启swagger enabled: true # 请求前缀 pathMapping: /dev-api # 防止XSS攻击 xss: # 过滤开关 enabled: true # 排除链接(多个用逗号分隔) excludes: /system/notice # 匹配链接 urlPatterns: /system/*,/monitor/*,/tool/* mqtt: client: device_life: 180 sys: ## // 对于登录login 注册register 验证码captchaImage 允许匿名访问 antMatchers: /login,/register,/captchaImage,/getCacheObject,/v2/api-docs,/tool/gen/generatorCodeFromDb  
  1 +# 项目相关配置 jhlt: # 名称 name: zhonglai # 版本 version: 3.8.2 # 版权年份 copyrightYear: 2022 # 实例演示开关 demoEnabled: true # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath) profile: D:/ruoyi/uploadPath # 获取ip地址开关 addressEnabled: false # 验证码类型 math 数组计算 char 字符验证 captchaType: math # 开发环境配置 server: # 服务器的HTTP端口,默认为8080 port: 8080 servlet: # 应用的访问路径 context-path: / tomcat: # tomcat的URI编码 uri-encoding: UTF-8 # 连接数满后的排队数,默认为100 accept-count: 1000 threads: # tomcat最大线程数,默认为200 max: 800 # Tomcat启动初始化的线程数,默认值10 min-spare: 100 # 日志配置 logging: level: com.ruoyi: debug org.springframework: warn # Spring配置 spring: # 资源信息 messages: # 国际化资源文件路径 basename: i18n/messages profiles: active: druid # 文件上传 servlet: multipart: # 单个文件大小 max-file-size: 10MB # 设置总上传的文件大小 max-request-size: 20MB # 服务模块 devtools: restart: # 热部署开关 enabled: true # redis 配置 redis: # 地址 host: 47.112.163.61 # 端口,默认为6379 port: 9527 # 数据库索引 database: 1 # 密码 password: Luhui586 # 连接超时时间 timeout: 10s lettuce: pool: # 连接池中的最小空闲连接 min-idle: 0 # 连接池中的最大空闲连接 max-idle: 8 # 连接池的最大数据库连接数 max-active: 8 # #连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1ms # token配置 token: # 令牌自定义标识 header: Authorization # 令牌密钥 secret: abcdefghijklmnopqrstuvwxyz # 令牌有效期(默认30分钟) expireTime: 1440 # MyBatis配置 mybatis: # 搜索指定包别名 typeAliasesPackage: com.ruoyi.**.domain # 配置mapper的扫描,找到所有的mapper.xml映射文件 mapperLocations: classpath*:mapper/**/*Mapper.xml # 加载全局的配置文件 configLocation: classpath:mybatis/mybatis-config.xml # PageHelper分页插件 pagehelper: helperDialect: mysql supportMethodsArguments: true params: count=countSql # Swagger配置 swagger: # 是否开启swagger enabled: true # 请求前缀 pathMapping: /dev-api # 防止XSS攻击 xss: # 过滤开关 enabled: true # 排除链接(多个用逗号分隔) excludes: /system/notice # 匹配链接 urlPatterns: /system/*,/monitor/*,/tool/* mqtt: client: device_life: 180 sys: ## // 对于登录login 注册register 验证码captchaImage 允许匿名访问 antMatchers: /login,/register,/captchaImage,/getCacheObject,/v2/api-docs,/tool/gen/generatorCodeFromDb
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<project xmlns="http://maven.apache.org/POM/4.0.0"
  3 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5 + <parent>
  6 + <artifactId>Luhui</artifactId>
  7 + <groupId>com.zhonglai.luhui</groupId>
  8 + <version>1.0-SNAPSHOT</version>
  9 + </parent>
  10 + <modelVersion>4.0.0</modelVersion>
  11 +
  12 + <artifactId>lh-api</artifactId>
  13 +
  14 + <dependencies>
  15 + <!-- spring-boot-devtools -->
  16 + <dependency>
  17 + <groupId>org.springframework.boot</groupId>
  18 + <artifactId>spring-boot-devtools</artifactId>
  19 + <optional>true</optional> <!-- 表示依赖不会传递 -->
  20 + </dependency>
  21 +
  22 + <!-- Mysql驱动包 -->
  23 + <dependency>
  24 + <groupId>mysql</groupId>
  25 + <artifactId>mysql-connector-java</artifactId>
  26 + </dependency>
  27 +
  28 + <!-- 核心模块-->
  29 + <dependency>
  30 + <groupId>com.zhonglai.luhui</groupId>
  31 + <artifactId>ruoyi-framework</artifactId>
  32 + </dependency>
  33 + <!-- 代码生成模块-->
  34 + <dependency>
  35 + <groupId>com.zhonglai.luhui</groupId>
  36 + <artifactId>ruoyi-generator</artifactId>
  37 + </dependency>
  38 + <!-- 代码生成模块-->
  39 + <dependency>
  40 + <groupId>com.zhonglai.luhui</groupId>
  41 + <artifactId>lh-mqtt-service</artifactId>
  42 + </dependency>
  43 + <!-- 文档 -->
  44 + <dependency >
  45 + <groupId>io.springfox</groupId>
  46 + <artifactId>springfox-swagger2</artifactId>
  47 + <version>${swagger.version}</version>
  48 + <exclusions>
  49 + <exclusion>
  50 + <groupId>io.swagger</groupId>
  51 + <artifactId>swagger-models</artifactId>
  52 + </exclusion>
  53 + <exclusion>
  54 + <groupId>com.google.guava</groupId>
  55 + <artifactId>guava</artifactId>
  56 + </exclusion>
  57 + </exclusions>
  58 + </dependency>
  59 + <!--https://mvnrepository.com/artifact/io.swagger/swagger-models-->
  60 + <dependency>
  61 + <groupId>io.swagger</groupId>
  62 + <artifactId>swagger-models</artifactId>
  63 + <version>${swagger-models.version}</version>
  64 + </dependency>
  65 + <dependency>
  66 + <groupId>io.springfox</groupId>
  67 + <artifactId>springfox-swagger-ui</artifactId>
  68 + <version>${swagger.version}</version>
  69 + </dependency>
  70 + <!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui &ndash;&gt;-->
  71 + <dependency>
  72 + <groupId>com.github.xiaoymin</groupId>
  73 + <artifactId>swagger-bootstrap-ui</artifactId>
  74 + <version>${swagger-ui.version}</version>
  75 + </dependency>
  76 +
  77 + <dependency>
  78 + <groupId>org.aspectj</groupId>
  79 + <artifactId>aspectjweaver</artifactId>
  80 + </dependency>
  81 + <dependency>
  82 + <groupId>org.aspectj</groupId>
  83 + <artifactId>aspectjrt</artifactId>
  84 + </dependency>
  85 + </dependencies>
  86 +
  87 + <build>
  88 + <finalName>lh-api</finalName>
  89 + <plugins>
  90 + <plugin>
  91 + <groupId>org.apache.maven.plugins</groupId>
  92 + <artifactId>maven-jar-plugin</artifactId>
  93 + <version>2.4</version>
  94 + <configuration>
  95 + <archive>
  96 + <!--
  97 + 生成的jar中,不要包含pom.xml和pom.properties这两个文件
  98 + -->
  99 + <addMavenDescriptor>false</addMavenDescriptor>
  100 + <manifest>
  101 + <!--
  102 + 是否要把第三方jar放到manifest的classpath中
  103 + -->
  104 + <addClasspath>true</addClasspath>
  105 +
  106 + <!--
  107 + 生成的manifest中classpath的前缀,因为要把第三方jar放到lib目录下,所以classpath的前缀是lib/
  108 + -->
  109 + <classpathPrefix>lib/</classpathPrefix>
  110 + <mainClass>com.zhonglai.luhui.admin.AdminApplication</mainClass>
  111 + </manifest>
  112 + </archive>
  113 + </configuration>
  114 + </plugin>
  115 +
  116 + <!-- The configuration of maven-assembly-plugin -->
  117 + <plugin>
  118 + <groupId>org.apache.maven.plugins</groupId>
  119 + <artifactId>maven-assembly-plugin</artifactId>
  120 + <version>2.4</version>
  121 + <configuration>
  122 + <descriptors>
  123 + <descriptor>src/main/resources/package.xml</descriptor>
  124 + </descriptors>
  125 + </configuration>
  126 + <executions>
  127 + <execution>
  128 + <id>make-assembly</id>
  129 + <phase>package</phase>
  130 + <goals>
  131 + <goal>single</goal>
  132 + </goals>
  133 + </execution>
  134 + </executions>
  135 + </plugin>
  136 + </plugins>
  137 + </build>
  138 +</project>
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<project xmlns="http://maven.apache.org/POM/4.0.0"
  3 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5 + <parent>
  6 + <artifactId>Luhui</artifactId>
  7 + <groupId>com.zhonglai.luhui</groupId>
  8 + <version>1.0-SNAPSHOT</version>
  9 + </parent>
  10 + <modelVersion>4.0.0</modelVersion>
  11 +
  12 + <artifactId>lh-central-control</artifactId>
  13 +
  14 + <description>
  15 + 中控平台
  16 + </description>
  17 +
  18 + <dependencies>
  19 + <!-- spring-boot-devtools -->
  20 + <dependency>
  21 + <groupId>org.springframework.boot</groupId>
  22 + <artifactId>spring-boot-devtools</artifactId>
  23 + <optional>true</optional> <!-- 表示依赖不会传递 -->
  24 + </dependency>
  25 + <!-- SpringBoot Web容器 -->
  26 + <dependency>
  27 + <groupId>org.springframework.boot</groupId>
  28 + <artifactId>spring-boot-starter-web</artifactId>
  29 + </dependency>
  30 + <!-- Spring框架基本的核心工具 -->
  31 + <dependency>
  32 + <groupId>org.springframework</groupId>
  33 + <artifactId>spring-context-support</artifactId>
  34 + </dependency>
  35 + <!-- SpringWeb模块 -->
  36 + <dependency>
  37 + <groupId>org.springframework</groupId>
  38 + <artifactId>spring-web</artifactId>
  39 + </dependency>
  40 + <!-- servlet包 -->
  41 + <dependency>
  42 + <groupId>javax.servlet</groupId>
  43 + <artifactId>javax.servlet-api</artifactId>
  44 + </dependency>
  45 + <dependency>
  46 + <groupId>org.apache.commons</groupId>
  47 + <artifactId>commons-text</artifactId>
  48 + </dependency>
  49 +
  50 + <!-- 文档 -->
  51 + <dependency>
  52 + <groupId>io.springfox</groupId>
  53 + <artifactId>springfox-swagger2</artifactId>
  54 + <version>${swagger.version}</version>
  55 + <exclusions>
  56 + <exclusion>
  57 + <groupId>io.swagger</groupId>
  58 + <artifactId>swagger-models</artifactId>
  59 + </exclusion>
  60 + <exclusion>
  61 + <groupId>com.google.guava</groupId>
  62 + <artifactId>guava</artifactId>
  63 + </exclusion>
  64 + </exclusions>
  65 + </dependency>
  66 + <!--https://mvnrepository.com/artifact/io.swagger/swagger-models-->
  67 + <dependency>
  68 + <groupId>io.swagger</groupId>
  69 + <artifactId>swagger-models</artifactId>
  70 + <version>${swagger-models.version}</version>
  71 + </dependency>
  72 + <dependency>
  73 + <groupId>io.springfox</groupId>
  74 + <artifactId>springfox-swagger-ui</artifactId>
  75 + <version>${swagger.version}</version>
  76 + </dependency>
  77 + <!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui &ndash;&gt;-->
  78 + <dependency>
  79 + <groupId>com.github.xiaoymin</groupId>
  80 + <artifactId>swagger-bootstrap-ui</artifactId>
  81 + <version>${swagger-ui.version}</version>
  82 + </dependency>
  83 +
  84 + <!-- mqtt -->
  85 + <dependency>
  86 + <groupId>org.eclipse.paho</groupId>
  87 + <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
  88 + </dependency>
  89 +
  90 + <dependency>
  91 + <groupId>net.jodah</groupId>
  92 + <artifactId>expiringmap</artifactId>
  93 + </dependency>
  94 +
  95 +
  96 + <!-- 数据库 -->
  97 + <dependency>
  98 + <groupId>commons-dbcp</groupId>
  99 + <artifactId>commons-dbcp</artifactId>
  100 + <version>1.4</version>
  101 + </dependency>
  102 + <dependency>
  103 + <groupId>commons-dbutils</groupId>
  104 + <artifactId>commons-dbutils</artifactId>
  105 + <version>1.6</version>
  106 + </dependency>
  107 + <dependency>
  108 + <groupId>commons-pool</groupId>
  109 + <artifactId>commons-pool</artifactId>
  110 + <version>1.6</version>
  111 + </dependency>
  112 + <dependency>
  113 + <groupId>mysql</groupId>
  114 + <artifactId>mysql-connector-java</artifactId>
  115 + <version>8.0.17</version>
  116 + </dependency>
  117 +
  118 + <!-- 阿里JSON解析器 -->
  119 + <dependency>
  120 + <groupId>com.alibaba</groupId>
  121 + <artifactId>fastjson</artifactId>
  122 + </dependency>
  123 +
  124 + <!--常用工具类 -->
  125 + <dependency>
  126 + <groupId>org.apache.commons</groupId>
  127 + <artifactId>commons-lang3</artifactId>
  128 + </dependency>
  129 +
  130 + <!-- redis 缓存操作 -->
  131 + <dependency>
  132 + <groupId>org.springframework.boot</groupId>
  133 + <artifactId>spring-boot-starter-data-redis</artifactId>
  134 + <exclusions>
  135 + <exclusion>
  136 + <groupId>io.lettuce</groupId>
  137 + <artifactId>lettuce-core</artifactId>
  138 + </exclusion>
  139 + </exclusions>
  140 + </dependency>
  141 + <dependency>
  142 + <groupId>redis.clients</groupId>
  143 + <artifactId>jedis</artifactId>
  144 + </dependency>
  145 +
  146 + <!-- 通用工具-->
  147 + <dependency>
  148 + <groupId>com.zhonglai.luhui</groupId>
  149 + <artifactId>lh-domain</artifactId>
  150 + </dependency>
  151 +
  152 + </dependencies>
  153 +</project>
  1 +package com.zhonglai.luhui.central.control;
  2 +
  3 +public class LhCentralControlApplication {
  4 +}
  1 +package com.zhonglai.luhui.central.control.comm;
  2 +
  3 +
  4 +public class Message {
  5 + private int code;
  6 + private String message;
  7 + private Object data;
  8 +
  9 + public Message() {
  10 + }
  11 +
  12 + public Message(MessageCodeType code, String message, Object data) {
  13 + this.code = code.getCode();
  14 + this.message = message;
  15 + if (null == message || "".equals(message)) {
  16 + this.message = code.getMessage();
  17 + }
  18 +
  19 + this.data = data;
  20 + }
  21 +
  22 + public Message(MessageCodeType code, Object data) {
  23 + this.code = code.getCode();
  24 + this.message = code.getMessage();
  25 + this.data = data;
  26 + }
  27 +
  28 + public Message(MessageCodeType code, String message) {
  29 + this.code = code.getCode();
  30 + this.message = message;
  31 + this.data = null;
  32 + }
  33 +
  34 + public Message(MessageCodeType code) {
  35 + this.code = code.getCode();
  36 + this.message = code.getMessage();
  37 + }
  38 +
  39 + public void setCode(MessageCode messageCode )
  40 + {
  41 + code = messageCode.code;
  42 + }
  43 +
  44 + public void setCode(MessageCodeType code) {
  45 + this.code = code.getCode();
  46 + }
  47 +
  48 + public int getCode() {
  49 + return code;
  50 + }
  51 +
  52 + public void setCode(int code) {
  53 + this.code = code;
  54 + }
  55 +
  56 + public String getMessage() {
  57 + return message;
  58 + }
  59 +
  60 + public void setMessage(String message) {
  61 + this.message = message;
  62 + }
  63 +
  64 + public Object getData() {
  65 + return data;
  66 + }
  67 +
  68 + public void setData(Object data) {
  69 + this.data = data;
  70 + }
  71 +}
  1 +package com.zhonglai.luhui.central.control.comm;
  2 +
  3 +public enum MessageCode implements MessageCodeType{
  4 + DEFAULT_FAIL_CODE(0, "请求失败"),
  5 + DEFAULT_SUCCESS_CODE(1, "请求成功"),
  6 + SESSION_TIME_OUT(2, "会话超时,请刷新令牌"),
  7 + USER_INVALID(4, "用户失效,请重新登录"),
  8 + SYS_ERROR(3, "已知系统错误"),
  9 + REQUEST_METHOD_ERROR(6, "请求方式错误"),
  10 + REQUEST_PATH_ERROR(7, "请求路径错误"),
  11 + UNKNOWN_SYS_ERROR(5, "未知系统错误");
  12 +
  13 + public int code;
  14 + public String message;
  15 +
  16 + public int getCode() {
  17 + return this.code;
  18 + }
  19 +
  20 + public String getMessage() {
  21 + return this.message;
  22 + }
  23 +
  24 + private MessageCode(int code, String message) {
  25 + this.code = code;
  26 + this.message = message;
  27 + }
  28 +}
  1 +package com.zhonglai.luhui.central.control.comm;
  2 +
  3 +public interface MessageCodeType {
  4 + int getCode();
  5 +
  6 + String getMessage();
  7 +}
  1 +package com.zhonglai.luhui.central.control.comm;
  2 +
  3 +/**
  4 + * mqtt消息解析结果
  5 + */
  6 +public enum MqttAnalysisMessageResult {
  7 + /**
  8 + * 成功
  9 + */
  10 + Success,
  11 +
  12 + /**
  13 + * 失败
  14 + */
  15 + Fail,
  16 + /**
  17 + *topic异常
  18 + */
  19 + TopicException,
  20 +
  21 + /**
  22 + *设备不存在
  23 + */
  24 + DeviceDoesNotExist,
  25 +
  26 + /**
  27 + *payload解析异常
  28 + */
  29 + PayloadParsingException
  30 +}
  1 +package com.zhonglai.luhui.central.control.comm;
  2 +
  3 +
  4 +public class MyException extends RuntimeException{
  5 + private static final long serialVersionUID = 8827598182853467258L;
  6 + private Message errmge;
  7 +
  8 + public MyException(Message myMessage) {
  9 + super(myMessage.getMessage());
  10 + this.errmge = myMessage;
  11 + }
  12 +
  13 + public MyException(String message, Throwable cause) {
  14 + super(message, cause);
  15 + }
  16 + public MyException(String message) {
  17 + super(message);
  18 + }
  19 +
  20 +}
  1 +package com.zhonglai.luhui.central.control.comm;
  2 +
  3 +import org.slf4j.Logger;
  4 +import org.slf4j.LoggerFactory;
  5 +import org.springframework.beans.factory.annotation.Value;
  6 +import org.springframework.context.annotation.Configuration;
  7 +
  8 +import javax.annotation.PostConstruct;
  9 +
  10 +@Configuration
  11 +public class SysParameter {
  12 + private static Logger log = LoggerFactory.getLogger(SysParameter.class);
  13 +
  14 + public static String service_ip = ""; //服务所在地址
  15 +
  16 + @Value("${mqtt.topicconfig:/{{roleid}}/{{username}}/{{clientid}}/{{topicType}}/{{messageid}}}")
  17 + public String tempTopicconfig ; //topic 配置
  18 +
  19 + @Value("${mqtt.topics")
  20 + public String topics ; //topic
  21 +
  22 + public static String topicconfig ; //topic 配置
  23 +
  24 +
  25 + @PostConstruct
  26 + public void init() {
  27 + inittopicconfig();
  28 + }
  29 +
  30 + public void inittopicconfig()
  31 + {
  32 + topicconfig = tempTopicconfig;
  33 + }
  34 +
  35 +}
  1 +package com.zhonglai.luhui.central.control.comm;
  2 +
  3 +import org.apache.commons.lang3.StringUtils;
  4 +import org.slf4j.Logger;
  5 +import org.slf4j.LoggerFactory;
  6 +
  7 +import java.lang.reflect.Field;
  8 +import java.util.Optional;
  9 +
  10 +public class Topic {
  11 + private static final Logger log = LoggerFactory.getLogger(Topic.class);
  12 +
  13 + private String roleid;
  14 + private String username;
  15 + private String clientid;
  16 + private String topicType;
  17 + private String messageid;
  18 + private String payloadtype;
  19 +
  20 + public Topic() {
  21 + }
  22 +
  23 + public Topic(String roleid, String username, String clientid, String topicType, String payloadtype) {
  24 + this.roleid = roleid;
  25 + this.username = username;
  26 + this.clientid = clientid;
  27 + this.topicType = topicType;
  28 + this.payloadtype = payloadtype;
  29 + }
  30 +
  31 + public Topic(String roleid, String username, String clientid, String topicType, String messageid, String payloadtype) {
  32 + this.roleid = roleid;
  33 + this.username = username;
  34 + this.clientid = clientid;
  35 + this.topicType = topicType;
  36 + this.messageid = messageid;
  37 + this.payloadtype = payloadtype;
  38 + }
  39 +
  40 + public Topic(String topic)
  41 + {
  42 + topic = Optional.ofNullable(topic).orElseThrow(()->new MyException("topic为空"));
  43 + String[] sts = topic.split("/");
  44 + String[] config = SysParameter.topicconfig.split("/");
  45 + int number = sts.length;
  46 + if(number>config.length)
  47 + {
  48 + number = config.length;
  49 + }
  50 + for(int i=1;i<number;i++)
  51 + {
  52 + String cf = config[i].replace("{{","").replace("}}","");
  53 + try {
  54 + Field field = this.getClass().getDeclaredField(cf);
  55 + field.set(this,sts[i]);
  56 + } catch (NoSuchFieldException e) {
  57 + log.info("{}生成topic时没有属性{}",topic,cf);
  58 + } catch (IllegalAccessException e) {
  59 + log.info("{}生成topic时无法给{}赋值{}",topic,cf,sts[i]);
  60 + }
  61 + }
  62 +
  63 + if("ONLINE".equals(topicType.toUpperCase()))
  64 + {
  65 + this.payloadtype = "String";
  66 + }
  67 + }
  68 +
  69 + /**
  70 + * 生成缓存关键字
  71 + * @return
  72 + */
  73 + public String generateRedicKey()
  74 + {
  75 + return generate(":");
  76 + }
  77 +
  78 + /**
  79 + * 生成发送消息的topic
  80 + * @return
  81 + */
  82 + public String generateSendMessageTopic()
  83 + {
  84 + return "/"+generate("/");
  85 + }
  86 +
  87 + /**
  88 + * 生成客户端关键字
  89 + * @return
  90 + */
  91 + public String generateClienKey()
  92 + {
  93 + return "/"+generate("/");
  94 + }
  95 +
  96 + private String generate(String division)
  97 + {
  98 + String str = SysParameter.topicconfig;
  99 + if(StringUtils.isEmpty(roleid))
  100 + {
  101 + roleid = "2";
  102 + }
  103 + str = str.replace("/{{roleid}}",roleid+division);
  104 +
  105 + if(StringUtils.isEmpty(username))
  106 + {
  107 + username = "+";
  108 + }
  109 + str = str.replace("/{{username}}",username+division);
  110 +
  111 + if(StringUtils.isEmpty(clientid))
  112 + {
  113 + clientid = "+";
  114 + }
  115 + str = str.replace("/{{clientid}}",clientid+division);
  116 +
  117 + if(StringUtils.isEmpty(payloadtype))
  118 + {
  119 + payloadtype = "String";
  120 + }
  121 + str = str.replace("/{{payloadtype}}",payloadtype+division);
  122 +
  123 + if(StringUtils.isEmpty(topicType))
  124 + {
  125 + topicType = "PUT";
  126 + }
  127 + str = str.replace("/{{topicType}}",topicType+division);
  128 +
  129 + if(StringUtils.isNotEmpty(messageid))
  130 + {
  131 + str = str.replace("/{{messageid}}",messageid);
  132 + }
  133 +
  134 + return str;
  135 + }
  136 +
  137 + public String getRoleid() {
  138 + return roleid;
  139 + }
  140 +
  141 + public void setRoleid(String roleid) {
  142 + this.roleid = roleid;
  143 + }
  144 +
  145 + public String getUsername() {
  146 + return username;
  147 + }
  148 +
  149 + public void setUsername(String username) {
  150 + this.username = username;
  151 + }
  152 +
  153 + public String getClientid() {
  154 + return clientid;
  155 + }
  156 +
  157 + public void setClientid(String clientid) {
  158 + this.clientid = clientid;
  159 + }
  160 +
  161 + public String getTopicType() {
  162 + return topicType;
  163 + }
  164 +
  165 + public void setTopicType(String topicType) {
  166 + this.topicType = topicType;
  167 + }
  168 +
  169 + public String getMessageid() {
  170 + return messageid;
  171 + }
  172 +
  173 + public void setMessageid(String messageid) {
  174 + this.messageid = messageid;
  175 + }
  176 +
  177 + public String getPayloadtype() {
  178 + return payloadtype;
  179 + }
  180 +
  181 + public void setPayloadtype(String payloadtype) {
  182 + this.payloadtype = payloadtype;
  183 + }
  184 +}
  1 +package com.zhonglai.luhui.central.control.config;
  2 +
  3 +import org.springframework.beans.factory.annotation.Value;
  4 +import org.springframework.stereotype.Component;
  5 +
  6 +@Component
  7 +public class MqttConfig {
  8 + @Value("${mqtt.broker}")
  9 + private String broker;
  10 + @Value("${mqtt.clientId}")
  11 + private String clientId;
  12 + @Value("${mqtt.topics}")
  13 + private String topics;
  14 + @Value("${mqtt.username}")
  15 + private String username;
  16 + @Value("${mqtt.password}")
  17 + private String password;
  18 +
  19 + public String getBroker() {
  20 + return broker;
  21 + }
  22 +
  23 + public void setBroker(String broker) {
  24 + this.broker = broker;
  25 + }
  26 +
  27 + public String getClientId() {
  28 + return clientId;
  29 + }
  30 +
  31 + public void setClientId(String clientId) {
  32 + this.clientId = clientId;
  33 + }
  34 +
  35 + public String getTopics() {
  36 + return topics;
  37 + }
  38 +
  39 + public void setTopics(String topics) {
  40 + this.topics = topics;
  41 + }
  42 +
  43 + public String getUsername() {
  44 + return username;
  45 + }
  46 +
  47 + public void setUsername(String username) {
  48 + this.username = username;
  49 + }
  50 +
  51 + public String getPassword() {
  52 + return password;
  53 + }
  54 +
  55 + public void setPassword(String password) {
  56 + this.password = password;
  57 + }
  58 +}
  1 +package com.zhonglai.luhui.central.control.service;
  2 +
  3 +import com.ruoyi.system.domain.IotDevice;
  4 +
  5 +public interface DeviceService {
  6 + IotDevice getDeviceById(String clientId);
  7 +}
  1 +package com.zhonglai.luhui.central.control.service;
  2 +
  3 +import com.zhonglai.luhui.central.control.config.MqttConfig;
  4 +import com.zhonglai.luhui.central.control.util.ByteUtil;
  5 +import org.eclipse.paho.client.mqttv3.*;
  6 +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  7 +import org.slf4j.Logger;
  8 +import org.slf4j.LoggerFactory;
  9 +import org.springframework.beans.factory.annotation.Autowired;
  10 +import org.springframework.stereotype.Service;
  11 +
  12 +import javax.annotation.PostConstruct;
  13 +
  14 +@Service
  15 +public class MqttClientService {
  16 + private Logger log = LoggerFactory.getLogger(MqttClientService.class);
  17 +
  18 + @Autowired
  19 + private MqttConfig mqttConfig;
  20 +
  21 + @Autowired
  22 + private MqttMessageArrivedService mqttMessageArrivedService;
  23 +
  24 + @Autowired
  25 + private MqttOperation mqttOperation;
  26 +
  27 + private MqttClient mqttclient;
  28 +
  29 + private MqttConnectOptions options;
  30 +
  31 + {
  32 + if(null == mqttclient)
  33 + {
  34 + try {
  35 + mqttclient = new MqttClient(mqttConfig.getBroker(), mqttConfig.getClientId(), new MemoryPersistence());
  36 + } catch (MqttException e) {
  37 + e.printStackTrace();
  38 + }
  39 + options = new MqttConnectOptions();
  40 + options.setCleanSession(true);
  41 + options.setConnectionTimeout(15);
  42 + //设置断开后重新连接
  43 + options.setAutomaticReconnect(true);
  44 + mqttclient.setCallback(new MqttCallbackExtended() {
  45 + @Override
  46 + public void connectComplete(boolean b, String s) {
  47 + log.info("连接成功");
  48 + try {
  49 + subscribe();
  50 + } catch (MqttException e) {
  51 + e.printStackTrace();
  52 + }
  53 + }
  54 +
  55 + @Override
  56 + public void connectionLost(Throwable cause) {
  57 + log.error("连接丢失",cause);
  58 + }
  59 +
  60 + @Override
  61 + public void messageArrived(String topic, MqttMessage message) {
  62 + log.info("接收到消息topc:{}, mqttMessage {},payload 十六进制 {}",topic,message, ByteUtil.hexStringToSpace(ByteUtil.toHexString(message.getPayload())));
  63 + mqttMessageArrivedService.analysisMessage(topic,message);
  64 + }
  65 +
  66 + @Override
  67 + public void deliveryComplete(IMqttDeliveryToken token) {
  68 + try {
  69 + log.info("成功发出消息 messageid{}",token.getMessage());
  70 + } catch (MqttException e) {
  71 + e.printStackTrace();
  72 + }
  73 + }
  74 + });
  75 + }
  76 +
  77 + }
  78 +
  79 + @PostConstruct
  80 + public void init() throws MqttException {
  81 + log.info("-----------终端数据模型配置成功--------------------");
  82 + connect();
  83 + log.info("-----------mqtt连接服务器成功--------------------");
  84 + subscribe();
  85 + log.info("-----------订阅{}成功--------------------",mqttConfig.getTopics());
  86 + }
  87 +
  88 + private void connect() throws MqttException {
  89 + options.setUserName(mqttConfig.getUsername());
  90 + options.setPassword(mqttConfig.getPassword().toCharArray());
  91 + mqttclient.connect(options);
  92 + }
  93 +
  94 + private void subscribe() throws MqttException {
  95 + mqttOperation.subscribe(mqttclient,mqttConfig.getTopics().split(","));
  96 + }
  97 +
  98 +}
  1 +package com.zhonglai.luhui.central.control.service;
  2 +
  3 +import com.ruoyi.system.domain.IotDevice;
  4 +import com.zhonglai.luhui.central.control.comm.MqttAnalysisMessageResult;
  5 +import com.zhonglai.luhui.central.control.comm.Topic;
  6 +import org.eclipse.paho.client.mqttv3.MqttMessage;
  7 +import org.slf4j.Logger;
  8 +import org.slf4j.LoggerFactory;
  9 +import org.springframework.beans.factory.annotation.Autowired;
  10 +import org.springframework.stereotype.Service;
  11 +
  12 +/**
  13 + * 数据解析业务
  14 + */
  15 +@Service
  16 +public class MqttMessageArrivedService {
  17 + @Autowired
  18 + private DeviceService deviceService ;
  19 +
  20 + private Logger log = LoggerFactory.getLogger(MqttMessageArrivedService.class);
  21 +
  22 + public MqttAnalysisMessageResult analysisMessage(String topicStr, MqttMessage message)
  23 + {
  24 + Topic topic = new Topic(topicStr);
  25 + if(null == topic)
  26 + {
  27 + log.error("消息{},解析出来的topic为空,不做解析",topicStr);
  28 + return MqttAnalysisMessageResult.TopicException;
  29 + }
  30 +
  31 + IotDevice iotDevice = deviceService.getDeviceById(topic.getClientid());
  32 + if(null == iotDevice)
  33 + {
  34 + log.info("设备{}不存在",topic.getClientid());
  35 + return MqttAnalysisMessageResult.DeviceDoesNotExist;
  36 + }
  37 +
  38 + //消息分发
  39 + try {
  40 +// messageDistribution();
  41 + }catch (Exception e)
  42 + {
  43 + log.info("消息解析异常",e);
  44 + return MqttAnalysisMessageResult.PayloadParsingException;
  45 + }
  46 +
  47 + return MqttAnalysisMessageResult.Success;
  48 + }
  49 +
  50 +}
  1 +package com.zhonglai.luhui.central.control.service;
  2 +
  3 +import org.eclipse.paho.client.mqttv3.MqttClient;
  4 +import org.eclipse.paho.client.mqttv3.MqttException;
  5 +import org.eclipse.paho.client.mqttv3.MqttMessage;
  6 +import org.springframework.stereotype.Service;
  7 +
  8 +import java.nio.ByteBuffer;
  9 +import java.nio.charset.Charset;
  10 +
  11 +@Service
  12 +public class MqttOperation {
  13 + public void subscribe(MqttClient mqttclient,String[] topicFilters) throws MqttException {
  14 + mqttclient.subscribe(topicFilters);
  15 + }
  16 +
  17 + public void publish(MqttClient mqttclient,String topic, MqttMessage message) throws MqttException {
  18 + mqttclient.publish(topic,message);
  19 + }
  20 +
  21 + public void publish(MqttClient mqttclient,String topic, String messageStr) throws MqttException {
  22 + MqttMessage message = new MqttMessage();
  23 + message.setPayload(messageStr.getBytes());
  24 + mqttclient.publish(topic,message);
  25 + }
  26 +
  27 + public void closeClient (MqttClient mqttclient,String clientId,String code,String messageStr) throws MqttException {
  28 + String topic = "SYSOPERATION/CLOSE";
  29 + MqttMessage message = new MqttMessage();
  30 + Charset charset = Charset.forName("utf-8");
  31 + ByteBuffer payload = charset.encode(clientId+","+code+","+messageStr);
  32 + message.setPayload(payload.array());
  33 + mqttclient.publish(topic,message);
  34 + }
  35 +}
  1 +package com.zhonglai.luhui.central.control.util;
  2 +
  3 +import java.util.Arrays;
  4 +
  5 +public class ByteUtil {
  6 + /**
  7 + * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用
  8 + *
  9 + * @param src
  10 + * byte数组
  11 + * @param offset
  12 + * 从数组的第offset位开始
  13 + * @return int数值
  14 + */
  15 + public static long bytesToLongASC(byte[] src, int offset,int lenth) {
  16 + int value = 0;
  17 + for(int i=0;i<lenth;i++)
  18 + {
  19 + value = value | ((src[offset+i] & 0xFF)<<(8*i));
  20 + }
  21 + return value;
  22 + }
  23 +
  24 + /**
  25 + * 把16进制字符串转换成字节数组
  26 + *
  27 + * @param hex
  28 + * @return
  29 + */
  30 + public static byte[] hexStringToByte(String hex) {
  31 + int len = (hex.length() / 2);
  32 + byte[] result = new byte[len];
  33 + char[] achar = hex.toCharArray();
  34 + for (int i = 0; i < len; i++) {
  35 + int pos = i * 2;
  36 + result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
  37 + }
  38 + return result;
  39 + }
  40 + private static byte toByte(char c) {
  41 + byte b = (byte) "0123456789ABCDEF".indexOf(c);
  42 + return b;
  43 + }
  44 +
  45 + /**
  46 + * 把16进制字符串转换成字节数组
  47 + *
  48 + * @param hex
  49 + * @return
  50 + */
  51 + public static String hexStringToSpace(String hex) {
  52 + if (null == hex) {
  53 + return null;
  54 + } else {
  55 + StringBuilder sb = new StringBuilder(hex.length() << 1);
  56 +
  57 + for(int i = 0; i < hex.length(); i+=2) {
  58 + sb.append(hex.substring(i,i+2)).append(" ");
  59 + }
  60 + return sb.toString();
  61 + }
  62 + }
  63 +
  64 + /**
  65 + * 把原数组加点目标数组后面
  66 + * @param dest 目标数组
  67 + * @param src 原数组
  68 + * @return
  69 + */
  70 + public static byte[] addBytes(byte[] dest,byte[] src )
  71 + {
  72 + int dl = dest.length;
  73 + int sl = src.length;
  74 + dest = Arrays.copyOf(dest, dl+sl);//数组扩容
  75 + System.arraycopy(src,0,dest,dl,src.length);
  76 + return dest;
  77 + }
  78 +
  79 + /**
  80 + * 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。 和bytesToInt2()配套使用
  81 + */
  82 + public static byte[] intToBytesDESC(long value,int lenth)
  83 + {
  84 + byte[] src = new byte[lenth];
  85 + for(int i=0;i<lenth;i++)
  86 + {
  87 + src[i] = (byte) ((value>>(8*(lenth-i-1))) & 0xFF);
  88 + }
  89 + return src;
  90 + }
  91 +
  92 + /**
  93 + * 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。 和bytesToInt()配套使用
  94 + * @param value
  95 + * 要转换的int值
  96 + * @return byte数组
  97 + */
  98 + public static byte[] intToBytesASC( long value,int lenth)
  99 + {
  100 + byte[] src = new byte[lenth];
  101 + for(int i=lenth;i>0;i--)
  102 + {
  103 + src[i-1] = (byte) ((value>>(8*(i-1))) & 0xFF);
  104 + }
  105 + return src;
  106 + }
  107 +
  108 + public static void main(String[] args) {
  109 + System.out.println(ByteUtil.toHexString( ByteUtil.intToBytesASC(2011239256,4)));
  110 + }
  111 +
  112 + /**
  113 + * ip转化位4byte
  114 + * @param ip
  115 + * @return
  116 + */
  117 + public static byte[] ipTo4Byte(String ip)
  118 + {
  119 + String[] ips = ip.split(".");
  120 + return new byte[]{(byte) Integer.parseInt(ips[0]),(byte) Integer.parseInt(ips[1]),(byte) Integer.parseInt(ips[2]),(byte) Integer.parseInt(ips[3])};
  121 + }
  122 +
  123 + /**
  124 + * byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。和intToBytes2()配套使用
  125 + */
  126 + public static long bytesToLongDESC(byte[] src, int offset,int lenth) {
  127 + long value = 0;
  128 + for(int i=lenth;i>0;i--)
  129 + {
  130 + value = value | ((src[offset+(lenth-i)] & 0xFF)<<(8*(i-1)));
  131 + }
  132 + return value;
  133 + }
  134 +
  135 + private static final char[] hex = "0123456789abcdef".toCharArray();
  136 + public static String toHexString(byte[] bytes) {
  137 + if (null == bytes) {
  138 + return null;
  139 + } else {
  140 + StringBuilder sb = new StringBuilder(bytes.length << 1);
  141 +
  142 + for(int i = 0; i < bytes.length; ++i) {
  143 + sb.append(hex[(bytes[i] & 240) >> 4]).append(hex[bytes[i] & 15]);
  144 + }
  145 +
  146 + return sb.toString();
  147 + }
  148 + }
  149 +
  150 + /**
  151 + * 计算CRC16/Modbus校验码 低位在前,高位在后
  152 + *
  153 + * @param str 十六进制字符串
  154 + * @return
  155 + */
  156 + public static String getCRC16(String str) {
  157 + byte[] bytes = hexStringToByte(str);
  158 + return getCRC16(bytes);
  159 + }
  160 +
  161 + /**
  162 + * 计算CRC16/Modbus校验码 低位在前,高位在后
  163 + *
  164 + * @return
  165 + */
  166 + public static String getCRC16( byte[] bytes) {
  167 + int CRC = 0x0000ffff;
  168 + int POLYNOMIAL = 0x0000a001;
  169 +
  170 + int i, j;
  171 + for (i = 0; i < bytes.length; i++) {
  172 + CRC ^= ((int) bytes[i] & 0x000000ff);
  173 + for (j = 0; j < 8; j++) {
  174 + if ((CRC & 0x00000001) != 0) {
  175 + CRC >>= 1;
  176 + CRC ^= POLYNOMIAL;
  177 + } else {
  178 + CRC >>= 1;
  179 + }
  180 + }
  181 + }
  182 + String crc = Integer.toHexString(CRC);
  183 + if (crc.length() == 2) {
  184 + crc = "00" + crc;
  185 + } else if (crc.length() == 3) {
  186 + crc = "0" + crc;
  187 + }
  188 + crc = crc.substring(2, 4) + crc.substring(0, 2);
  189 + return crc.toUpperCase();
  190 + }
  191 +}
@@ -44,7 +44,7 @@ public class IotDevice implements Serializable @@ -44,7 +44,7 @@ public class IotDevice implements Serializable
44 44
45 /** 固件版本 */ 45 /** 固件版本 */
46 @ApiModelProperty("固件版本") 46 @ApiModelProperty("固件版本")
47 - private Float firmware_version; 47 + private String firmware_version;
48 48
49 /** 图片地址 */ 49 /** 图片地址 */
50 @ApiModelProperty("图片地址") 50 @ApiModelProperty("图片地址")
@@ -120,6 +120,28 @@ public class IotDevice implements Serializable @@ -120,6 +120,28 @@ public class IotDevice implements Serializable
120 @ApiModelProperty("描述") 120 @ApiModelProperty("描述")
121 private String remark; 121 private String remark;
122 122
  123 + @ApiModelProperty("设备生命周期")
  124 + private Long device_life;
  125 +
  126 + @ApiModelProperty("数据更新时间")
  127 + private Integer data_update_time;
  128 +
  129 + public Integer getData_update_time() {
  130 + return data_update_time;
  131 + }
  132 +
  133 + public void setData_update_time(Integer data_update_time) {
  134 + this.data_update_time = data_update_time;
  135 + }
  136 +
  137 + public Long getDevice_life() {
  138 + return device_life;
  139 + }
  140 +
  141 + public void setDevice_life(Long device_life) {
  142 + this.device_life = device_life;
  143 + }
  144 +
123 public String getListen_service_ip() { 145 public String getListen_service_ip() {
124 return listen_service_ip; 146 return listen_service_ip;
125 } 147 }
@@ -199,12 +221,12 @@ public class IotDevice implements Serializable @@ -199,12 +221,12 @@ public class IotDevice implements Serializable
199 { 221 {
200 return del_flag; 222 return del_flag;
201 } 223 }
202 - public void setFirmware_version(Float firmware_version) 224 + public void setFirmware_version(String firmware_version)
203 { 225 {
204 this.firmware_version = firmware_version; 226 this.firmware_version = firmware_version;
205 } 227 }
206 228
207 - public Float getFirmware_version() 229 + public String getFirmware_version()
208 { 230 {
209 return firmware_version; 231 return firmware_version;
210 } 232 }
  1 +package com.ruoyi.system.domain;
  2 +
  3 +import com.ruoyi.system.domain.tool.BaseEntity;
  4 +import io.swagger.annotations.ApiModel;
  5 +import io.swagger.annotations.ApiModelProperty;
  6 +import org.apache.commons.lang3.builder.ToStringBuilder;
  7 +import org.apache.commons.lang3.builder.ToStringStyle;
  8 +
  9 +/**
  10 + * 产品指标翻译对象 iot_product_translate
  11 + *
  12 + * @author 钟来
  13 + * @date 2022-11-04
  14 + */
  15 +@ApiModel("产品指标翻译")
  16 +public class IotProductTranslate extends BaseEntity
  17 +{
  18 + private static final long serialVersionUID = 1L;
  19 +
  20 + /** 创建时间 */
  21 + @ApiModelProperty("创建时间")
  22 + private Integer create_time;
  23 +
  24 + /** 主键 */
  25 + @ApiModelProperty("主键")
  26 + private Integer id;
  27 +
  28 + /** 模型标识 */
  29 + @ApiModelProperty("模型标识")
  30 + private String model_identifier;
  31 +
  32 + /** 产品id */
  33 + @ApiModelProperty("产品id")
  34 + private Integer product_id;
  35 +
  36 + /** 翻译的模型标识(支持两层josn键值,用英文点分割) */
  37 + @ApiModelProperty("翻译的模型标识(支持两层josn键值,用英文点分割如:11:start)")
  38 + private String translate_identifier;
  39 +
  40 + public void setCreate_time(Integer create_time)
  41 + {
  42 + this.create_time = create_time;
  43 + }
  44 +
  45 + public Integer getCreate_time()
  46 + {
  47 + return create_time;
  48 + }
  49 + public void setId(Integer id)
  50 + {
  51 + this.id = id;
  52 + }
  53 +
  54 + public Integer getId()
  55 + {
  56 + return id;
  57 + }
  58 + public void setModel_identifier(String model_identifier)
  59 + {
  60 + this.model_identifier = model_identifier;
  61 + }
  62 +
  63 + public String getModel_identifier()
  64 + {
  65 + return model_identifier;
  66 + }
  67 + public void setProduct_id(Integer product_id)
  68 + {
  69 + this.product_id = product_id;
  70 + }
  71 +
  72 + public Integer getProduct_id()
  73 + {
  74 + return product_id;
  75 + }
  76 + public void setTranslate_identifier(String translate_identifier)
  77 + {
  78 + this.translate_identifier = translate_identifier;
  79 + }
  80 +
  81 + public String getTranslate_identifier()
  82 + {
  83 + return translate_identifier;
  84 + }
  85 +
  86 + @Override
  87 + public String toString() {
  88 + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
  89 + .append("create_time", getCreate_time())
  90 + .append("id", getId())
  91 + .append("model_identifier", getModel_identifier())
  92 + .append("product_id", getProduct_id())
  93 + .append("translate_identifier", getTranslate_identifier())
  94 + .toString();
  95 + }
  96 +}
@@ -46,6 +46,16 @@ public class IotTerminal implements Serializable @@ -46,6 +46,16 @@ public class IotTerminal implements Serializable
46 @ApiModelProperty("产品名称") 46 @ApiModelProperty("产品名称")
47 private String mqtt_username; 47 private String mqtt_username;
48 48
  49 + @ApiModelProperty("数据更新时间")
  50 + private Integer data_update_time;
  51 +
  52 + public Integer getData_update_time() {
  53 + return data_update_time;
  54 + }
  55 +
  56 + public void setData_update_time(Integer data_update_time) {
  57 + this.data_update_time = data_update_time;
  58 + }
49 public Integer getProduct_id() { 59 public Integer getProduct_id() {
50 return product_id; 60 return product_id;
51 } 61 }
@@ -21,14 +21,14 @@ @@ -21,14 +21,14 @@
21 # rssi 设备强度(信号极好[-55— 0],信号好[-70— -55],信号一般[-85— -70],信号差[-100— -85]) 21 # rssi 设备强度(信号极好[-55— 0],信号好[-70— -55],信号一般[-85— -70],信号差[-100— -85])
22 # status 设备状态,固定为3,表示在线 22 # status 设备状态,固定为3,表示在线
23 # userId 用户的ID,1=admin 23 # userId 用户的ID,1=admin
24 -# firmwareVersion 固件版本 24 +# firmware_version 固件版本
25 # longitude 经度,可选,使用设备定位时需要上传 25 # longitude 经度,可选,使用设备定位时需要上传
26 # latitude 纬度,可选,使用设备定位时需要上传 26 # latitude 纬度,可选,使用设备定位时需要上传
27 # summary 摘要,可选,设备的配置信息等,json格式,对象可自定义 27 # summary 摘要,可选,设备的配置信息等,json格式,对象可自定义
28 { 28 {
29 "0":{ 29 "0":{
30 "rssi": -43, 30 "rssi": -43,
31 - "firmwareVersion": 1.2, 31 + "firmware_version": 1.2,
32 "longitude": 0, 32 "longitude": 0,
33 "latitude": 0, 33 "latitude": 0,
34 "summary": { 34 "summary": {
@@ -134,7 +134,7 @@ @@ -134,7 +134,7 @@
134 { 134 {
135 "0":{ 135 "0":{
136 "restart": 1, 136 "restart": 1,
137 - "firmwareVersion": 1.2, 137 + "firmware_version": 1.2,
138 "longitude": 0, 138 "longitude": 0,
139 "latitude": 0, 139 "latitude": 0,
140 "summary": { 140 "summary": {
@@ -139,8 +139,17 @@ @@ -139,8 +139,17 @@
139 <dependency> 139 <dependency>
140 <groupId>org.springframework.boot</groupId> 140 <groupId>org.springframework.boot</groupId>
141 <artifactId>spring-boot-starter-data-redis</artifactId> 141 <artifactId>spring-boot-starter-data-redis</artifactId>
  142 + <exclusions>
  143 + <exclusion>
  144 + <groupId>io.lettuce</groupId>
  145 + <artifactId>lettuce-core</artifactId>
  146 + </exclusion>
  147 + </exclusions>
  148 + </dependency>
  149 + <dependency>
  150 + <groupId>redis.clients</groupId>
  151 + <artifactId>jedis</artifactId>
142 </dependency> 152 </dependency>
143 -  
144 <!-- Token生成与解析--> 153 <!-- Token生成与解析-->
145 <dependency> 154 <dependency>
146 <groupId>io.jsonwebtoken</groupId> 155 <groupId>io.jsonwebtoken</groupId>
1 package com.zhonglai.luhui.mqtt.comm.agreement; 1 package com.zhonglai.luhui.mqtt.comm.agreement;
2 2
3 -import com.alibaba.fastjson.JSONObject;  
4 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement; 3 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;
5 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreementFactory; 4 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreementFactory;
6 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 5 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
1 package com.zhonglai.luhui.mqtt.comm.config; 1 package com.zhonglai.luhui.mqtt.comm.config;
2 2
3 import com.fasterxml.jackson.annotation.JsonAutoDetect; 3 import com.fasterxml.jackson.annotation.JsonAutoDetect;
  4 +import com.fasterxml.jackson.annotation.JsonTypeInfo;
4 import com.fasterxml.jackson.annotation.PropertyAccessor; 5 import com.fasterxml.jackson.annotation.PropertyAccessor;
5 import com.fasterxml.jackson.databind.ObjectMapper; 6 import com.fasterxml.jackson.databind.ObjectMapper;
6 import org.springframework.beans.factory.annotation.Value; 7 import org.springframework.beans.factory.annotation.Value;
@@ -54,7 +55,7 @@ public class RedisConfig { @@ -54,7 +55,7 @@ public class RedisConfig {
54 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 55 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
55 ObjectMapper om = new ObjectMapper(); 56 ObjectMapper om = new ObjectMapper();
56 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 57 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
57 - om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 58 + om.activateDefaultTyping(om.getPolymorphicTypeValidator(),ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
58 jackson2JsonRedisSerializer.setObjectMapper(om); 59 jackson2JsonRedisSerializer.setObjectMapper(om);
59 //普通的值采用jackson方式自动序列化 60 //普通的值采用jackson方式自动序列化
60 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); 61 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
@@ -13,12 +13,16 @@ import com.zhonglai.luhui.mqtt.dto.topic.AddPostDto; @@ -13,12 +13,16 @@ import com.zhonglai.luhui.mqtt.dto.topic.AddPostDto;
13 import com.zhonglai.luhui.mqtt.service.db.DeviceService; 13 import com.zhonglai.luhui.mqtt.service.db.DeviceService;
14 import org.slf4j.Logger; 14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory; 15 import org.slf4j.LoggerFactory;
  16 +import org.springframework.beans.BeanUtils;
  17 +import org.springframework.beans.BeanWrapper;
  18 +import org.springframework.beans.BeanWrapperImpl;
16 import org.springframework.beans.factory.annotation.Autowired; 19 import org.springframework.beans.factory.annotation.Autowired;
17 import org.springframework.beans.factory.annotation.Value; 20 import org.springframework.beans.factory.annotation.Value;
18 import org.springframework.stereotype.Service; 21 import org.springframework.stereotype.Service;
19 22
20 -import java.util.ArrayList;  
21 -import java.util.List; 23 +import java.beans.PropertyDescriptor;
  24 +import java.lang.reflect.Field;
  25 +import java.util.*;
22 26
23 /** 27 /**
24 * 业务数据更新服务 28 * 业务数据更新服务
@@ -50,11 +54,6 @@ public class BusinessDataUpdateService { @@ -50,11 +54,6 @@ public class BusinessDataUpdateService {
50 */ 54 */
51 public void updataDta(Type type,Topic topic, JSONObject data,boolean isOperLog,List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list) 55 public void updataDta(Type type,Topic topic, JSONObject data,boolean isOperLog,List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list)
52 { 56 {
53 - if(1==deviceService.getlockIotDevice(topic.getClientid()))  
54 - {  
55 - logger.info("设备锁定等待解锁");  
56 - return;  
57 - }  
58 IotDevice olddevice = deviceService.getRedicDevice(topic.getClientid()); 57 IotDevice olddevice = deviceService.getRedicDevice(topic.getClientid());
59 58
60 for(String key:data.keySet()) 59 for(String key:data.keySet())
@@ -77,11 +76,15 @@ public class BusinessDataUpdateService { @@ -77,11 +76,15 @@ public class BusinessDataUpdateService {
77 { 76 {
78 iotDevice.setStatus(3); 77 iotDevice.setStatus(3);
79 } 78 }
  79 + iotDevice.setDevice_life(olddevice.getDevice_life());
  80 + iotDevice.setData_update_time(DateUtils.getNowTimeMilly());
  81 + iotDevice.setName(olddevice.getName());
80 deviceService.updataDevice(iotDevice); 82 deviceService.updataDevice(iotDevice);
81 }else{ //终端 83 }else{ //终端
82 IotTerminal iotTerminal = translateTerminal(type,key,olddevice,jsData,isOperLog,operateHisList,list); 84 IotTerminal iotTerminal = translateTerminal(type,key,olddevice,jsData,isOperLog,operateHisList,list);
83 logger.info("更新终端数据{}",iotTerminal); 85 logger.info("更新终端数据{}",iotTerminal);
84 - deviceService.updataTerminal(iotTerminal); 86 + iotTerminal.setData_update_time(DateUtils.getNowTimeMilly());
  87 + deviceService.updataTerminal(iotTerminal,olddevice.getDevice_life());
85 } 88 }
86 } 89 }
87 } 90 }
@@ -106,10 +109,7 @@ public class BusinessDataUpdateService { @@ -106,10 +109,7 @@ public class BusinessDataUpdateService {
106 jsData.remove("summary"); 109 jsData.remove("summary");
107 } 110 }
108 IotDevice device = JSONObject.parseObject(JSONObject.toJSONString(jsData),IotDevice.class); 111 IotDevice device = JSONObject.parseObject(JSONObject.toJSONString(jsData),IotDevice.class);
109 - device.setClient_id(olddevice.getClient_id());  
110 - device.setUpdate_time(DateUtils.getNowTimeMilly());  
111 - device.setMqtt_username(olddevice.getMqtt_username());  
112 - device.setProduct_id(olddevice.getProduct_id()); 112 + device = (IotDevice) mergerData(olddevice,device);
113 if(null != summaryObjec) 113 if(null != summaryObjec)
114 { 114 {
115 device.setSummary(summaryObjec.toString()); 115 device.setSummary(summaryObjec.toString());
@@ -148,7 +148,6 @@ public class BusinessDataUpdateService { @@ -148,7 +148,6 @@ public class BusinessDataUpdateService {
148 SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( id,olddevice.getMqtt_username(),jsData,"终端本地",isOperLog,operateHisList,list); 148 SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( id,olddevice.getMqtt_username(),jsData,"终端本地",isOperLog,operateHisList,list);
149 IotTerminal terminal = new IotTerminal(); 149 IotTerminal terminal = new IotTerminal();
150 terminal.setId(id); 150 terminal.setId(id);
151 - terminal.setUpdate_time(DateUtils.getNowTimeMilly());  
152 terminal.setDevice_id(olddevice.getClient_id()); 151 terminal.setDevice_id(olddevice.getClient_id());
153 terminal.setProduct_id(olddevice.getProduct_id()); 152 terminal.setProduct_id(olddevice.getProduct_id());
154 terminal.setMqtt_username(olddevice.getMqtt_username()); 153 terminal.setMqtt_username(olddevice.getMqtt_username());
@@ -162,7 +161,7 @@ public class BusinessDataUpdateService { @@ -162,7 +161,7 @@ public class BusinessDataUpdateService {
162 oldterminal.setMqtt_username(olddevice.getMqtt_username()); 161 oldterminal.setMqtt_username(olddevice.getMqtt_username());
163 oldterminal.setName(olddevice.getMqtt_username()+"终端"+key); 162 oldterminal.setName(olddevice.getMqtt_username()+"终端"+key);
164 oldterminal.setProduct_id(olddevice.getProduct_id()); 163 oldterminal.setProduct_id(olddevice.getProduct_id());
165 - deviceService.updataTerminal(oldterminal); 164 + deviceService.updataTerminal(oldterminal,olddevice.getDevice_life());
166 } 165 }
167 if(null != oldterminal && ("ADD".equals(type.name())|| "READ".equals(type.name()))) 166 if(null != oldterminal && ("ADD".equals(type.name())|| "READ".equals(type.name())))
168 { 167 {
@@ -177,7 +176,7 @@ public class BusinessDataUpdateService { @@ -177,7 +176,7 @@ public class BusinessDataUpdateService {
177 } 176 }
178 String str = (null!=oldterminal?oldterminal.getThings_model_config():null); 177 String str = (null!=oldterminal?oldterminal.getThings_model_config():null);
179 terminal.setThings_model_config(deviceService.getNewAdddate(str,saveDataDto.getConfig()).toJSONString()); 178 terminal.setThings_model_config(deviceService.getNewAdddate(str,saveDataDto.getConfig()).toJSONString());
180 - 179 + terminal.setName(oldterminal.getName());
181 return terminal; 180 return terminal;
182 } 181 }
183 182
@@ -185,4 +184,54 @@ public class BusinessDataUpdateService { @@ -185,4 +184,54 @@ public class BusinessDataUpdateService {
185 { 184 {
186 ADD,ALL 185 ADD,ALL
187 } 186 }
  187 +
  188 + public static void main(String[] args) {
  189 + IotDevice sourceBean = new IotDevice();
  190 + sourceBean.setName("sss");
  191 + sourceBean.setUpdate_time(21313);
  192 + IotDevice targetBean = new IotDevice();
  193 + targetBean.setClient_id("21321");
  194 + targetBean.setName("bbb");
  195 + Object newO = mergerData(sourceBean,targetBean);
  196 + System.out.println(JSONObject.toJSONString(newO));
  197 + }
  198 +
  199 + private static Object mergerData(Object sourceBean, Object targetBean)
  200 + {
  201 + if(null == sourceBean)
  202 + {
  203 + return targetBean;
  204 + }
  205 + if(null == targetBean)
  206 + {
  207 + return sourceBean;
  208 + }
  209 + Object newtargetBean = BeanUtils.instantiateClass(targetBean.getClass());
  210 + BeanUtils.copyProperties(targetBean,newtargetBean);
  211 + BeanUtils.copyProperties(sourceBean,newtargetBean,getNotNullField(newtargetBean));
  212 + return newtargetBean;
  213 + }
  214 +
  215 + /**
  216 + * 获取属性中为空的字段
  217 + *
  218 + * @param target
  219 + * @return
  220 + */
  221 + private static String[] getNotNullField(Object target) {
  222 + BeanWrapper beanWrapper = new BeanWrapperImpl(target);
  223 + PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
  224 + Set<String> notNullFieldSet = new HashSet<>();
  225 + if (propertyDescriptors.length > 0) {
  226 + for (PropertyDescriptor p : propertyDescriptors) {
  227 + String name = p.getName();
  228 + Object value = beanWrapper.getPropertyValue(name);
  229 + if (Objects.nonNull(value)) {
  230 + notNullFieldSet.add(name);
  231 + }
  232 + }
  233 + }
  234 + String[] notNullField = new String[notNullFieldSet.size()];
  235 + return notNullFieldSet.toArray(notNullField);
  236 + }
188 } 237 }
@@ -41,7 +41,12 @@ public class DataModeAnalysisService { @@ -41,7 +41,12 @@ public class DataModeAnalysisService {
41 */ 41 */
42 public void initDataThingsMode(String roleIds,String usernames) 42 public void initDataThingsMode(String roleIds,String usernames)
43 { 43 {
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 AND b.`role_id` IN("+roleIds+")"; 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 ";
  45 + if(StringUtils.isNotEmpty(roleIds))
  46 + {
  47 + sql += " AND b.`role_id` IN("+roleIds+")";
  48 + }
  49 +
45 if(StringUtils.isNotEmpty(usernames)) 50 if(StringUtils.isNotEmpty(usernames))
46 { 51 {
47 sql += " AND b.`username` IN("+usernames+")"; 52 sql += " AND b.`username` IN("+usernames+")";
@@ -108,11 +113,19 @@ public class DataModeAnalysisService { @@ -108,11 +113,19 @@ public class DataModeAnalysisService {
108 operateHisList.add(dviceLogService.newLogDeviceOperation(id,thingsModelBase.getSaveView(),null,controlModel+thingsModelItemBase.getName()+"为"+thingsModelBase.getView(),jsData.toString())); 113 operateHisList.add(dviceLogService.newLogDeviceOperation(id,thingsModelBase.getSaveView(),null,controlModel+thingsModelItemBase.getName()+"为"+thingsModelBase.getView(),jsData.toString()));
109 } 114 }
110 115
111 - if(1==thingsModel.getIs_config()) 116 +
  117 + if(null != thingsModel && null != thingsModel.getType() && 2==thingsModel.getType())
112 { 118 {
113 config.put(key,thingsModelBase); 119 config.put(key,thingsModelBase);
114 - }else{  
115 data.put(key,thingsModelBase); 120 data.put(key,thingsModelBase);
  121 + }else
  122 + {
  123 + if(null != thingsModel && null !=thingsModel.getIs_config() && 1==thingsModel.getIs_config())
  124 + {
  125 + config.put(key,thingsModelBase);
  126 + }else{
  127 + data.put(key,thingsModelBase);
  128 + }
116 } 129 }
117 } 130 }
118 SaveDataDto saveDataDto = new SaveDataDto(); 131 SaveDataDto saveDataDto = new SaveDataDto();
@@ -68,7 +68,11 @@ public class MqttCallback implements MqttCallbackExtended { @@ -68,7 +68,11 @@ public class MqttCallback implements MqttCallbackExtended {
68 //准备数据 68 //准备数据
69 byte[] data = mqttMessage.getPayload(); 69 byte[] data = mqttMessage.getPayload();
70 IotDevice iotDevice = deviceService.getDeviceById(topic.getClientid()); 70 IotDevice iotDevice = deviceService.getDeviceById(topic.getClientid());
71 - 71 + if(null == iotDevice)
  72 + {
  73 + log.info("设备{}不存在",topic.getClientid());
  74 + return;
  75 + }
72 if("ONLINE".equals(topic.getTopicType().toUpperCase())) 76 if("ONLINE".equals(topic.getTopicType().toUpperCase()))
73 { 77 {
74 topic.setPayloadtype("String"); 78 topic.setPayloadtype("String");
@@ -107,7 +107,7 @@ public class TerminalService { @@ -107,7 +107,7 @@ public class TerminalService {
107 if(null != topic) 107 if(null != topic)
108 { 108 {
109 String rild = topic.getRoleid(); 109 String rild = topic.getRoleid();
110 - if(StringUtils.isNoneBlank(rild)) 110 + if(StringUtils.isNoneBlank(rild) && !"+".equals(rild))
111 { 111 {
112 if(!"".equals(roleids)) 112 if(!"".equals(roleids))
113 { 113 {
@@ -23,8 +23,6 @@ public class RedisService { @@ -23,8 +23,6 @@ public class RedisService {
23 @Resource 23 @Resource
24 private RedisTemplate<String,Object> redisTemplate; 24 private RedisTemplate<String,Object> redisTemplate;
25 25
26 - @Value("${mqtt.client.device_life}")  
27 - private long device_life; //设备生命周期  
28 26
29 /** 27 /**
30 * @param key 28 * @param key
@@ -51,7 +49,7 @@ public class RedisService { @@ -51,7 +49,7 @@ public class RedisService {
51 * @param value 49 * @param value
52 * @return 50 * @return
53 */ 51 */
54 - public boolean setexDevice(String key,Object value){ 52 + public boolean setexDevice(String key,long device_life,Object value){
55 try{//TimeUnit.SECONDS指定类型为秒 53 try{//TimeUnit.SECONDS指定类型为秒
56 redisTemplate.opsForValue().set(key,value,device_life, TimeUnit.SECONDS); 54 redisTemplate.opsForValue().set(key,value,device_life, TimeUnit.SECONDS);
57 return true; 55 return true;
@@ -99,11 +99,8 @@ public class DeviceController { @@ -99,11 +99,8 @@ public class DeviceController {
99 @Transactional 99 @Transactional
100 @RequestMapping(value = "delIotDevice/{client_id}",method = RequestMethod.POST) 100 @RequestMapping(value = "delIotDevice/{client_id}",method = RequestMethod.POST)
101 public Message delIotDevice(@PathVariable String client_id) throws MqttException, InterruptedException { 101 public Message delIotDevice(@PathVariable String client_id) throws MqttException, InterruptedException {
102 - deviceService.lockIotDevice(client_id);//先锁定  
103 closeSession(client_id); //强制下线 102 closeSession(client_id); //强制下线
104 - baseDao.updateBySql("DELETE FROM `iot_terminal` WHERE device_id='"+client_id+"'");  
105 - baseDao.updateBySql("DELETE FROM `iot_device` WHERE client_id='"+client_id+"'");  
106 - deviceService.unlockIotDevice(client_id);//解锁 103 + deviceService.deletRedisDevice(client_id);
107 return new Message(MessageCode.DEFAULT_SUCCESS_CODE); 104 return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
108 } 105 }
109 106
@@ -111,10 +108,8 @@ public class DeviceController { @@ -111,10 +108,8 @@ public class DeviceController {
111 @Transactional 108 @Transactional
112 @RequestMapping(value = "delIotTerminal/{client_id}/{number}",method = RequestMethod.POST) 109 @RequestMapping(value = "delIotTerminal/{client_id}/{number}",method = RequestMethod.POST)
113 public Message delIotTerminal(@PathVariable String client_id,@PathVariable String number) throws MqttException, InterruptedException { 110 public Message delIotTerminal(@PathVariable String client_id,@PathVariable String number) throws MqttException, InterruptedException {
114 - deviceService.lockIotDevice(client_id);//先锁定  
115 closeSession(client_id); //强制下线 111 closeSession(client_id); //强制下线
116 - baseDao.updateBySql("DELETE FROM `iot_terminal` WHERE id='"+client_id+"_"+number+"'");  
117 - deviceService.unlockIotDevice(client_id);//解锁 112 + deviceService.deletRedisTerminal(client_id+"_"+number);
118 return new Message(MessageCode.DEFAULT_SUCCESS_CODE); 113 return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
119 } 114 }
120 115
@@ -11,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired; @@ -11,6 +11,7 @@ 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.List; 13 import java.util.List;
  14 +import java.util.Set;
14 15
15 @Service 16 @Service
16 public class DeviceService { 17 public class DeviceService {
@@ -56,12 +57,14 @@ public class DeviceService { @@ -56,12 +57,14 @@ public class DeviceService {
56 */ 57 */
57 public IotDevice getRedicDevice(String id) 58 public IotDevice getRedicDevice(String id)
58 { 59 {
59 - Object object = redisService.get(RedisConfig.FIELD+RedisConfig.DEVICE+id); 60 + Object object = redisService.get(getRedicDeviceKey(id));
60 if(null != object) 61 if(null != object)
61 { 62 {
62 return (IotDevice)object; 63 return (IotDevice)object;
63 }else{ 64 }else{
64 - return getDeviceById(id); 65 + IotDevice iotDevice = getDeviceById(id);
  66 + setRedicDevice(iotDevice);
  67 + return iotDevice;
65 } 68 }
66 } 69 }
67 70
@@ -78,7 +81,8 @@ public class DeviceService { @@ -78,7 +81,8 @@ public class DeviceService {
78 */ 81 */
79 private boolean setRedicDevice(IotDevice device) 82 private boolean setRedicDevice(IotDevice device)
80 { 83 {
81 - return redisService.setexDevice(getRedicDeviceKey(device.getClient_id()),device); 84 + System.out.println("更新 "+device.getClient_id()+" 缓存,生命周期为 "+device.getDevice_life());
  85 + return redisService.setexDevice(getRedicDeviceKey(device.getClient_id()),device.getDevice_life(),device);
82 } 86 }
83 87
84 public String getRedicDeviceKey(String client_id) 88 public String getRedicDeviceKey(String client_id)
@@ -86,6 +90,11 @@ public class DeviceService { @@ -86,6 +90,11 @@ public class DeviceService {
86 return getRedicDeviceKeyPath()+client_id; 90 return getRedicDeviceKeyPath()+client_id;
87 } 91 }
88 92
  93 + public String getRedicTerminalFromClientId(String client_id)
  94 + {
  95 + return RedisConfig.FIELD+"*:"+client_id+"*";
  96 + }
  97 +
89 public String getRedicDeviceKeyPath() 98 public String getRedicDeviceKeyPath()
90 { 99 {
91 return RedisConfig.FIELD+RedisConfig.DEVICE; 100 return RedisConfig.FIELD+RedisConfig.DEVICE;
@@ -98,7 +107,7 @@ public class DeviceService { @@ -98,7 +107,7 @@ public class DeviceService {
98 */ 107 */
99 public IotTerminal getRedicTerminal(String id) 108 public IotTerminal getRedicTerminal(String id)
100 { 109 {
101 - Object object = redisService.get(RedisConfig.FIELD+RedisConfig.TERMINAL+id); 110 + Object object = redisService.get(getRedicTerminalKey(id));
102 if(null == object) 111 if(null == object)
103 { 112 {
104 IotTerminal terminal = getTerminalById(id); 113 IotTerminal terminal = getTerminalById(id);
@@ -117,9 +126,9 @@ public class DeviceService { @@ -117,9 +126,9 @@ public class DeviceService {
117 * @param terminal 126 * @param terminal
118 * @return 127 * @return
119 */ 128 */
120 - private boolean setRedicTerminal(IotTerminal terminal) 129 + private boolean setRedicTerminal(IotTerminal terminal,long device_life)
121 { 130 {
122 - return redisService.setexDevice(getRedicTerminalKey(terminal.getId()),terminal); 131 + return redisService.setexDevice(getRedicTerminalKey(terminal.getId()),device_life,terminal);
123 } 132 }
124 133
125 public String getRedicTerminalKey(String terminal_id) 134 public String getRedicTerminalKey(String terminal_id)
@@ -132,9 +141,9 @@ public class DeviceService { @@ -132,9 +141,9 @@ public class DeviceService {
132 return RedisConfig.FIELD+RedisConfig.TERMINAL; 141 return RedisConfig.FIELD+RedisConfig.TERMINAL;
133 } 142 }
134 143
135 - public void updataTerminal(IotTerminal terminal) 144 + public void updataTerminal(IotTerminal terminal,long device_life)
136 { 145 {
137 - setRedicTerminal(terminal); 146 + setRedicTerminal(terminal,device_life);
138 baseDao.saveOrUpdateObject(terminal); 147 baseDao.saveOrUpdateObject(terminal);
139 } 148 }
140 149
@@ -159,33 +168,29 @@ public class DeviceService { @@ -159,33 +168,29 @@ public class DeviceService {
159 } 168 }
160 169
161 /** 170 /**
162 - * 上锁  
163 - * @param clint_id 171 + * 删除主机
  172 + * @param client_id
164 */ 173 */
165 - public void lockIotDevice(String clint_id) 174 + public void deletRedisDevice(String client_id)
166 { 175 {
167 - redisService.setexDevice(RedisConfig.FIELD+RedisConfig.LOCK+clint_id,1);  
168 - }  
169 - /**  
170 - * 获取锁  
171 - * @param clint_id  
172 - */  
173 - public int getlockIotDevice(String clint_id)  
174 - {  
175 - Object object = redisService.get(RedisConfig.FIELD+RedisConfig.LOCK+clint_id);  
176 - if(null==object) 176 + Set<String> keys = redisService.keys(getRedicTerminalFromClientId(client_id));
  177 + if(null != keys && keys.size() != 0)
177 { 178 {
178 - return 0; 179 + redisService.del(keys.toArray(new String[keys.size()]));
179 } 180 }
180 - return (int)object;  
181 } 181 }
182 182
183 /** 183 /**
184 - * 解锁锁  
185 - * @param clint_id 184 + * 删除终端
  185 + * @param client_ids
186 */ 186 */
187 - public void unlockIotDevice(String clint_id) 187 + public void deletRedisTerminal(String... client_ids)
188 { 188 {
189 - redisService.del(RedisConfig.FIELD+RedisConfig.LOCK+clint_id); 189 + String[] keys = new String[client_ids.length];
  190 + for (int i=0;i<client_ids.length;i++)
  191 + {
  192 + keys[i] = getRedicTerminalKey(client_ids[i]);
  193 + }
  194 + redisService.del(keys);
190 } 195 }
191 } 196 }
@@ -3,20 +3,14 @@ package com.zhonglai.luhui.mqtt.service.topic; @@ -3,20 +3,14 @@ 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.DeviceSensorData;  
7 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto; 6 import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
8 import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto; 7 import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto;
9 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelBase; 8 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelBase;
10 import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelDataTypeEnum; 9 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.factory.BusinessAgreement; 10 import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;
13 import com.zhonglai.luhui.mqtt.comm.factory.Topic; 11 import com.zhonglai.luhui.mqtt.comm.factory.Topic;
14 import com.zhonglai.luhui.mqtt.comm.service.BusinessDataUpdateService; 12 import com.zhonglai.luhui.mqtt.comm.service.BusinessDataUpdateService;
15 import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService; 13 import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService;
16 -import com.zhonglai.luhui.mqtt.comm.service.DataModeAnalysisService;  
17 -import com.zhonglai.luhui.mqtt.comm.util.DateUtils;  
18 -import com.zhonglai.luhui.mqtt.dto.SaveDataDto;  
19 -import com.zhonglai.luhui.mqtt.dto.topic.AddPostDto;  
20 import com.zhonglai.luhui.mqtt.dto.topic.ReadReqDto; 14 import com.zhonglai.luhui.mqtt.dto.topic.ReadReqDto;
21 import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService; 15 import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService;
22 import org.apache.commons.lang3.EnumUtils; 16 import org.apache.commons.lang3.EnumUtils;
@@ -18,7 +18,7 @@ spring: @@ -18,7 +18,7 @@ spring:
18 18
19 ##redic配置 19 ##redic配置
20 redis: 20 redis:
21 - database: 0 21 + database: 1
22 # Redis服务器地址 写你的ip 22 # Redis服务器地址 写你的ip
23 host: 47.112.163.61 23 host: 47.112.163.61
24 # Redis服务器连接端口 24 # Redis服务器连接端口
@@ -42,9 +42,9 @@ mqtt: @@ -42,9 +42,9 @@ mqtt:
42 #链接地址 42 #链接地址
43 broker: tcp://175.24.61.68:1883 43 broker: tcp://175.24.61.68:1883
44 #唯一标识 44 #唯一标识
45 - clientId: lh-mqtt-service-003 45 + clientId: ${random.uuid}
46 #订阅的topic 46 #订阅的topic
47 - topics: "/2/+/+/+/ADD_POST,/2/+/+/+/ALL_POST,/2/+/+/+/DB_TOPIC_DISTRIBUTE,/2/+/+/+/GET/+,/2/+/+/+/online,/2/+/+/+/PUT_REQ/+,/2/+/+/+/READ_REQ/+" 47 + topics: "/+/+/+/+/ADD_POST,/+/+/+/+/ALL_POST,/+/+/+/+/DB_TOPIC_DISTRIBUTE,/+/+/+/+/GET/+,/+/+/+/+/online,/+/+/+/+/PUT_REQ/+,/+/+/+/+/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
@@ -52,7 +52,6 @@ mqtt: @@ -52,7 +52,6 @@ mqtt:
52 client: 52 client:
53 #客户端操作时间 53 #客户端操作时间
54 operationTime: 5 54 operationTime: 5
55 - device_life: 180  
56 redis: 55 redis:
57 key: 56 key:
58 #角色 57 #角色
@@ -63,4 +62,4 @@ mqtt: @@ -63,4 +62,4 @@ mqtt:
63 sys: 62 sys:
64 redis: 63 redis:
65 field: "luhui:mqttservice:device:" 64 field: "luhui:mqttservice:device:"
66 - isText: true 65 + isText: false
@@ -15,6 +15,8 @@ @@ -15,6 +15,8 @@
15 <module>lh-admin</module> 15 <module>lh-admin</module>
16 <module>lh-mqtt-service</module> 16 <module>lh-mqtt-service</module>
17 <module>lh-domain</module> 17 <module>lh-domain</module>
  18 + <module>lh-api</module>
  19 + <module>lh-central-control</module>
18 </modules> 20 </modules>
19 21
20 <packaging>pom</packaging> 22 <packaging>pom</packaging>
@@ -322,6 +324,12 @@ @@ -322,6 +324,12 @@
322 <artifactId>expiringmap</artifactId> 324 <artifactId>expiringmap</artifactId>
323 <version>0.5.8</version> 325 <version>0.5.8</version>
324 </dependency> 326 </dependency>
  327 +
  328 + <dependency>
  329 + <groupId>redis.clients</groupId>
  330 + <artifactId>jedis</artifactId>
  331 + <version>3.6.3</version>
  332 + </dependency>
325 </dependencies> 333 </dependencies>
326 334
327 335
@@ -35,6 +35,15 @@ public class HttpUtils { @@ -35,6 +35,15 @@ public class HttpUtils {
35 .writeTimeout(20, TimeUnit.SECONDS) 35 .writeTimeout(20, TimeUnit.SECONDS)
36 .build(); 36 .build();
37 37
  38 + public static String getResponseString(Response response)
  39 + {
  40 + try {
  41 + return response.body().string();
  42 + } catch (IOException e) {
  43 + }
  44 + return null;
  45 + }
  46 +
38 public static Response postJsonBody(String url,JsonBody jsonBody) throws IOException { 47 public static Response postJsonBody(String url,JsonBody jsonBody) throws IOException {
39 return postJsonBody(url,null,jsonBody); 48 return postJsonBody(url,null,jsonBody);
40 } 49 }
  1 +package com.ruoyi.system.dto;
  2 +
  3 +import org.apache.commons.lang3.StringUtils;
  4 +
  5 +import java.lang.reflect.Field;
  6 +import java.lang.reflect.InvocationTargetException;
  7 +import java.lang.reflect.Method;
  8 +import java.text.MessageFormat;
  9 +import java.util.List;
  10 +import java.util.Map;
  11 +
  12 +public class PublicSQL {
  13 + private String changTableNameFromObject(Object object)
  14 + {
  15 + return com.ruoyi.common.utils.StringUtils.toUnderScoreCase(object.getClass().getName());
  16 + }
  17 +
  18 +
  19 + private String insertListSql(List<?> list, String tableName)
  20 + {
  21 + if(StringUtils.isBlank(tableName))
  22 + {
  23 + tableName = changTableNameFromObject(list.get(0));
  24 + }
  25 + StringBuilder sb = new StringBuilder();
  26 + sb.append("INSERT INTO "+tableName);
  27 + String values = "";
  28 + String mfStr = "";
  29 + Field[] fields = list.get(0).getClass().getDeclaredFields( );
  30 + for(Field field:fields)
  31 + {
  32 + if(!"".equals(values) )
  33 + {
  34 + mfStr += ",";
  35 + values += ",";
  36 + }
  37 + values += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`";
  38 + mfStr += "#'{'list[{0}]."+field.getName()+"}";
  39 + }
  40 + sb.append("("+values+")");
  41 + sb.append("VALUES ");
  42 + MessageFormat mf = new MessageFormat("("+mfStr+")");
  43 + for (int i = 0; i < list.size(); i++) {
  44 + sb.append(mf.format(new Object[]{i}));
  45 + if (i < list.size() - 1) {
  46 + sb.append(",");
  47 + }
  48 + }
  49 + return sb.toString();
  50 + }
  51 +
  52 + public String insertAllToTable(Map map)
  53 + {
  54 + List<?> list = (List<?>) map.get("list");
  55 + String tableName = (String) map.get("tableName");
  56 + return insertListSql(list,tableName);
  57 + }
  58 + /**
  59 + * 添加对象
  60 + * @return
  61 + */
  62 + public String insertAll(Map map)
  63 + {
  64 + List<?> list = (List<?>) map.get("list");
  65 + return insertListSql(list,null);
  66 + }
  67 +
  68 + /**
  69 + * 添加对象
  70 + * @param object 对象
  71 + * @return
  72 + */
  73 + public String insert(Object object)
  74 + {
  75 + StringBuffer stringBuffer = new StringBuffer("insert into ");
  76 +
  77 + String tableName = changTableNameFromObject(object);
  78 + stringBuffer.append(tableName + "(");
  79 + Field[] fields = object.getClass().getDeclaredFields( );
  80 + StringBuffer values = new StringBuffer("(");
  81 + for(Field field:fields)
  82 + {//
  83 + Method method;
  84 + try {
  85 + method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
  86 + Object value = method.invoke(object);
  87 + if(null != value)
  88 + {
  89 + if(!"(".equals(values.toString()) )
  90 + {
  91 + stringBuffer.append(",");
  92 + values.append( ",");
  93 + }
  94 + stringBuffer.append( "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`");
  95 + values.append( "'"+ escapeSql(value+"")+"'");
  96 + }
  97 + } catch (NoSuchMethodException e) {
  98 + // TODO Auto-generated catch block
  99 + e.printStackTrace();
  100 + } catch (SecurityException e) {
  101 + // TODO Auto-generated catch block
  102 + e.printStackTrace();
  103 + } catch (IllegalAccessException e) {
  104 + // TODO Auto-generated catch block
  105 + e.printStackTrace();
  106 + } catch (IllegalArgumentException e) {
  107 + // TODO Auto-generated catch block
  108 + e.printStackTrace();
  109 + } catch (InvocationTargetException e) {
  110 + // TODO Auto-generated catch block
  111 + e.printStackTrace();
  112 + }
  113 +
  114 +
  115 + }
  116 + stringBuffer.append( ")");
  117 + values.append( ")");
  118 + return stringBuffer.append(" values ").append(values).toString();
  119 + }
  120 +
  121 + /**
  122 + * 指定表名添加对象
  123 + * @param object
  124 + * @return
  125 + */
  126 + public String insertToTable(Object object)
  127 + {
  128 + String tableName = changTableNameFromObject(object);
  129 + StringBuffer sql = new StringBuffer();
  130 + sql.append("insert into ");
  131 + sql.append(tableName + "(");
  132 + Field[] fields = object.getClass().getDeclaredFields( );
  133 + String values = "(";
  134 +
  135 + for(Field field:fields)
  136 + {//
  137 + Method method;
  138 + try {
  139 + method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
  140 + Object value = method.invoke(object);
  141 + if(null != value)
  142 + {
  143 + if(!"(".equals(values) )
  144 + {
  145 + sql.append(",");
  146 + values += ",";
  147 + }
  148 + sql.append("`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`");
  149 + values += "'"+escapeSql(value+"")+"'";
  150 + }
  151 + } catch (NoSuchMethodException e) {
  152 + // TODO Auto-generated catch block
  153 + e.printStackTrace();
  154 + } catch (SecurityException e) {
  155 + // TODO Auto-generated catch block
  156 + e.printStackTrace();
  157 + } catch (IllegalAccessException e) {
  158 + // TODO Auto-generated catch block
  159 + e.printStackTrace();
  160 + } catch (IllegalArgumentException e) {
  161 + // TODO Auto-generated catch block
  162 + e.printStackTrace();
  163 + } catch (InvocationTargetException e) {
  164 + // TODO Auto-generated catch block
  165 + e.printStackTrace();
  166 + }
  167 +
  168 +
  169 + }
  170 + sql.append(")");
  171 + values += ")";
  172 + return sql.toString()+" values "+values;
  173 + }
  174 +
  175 + /**
  176 + * 更新对象不为空的属性
  177 + * @param para
  178 + * @return
  179 + */
  180 + public String updateObject(Map<String,Object> para)
  181 + {
  182 + Object object = para.get("object");
  183 + String whereFieldNames = (String) para.get("whereFieldNames");
  184 + String tableName = changTableNameFromObject(object);
  185 + String sql = "update ";
  186 + sql += tableName;
  187 + Field[] fields = object.getClass().getDeclaredFields();
  188 + if(null != fields && fields.length !=0 )
  189 + {
  190 + sql += " set ";
  191 + int j = 0;
  192 + for(int i=0;i<fields.length;i++)
  193 + {
  194 + Field field = fields[i];
  195 + try {
  196 + Method method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
  197 + Object value = method.invoke(object);
  198 + if(null != value)
  199 + {
  200 + if(j!=0)
  201 + {
  202 + sql += ",";
  203 + }
  204 + sql += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+"='"+escapeSql(value+"")+"'";
  205 + j++;
  206 +
  207 +// if(i!=0)
  208 +// {
  209 +// sql += ",";
  210 +// }
  211 +// sql += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+"='"+value+"'";
  212 + }
  213 + } catch (NoSuchMethodException e) {
  214 +
  215 + e.printStackTrace();
  216 + } catch (SecurityException e) {
  217 + // TODO Auto-generated catch block
  218 + e.printStackTrace();
  219 + } catch (IllegalAccessException e) {
  220 + // TODO Auto-generated catch block
  221 + e.printStackTrace();
  222 + } catch (IllegalArgumentException e) {
  223 + // TODO Auto-generated catch block
  224 + e.printStackTrace();
  225 + } catch (InvocationTargetException e) {
  226 + // TODO Auto-generated catch block
  227 + e.printStackTrace();
  228 + }
  229 +
  230 + }
  231 +
  232 + sql += " where 1=1 ";
  233 + String[] wheres = whereFieldNames.split(",");
  234 + if(StringUtils.isNotBlank(whereFieldNames))
  235 + {
  236 + for(int i =0;i<wheres.length;i++)
  237 + {
  238 + try {
  239 + Method method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(wheres[i]));
  240 + Object value = method.invoke(object);
  241 + sql += " and ";
  242 + sql += com.ruoyi.common.utils.StringUtils.toUnderScoreCase(wheres[i]) + "='"+escapeSql(value+"")+"'";
  243 +// sql += com.ruoyi.common.utils.StringUtils.getName(wheres[i]) + "='"+value+"'";
  244 + } catch (IllegalAccessException e) {
  245 + // TODO Auto-generated catch block
  246 + e.printStackTrace();
  247 + } catch (IllegalArgumentException e) {
  248 + // TODO Auto-generated catch block
  249 + e.printStackTrace();
  250 + } catch (InvocationTargetException e) {
  251 + // TODO Auto-generated catch block
  252 + e.printStackTrace();
  253 + } catch (NoSuchMethodException e) {
  254 + // TODO Auto-generated catch block
  255 + e.printStackTrace();
  256 + } catch (SecurityException e) {
  257 + // TODO Auto-generated catch block
  258 + e.printStackTrace();
  259 + }
  260 +
  261 + }
  262 + }
  263 +
  264 +
  265 + }
  266 + return sql;
  267 + }
  268 +
  269 + /**
  270 + * 获得对象
  271 + */
  272 + public String getObject(Map<String, Object> para)
  273 + {
  274 + Class<?> clas = (Class<?>) para.get("class");
  275 + String idName = (String) para.get("idName");
  276 + String values = (String) para.get("values");
  277 + String tableName = null;
  278 +
  279 + if(para.containsKey("tableName"))
  280 + {
  281 + tableName = (String) para.get("tableName");
  282 + }
  283 +
  284 + String select = "*";
  285 + if(para.containsKey("select") && null != para.get("select"))
  286 + {
  287 + select = (String) para.get("select");
  288 + }
  289 +
  290 + if(StringUtils.isBlank(tableName))
  291 + {
  292 + tableName = com.ruoyi.common.utils.StringUtils.toUnderScoreCase(clas.getSimpleName());
  293 + }
  294 +
  295 + String[] idnames = idName.split(",");
  296 + String[] valuess = values.split(",");
  297 +
  298 + String where = "";
  299 + for(int i=0;i<idnames.length;i++)
  300 + {
  301 + if(i != 0)
  302 + {
  303 + where += " and ";
  304 + }
  305 + where += "`"+idnames[i]+"`='"+escapeSql(valuess[i]+"")+"'";
  306 +
  307 + }
  308 + String sql = "select "+select+" from "+tableName + " where " +where;
  309 + return sql;
  310 + }
  311 +
  312 + /**
  313 + * 通过条件删除数据
  314 + * @param para
  315 + * @return
  316 + */
  317 + public String deleteObjectByContent(Map<String, Object> para)
  318 + {
  319 + Class<?> objectCalss = (Class<?>) para.get("objectCalss");
  320 + String tableName = null;
  321 + if(para.containsKey("tableName"))
  322 + {
  323 + tableName = (String) para.get("tableName");
  324 + }
  325 +
  326 + @SuppressWarnings("unchecked")
  327 + Map<String,String> map = (Map<String, String>) para.get("map");
  328 +
  329 + if(StringUtils.isBlank(tableName))
  330 + {
  331 + tableName = com.ruoyi.common.utils.StringUtils.toUnderScoreCase(objectCalss.getSimpleName());
  332 + }
  333 + String sql = "delete from ";
  334 + sql += tableName + " where 1=1 ";
  335 + for(String key:map.keySet())
  336 + {
  337 + sql += " and "+"`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(key)+"`"+"='"+escapeSql(map.get(key)+"")+"'";
  338 + }
  339 + return sql;
  340 + }
  341 +
  342 + /**
  343 + * 通过id删除数据
  344 + * @param para
  345 + * @return
  346 + */
  347 + public String deleteObjectById(Map<String, Object> para)
  348 + {
  349 + Class<?> objectCalss = (Class<?>) para.get("objectCalss");
  350 + String tableName = null;
  351 + if(para.containsKey("tableName"))
  352 + {
  353 + tableName = (String) para.get("tableName");
  354 + }
  355 +
  356 + String id = (String) para.get("id");
  357 + if(StringUtils.isBlank(tableName))
  358 + {
  359 + tableName = com.ruoyi.common.utils.StringUtils.toUnderScoreCase(objectCalss.getSimpleName());
  360 + }
  361 + String sql = "delete from ";
  362 + sql += tableName + " where 1=1 ";
  363 + sql += " and "+"`id`"+"='"+escapeSql(id)+"'";
  364 + return sql;
  365 + }
  366 +
  367 + /**
  368 + * 获取对象列表总数
  369 + */
  370 + public String getObjectListTotle(Map<String, Object> para)
  371 + {
  372 + Object object = para.get("object");
  373 + @SuppressWarnings("unchecked")
  374 + Map<String,String> whereMap = (Map<String, String>) para.get("whereMap");
  375 +
  376 + String tableName = changTableNameFromObject(object);
  377 + String sql = "select count(*) from "+tableName;
  378 + String where = " where 1=1 ";
  379 +
  380 + String like = "";
  381 +
  382 + Field[] fields = object.getClass().getDeclaredFields();
  383 + if(null != fields && fields.length !=0 )
  384 + {
  385 + for(Field field:fields)
  386 + {
  387 + try {
  388 + Method method;
  389 + method = object.getClass().getMethod("get"+ com.ruoyi.common.utils.StringUtils.getName(field.getName()));
  390 + Object value = method.invoke(object);
  391 + if(null != value)
  392 + {
  393 + String orther = "";
  394 + String s = "=";
  395 + if(null != whereMap && null != whereMap.get(field.getName()))
  396 + {
  397 + s = whereMap.get(field.getName());
  398 + if("like".equals(s))
  399 + {
  400 + value = "%"+value+"%";
  401 + like += " or " + "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" '"+escapeSql(value+"")+"'"+orther ;
  402 + continue;
  403 + }
  404 + if("time".equals(s))
  405 + {
  406 + s = ">";
  407 + orther = " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`< '"+whereMap.get("end_"+field.getName())+"'";
  408 + }
  409 + if("in".equals(s))
  410 + {
  411 + s = "in";
  412 + value = (value+"").replace(",","','");
  413 + where += " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" ("+"'"+value+"'"+")"+orther;
  414 + continue;
  415 + }
  416 + }
  417 + where += " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" '"+escapeSql(value+"")+"'"+orther;
  418 + }
  419 + } catch (NoSuchMethodException e) {
  420 + e.printStackTrace();
  421 + } catch (SecurityException e) {
  422 + // TODO Auto-generated catch block
  423 + e.printStackTrace();
  424 + } catch (IllegalAccessException e) {
  425 + // TODO Auto-generated catch block
  426 + e.printStackTrace();
  427 + } catch (IllegalArgumentException e) {
  428 + // TODO Auto-generated catch block
  429 + e.printStackTrace();
  430 + } catch (InvocationTargetException e) {
  431 + // TODO Auto-generated catch block
  432 + e.printStackTrace();
  433 + }
  434 +
  435 + }
  436 + }
  437 + sql += where;
  438 + if(StringUtils.isNoneBlank(like))
  439 + {
  440 + sql += " and (1=2 "+like+")";
  441 + }
  442 + return sql;
  443 + }
  444 +
  445 + /**
  446 + * 获取对象列表
  447 + */
  448 + public String getObjectList(Map<String, Object> para)
  449 + {
  450 + Object object = para.get("object");
  451 + @SuppressWarnings("unchecked")
  452 + Map<String,String> whereMap = (Map<String, String>) para.get("whereMap");
  453 + String selectStr = " * ";
  454 + String order = "";
  455 + if(para.containsKey("order") && null != para.get("order"))
  456 + {
  457 + order = para.get("order") +"";
  458 + }
  459 + Integer pageSize = 0;
  460 + if(para.containsKey("pageSize") && null != para.get("pageSize"))
  461 + {
  462 + pageSize = (Integer) para.get("pageSize");
  463 + }
  464 + Integer pageNo = 0;
  465 + if(para.containsKey("pageNo") && null != para.get("pageNo"))
  466 + {
  467 + pageNo = (Integer) para.get("pageNo");
  468 + }
  469 + if(para.containsKey("selectStr") && null != para.get("selectStr"))
  470 + {
  471 + selectStr = para.get("selectStr")+"";
  472 + }
  473 + String tableName = changTableNameFromObject(object);
  474 +
  475 + if(para.containsKey("tableName") && null != para.get("tableName"))
  476 + {
  477 + tableName = para.get("tableName")+"";
  478 + }
  479 + String sql = "select "+selectStr+" from "+tableName;
  480 + String where = " where 1=1 ";
  481 + String like = "";
  482 +
  483 + Field[] fields = object.getClass().getDeclaredFields();
  484 + if(null != fields && fields.length !=0 )
  485 + {
  486 + for(int i=0;i<fields.length;i++)
  487 + {
  488 + Field field = fields[i];
  489 + try {
  490 + Method method;
  491 + method = object.getClass().getMethod("get"+ com.ruoyi.common.utils.StringUtils.getName(field.getName()));
  492 + Object value = method.invoke(object);
  493 + if(!(null == value))
  494 + {
  495 + String orther = "";
  496 + String s = "=";
  497 + if(!(null == whereMap || null == whereMap.get(field.getName())))
  498 + {
  499 + s = whereMap.get(field.getName());
  500 + if("like".equals(s))
  501 + {
  502 + value = "%"+value+"%";
  503 + like += " or " + "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" '"+escapeSql(value+"")+"'"+orther ;
  504 + continue;
  505 + }
  506 + if("time".equals(s))
  507 + {
  508 + s = ">";
  509 + orther = " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`< '"+whereMap.get("end_"+field.getName())+"'";
  510 + }
  511 + if("in".equals(s))
  512 + {
  513 + s = "in";
  514 + value = (value+"").replace(",","','");
  515 + where += " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" ("+"'"+value+"'"+")"+orther;
  516 + continue;
  517 + }
  518 + }
  519 + where += " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" '"+escapeSql(value+"")+"'"+orther;
  520 + }
  521 + } catch (NoSuchMethodException e) {
  522 + e.printStackTrace();
  523 + } catch (SecurityException e) {
  524 + // TODO Auto-generated catch block
  525 + e.printStackTrace();
  526 + } catch (IllegalAccessException e) {
  527 + // TODO Auto-generated catch block
  528 + e.printStackTrace();
  529 + } catch (IllegalArgumentException e) {
  530 + // TODO Auto-generated catch block
  531 + e.printStackTrace();
  532 + } catch (InvocationTargetException e) {
  533 + // TODO Auto-generated catch block
  534 + e.printStackTrace();
  535 + }
  536 +
  537 + }
  538 + }
  539 + sql += where;
  540 + if(StringUtils.isNoneBlank(like))
  541 + {
  542 + sql += " and (1=2 "+like+")";
  543 + }
  544 + if(StringUtils.isNotBlank(order))
  545 + {
  546 + sql += " order by "+order;
  547 + }
  548 + if(0 != pageSize && 0 != pageNo)
  549 + {
  550 + sql += " limit "+((pageNo-1)*pageSize)+","+pageSize;
  551 + }
  552 + return sql;
  553 + }
  554 +
  555 + /**
  556 + * 添加或更新对象
  557 + * INSERT INTO test(`in1`,`str1`) VALUES ('1','1');
  558 + * @param object 对象
  559 + * @return
  560 + */
  561 + public String saveOrUpdateObject(Object object)
  562 + {
  563 + String sql = "insert into ";
  564 + String tableName = changTableNameFromObject(object);
  565 + sql += tableName + "(";
  566 + Field[] fields = object.getClass().getDeclaredFields( );
  567 + String values = "(";
  568 + String update = "";
  569 + for(Field field:fields)
  570 + {//
  571 + Method method;
  572 + try {
  573 + method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
  574 + Object value = method.invoke(object);
  575 + if(null != value)
  576 + {
  577 + if(!"(".equals(values) )
  578 + {
  579 + sql += ",";
  580 + values += ",";
  581 + update += ",";
  582 + }
  583 + sql += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`";
  584 + values += "'"+ escapeSql(value+"")+"'";
  585 + update += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+"=VALUES("+"`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`)";
  586 + }
  587 + } catch (NoSuchMethodException e) {
  588 + // TODO Auto-generated catch block
  589 + e.printStackTrace();
  590 + } catch (SecurityException e) {
  591 + // TODO Auto-generated catch block
  592 + e.printStackTrace();
  593 + } catch (IllegalAccessException e) {
  594 + // TODO Auto-generated catch block
  595 + e.printStackTrace();
  596 + } catch (IllegalArgumentException e) {
  597 + // TODO Auto-generated catch block
  598 + e.printStackTrace();
  599 + } catch (InvocationTargetException e) {
  600 + // TODO Auto-generated catch block
  601 + e.printStackTrace();
  602 + }
  603 +
  604 +
  605 + }
  606 + sql += ")";
  607 + values += ")";
  608 + return sql+" values "+values+" ON DUPLICATE KEY UPDATE "+update;
  609 + }
  610 +
  611 + /**
  612 + * 添加或更新对象列表
  613 + * INSERT INTO `test` (`in1`,`str1`)VALUES ('1','2'),('2','2') ON DUPLICATE KEY UPDATE `in1`=VALUES(`in1`),`str1`=VALUES(`str1`);
  614 + * @param objectlist 对象列表
  615 + * @return
  616 + */
  617 + public String saveOrUpdateObjectList(List<Object> objectlist)
  618 + {
  619 + StringBuffer sb =new StringBuffer();
  620 + String update = "";
  621 + for(int i = 0; i<objectlist.size();i++)
  622 + {
  623 + Object object = objectlist.get(i);
  624 +
  625 + Field[] fields = object.getClass().getDeclaredFields( );
  626 + if(i==0)
  627 + {
  628 + String tableName = changTableNameFromObject(object);
  629 + sb.append("INSERT INTO `"+tableName+"` ");
  630 + sb.append("(");
  631 + for(Field field:fields)
  632 + {
  633 + if(!"".equals(update) )
  634 + {
  635 + sb.append(",");
  636 + update += ",";
  637 + }
  638 + sb.append("`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`");
  639 + update += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+"=VALUES("+"`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`)";
  640 + }
  641 + sb.append(")");
  642 + sb.append("VALUES ");
  643 + }else{
  644 + sb.append(",");
  645 + }
  646 + for(int j=0;j<fields.length;j++)
  647 + {
  648 + Field field = fields[j];
  649 + Method method;
  650 + try {
  651 + method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
  652 + Object value = method.invoke(object);
  653 + if(null == value)
  654 + {
  655 + value = "";
  656 + }
  657 + if(j!=0)
  658 + {
  659 + sb.append(",");
  660 + }else{
  661 + sb.append("(");
  662 + }
  663 + sb.append("'"+ escapeSql(value+"")+"'");
  664 + if(j==fields.length-1)
  665 + {
  666 + sb.append(")");
  667 + }
  668 + } catch (NoSuchMethodException e) {
  669 + // TODO Auto-generated catch block
  670 + e.printStackTrace();
  671 + } catch (SecurityException e) {
  672 + // TODO Auto-generated catch block
  673 + e.printStackTrace();
  674 + } catch (IllegalAccessException e) {
  675 + // TODO Auto-generated catch block
  676 + e.printStackTrace();
  677 + } catch (IllegalArgumentException e) {
  678 + // TODO Auto-generated catch block
  679 + e.printStackTrace();
  680 + } catch (InvocationTargetException e) {
  681 + // TODO Auto-generated catch block
  682 + e.printStackTrace();
  683 + }
  684 +
  685 + }
  686 + }
  687 + sb.append(" ON DUPLICATE KEY UPDATE ");
  688 + sb.append(update);
  689 + return sb.toString();
  690 + }
  691 +
  692 + public String getObjectListBySQL(Map<String, Object> para)
  693 + {
  694 + return para.get("sql")+"";
  695 + }
  696 +
  697 + public String updateBySql(Map<String, Object> para)
  698 + {
  699 + return para.get("sql")+"";
  700 + }
  701 +
  702 + public static String escapeSql(String str) {
  703 + return str == null ? null : StringUtils.replace(str, "'", "''");
  704 + }
  705 +}
  1 +package com.ruoyi.system.mapper;
  2 +
  3 +import java.util.List;
  4 +import com.ruoyi.system.domain.IotProductTranslate;
  5 +
  6 +/**
  7 + * 产品指标翻译Mapper接口
  8 + *
  9 + * @author 钟来
  10 + * @date 2022-11-04
  11 + */
  12 +public interface IotProductTranslateMapper
  13 +{
  14 + /**
  15 + * 查询产品指标翻译
  16 + *
  17 + * @param id 产品指标翻译主键
  18 + * @return 产品指标翻译
  19 + */
  20 + public IotProductTranslate selectIotProductTranslateById(Integer id);
  21 +
  22 + /**
  23 + * 查询产品指标翻译列表
  24 + *
  25 + * @param iotProductTranslate 产品指标翻译
  26 + * @return 产品指标翻译集合
  27 + */
  28 + public List<IotProductTranslate> selectIotProductTranslateList(IotProductTranslate iotProductTranslate);
  29 +
  30 + /**
  31 + * 新增产品指标翻译
  32 + *
  33 + * @param iotProductTranslate 产品指标翻译
  34 + * @return 结果
  35 + */
  36 + public int insertIotProductTranslate(IotProductTranslate iotProductTranslate);
  37 +
  38 + int insertAll(List<IotProductTranslate> list);
  39 + /**
  40 + * 修改产品指标翻译
  41 + *
  42 + * @param iotProductTranslate 产品指标翻译
  43 + * @return 结果
  44 + */
  45 + public int updateIotProductTranslate(IotProductTranslate iotProductTranslate);
  46 +
  47 + /**
  48 + * 删除产品指标翻译
  49 + *
  50 + * @param id 产品指标翻译主键
  51 + * @return 结果
  52 + */
  53 + public int deleteIotProductTranslateById(Integer id);
  54 +
  55 + /**
  56 + * 批量删除产品指标翻译
  57 + *
  58 + * @param ids 需要删除的数据主键集合
  59 + * @return 结果
  60 + */
  61 + public int deleteIotProductTranslateByIds(Integer[] ids);
  62 +
  63 + List<IotProductTranslate> selectIotProductTranslateListByIds(Integer[] ids);
  64 +}
@@ -58,4 +58,5 @@ public interface IotTerminalMapper @@ -58,4 +58,5 @@ public interface IotTerminalMapper
58 * @return 结果 58 * @return 结果
59 */ 59 */
60 public int deleteIotTerminalByIds(String[] ids); 60 public int deleteIotTerminalByIds(String[] ids);
  61 + int deleteIotTerminalByDeviceId(String deviceId);
61 } 62 }
  1 +package com.ruoyi.system.mapper;
  2 +
  3 +import com.ruoyi.system.dto.PublicSQL;
  4 +import org.apache.ibatis.annotations.*;
  5 +
  6 +import java.util.List;
  7 +import java.util.Map;
  8 +
  9 +/**
  10 + * 公用mapper
  11 + */
  12 +public interface PublicMapper {
  13 + /**
  14 + * 添加对象
  15 + */
  16 + @InsertProvider(type = PublicSQL.class, method = "insert")
  17 + int insert(Object object);
  18 +
  19 + /**
  20 + * 指定表名添加
  21 + */
  22 + @InsertProvider(type = PublicSQL.class, method = "insertToTable")
  23 + int insertToTable(Object object,String tableName);
  24 +
  25 + /**
  26 + * 添加对象集合
  27 + */
  28 + @InsertProvider(type = PublicSQL.class, method = "insertAll")
  29 + int insertAll(List<?> list);
  30 +
  31 + /**
  32 + * 指定表名添加对象集合
  33 + */
  34 + @InsertProvider(type = PublicSQL.class, method = "insertAllToTable")
  35 + int insertAllToTable(List<?> list,String tableName);
  36 +
  37 + /**
  38 + * 更新对象不为空的属性
  39 + * @param object
  40 + * @param whereFieldNames
  41 + */
  42 + @UpdateProvider(type = PublicSQL.class, method = "updateObject")
  43 + void updateObject(@Param("object") Object object, @Param("whereFieldNames") String whereFieldNames);
  44 +
  45 + /**
  46 + * 自定义sql更新
  47 + * @param sql
  48 + */
  49 + @UpdateProvider(type = PublicSQL.class, method = "updateBySql")
  50 + void updateBySql(String sql);
  51 +
  52 + /**
  53 + * 查询 通过条件查询
  54 + * @param clas
  55 + * @param idName
  56 + * @param values
  57 + * @return
  58 + */
  59 + @SelectProvider(type = PublicSQL.class, method = "getObject")
  60 + <T> T getObject(@Param("class") Class<?> clas, @Param("idName") String idName, @Param("values") String values);
  61 +
  62 + /**
  63 + * 查询 通过条件查询
  64 + * @param clas
  65 + * @param idName
  66 + * @param values
  67 + * @return
  68 + */
  69 + @SelectProvider(type = PublicSQL.class, method = "getObject")
  70 + Map<String,Object> getObjectForTableName(@Param("class") Class<?> clas, @Param("idName") String idName, @Param("values") String values, @Param("tableName") String tableName);
  71 +
  72 + /**
  73 + * 查询 通过条件查询单个指定项目
  74 + * @param clas 類型
  75 + * @param select 查詢結果
  76 + * @param idName 主鍵名稱
  77 + * @param values 主鍵值
  78 + * @return
  79 + */
  80 + @SelectProvider(type = PublicSQL.class, method = "getObject")
  81 + Map<String,Object> getObjectSelectTableName(@Param("class") Class<?> clas, @Param("select") String select, @Param("idName") String idName, @Param("values") String values, @Param("tableName") String tableName);
  82 +
  83 + /**
  84 + * 查询list
  85 + * @param object
  86 + * @param whereMap 如果是时间,whereMap里面对应的字段比较符为time,同时添加一个end_字段名的值 表示是结束时间
  87 + * @param order
  88 + * @param pagetSize
  89 + * @param pageNo
  90 + * @return
  91 + */
  92 + @SelectProvider(type = PublicSQL.class, method = "getObjectList")
  93 + List<Map<String,Object>> getObjectList(@Param("object") Object object, @Param("selectStr") String selectStr, @Param("whereMap") Map<String, String> whereMap, @Param("order") String order, @Param("pageSize") Integer pagetSize, @Param("pageNo") Integer pageNo);
  94 +
  95 + /**
  96 + * 查詢totle
  97 + * @param object
  98 + * @param whereMap 如果是时间,whereMap里面对应的字段比较符为time,同时添加一个end_字段名的值 表示是结束时间
  99 + * @return
  100 + */
  101 + @SelectProvider(type = PublicSQL.class, method = "getObjectListTotle")
  102 + Long getObjectListTotle(@Param("object") Object object, @Param("whereMap") Map<String, String> whereMap);
  103 +
  104 + /**
  105 + * 通过条件删除对象
  106 + * @param oClass
  107 + * @param map
  108 + */
  109 + @UpdateProvider(type = PublicSQL.class, method = "deleteObjectByContent")
  110 + void deleteObjectByContent(@Param("objectCalss") Class<?> oClass, @Param("map") Map<String, String> map);
  111 +
  112 + /**
  113 + * 自定义sql语句查询list
  114 + * @param sql
  115 + * @return
  116 + */
  117 + @SelectProvider(type = PublicSQL.class, method = "getObjectListBySQL")
  118 + List<Map<String,Object>> getObjectListBySQL(@Param("sql") String sql);
  119 + /**
  120 + * 添加或更新对象列表
  121 + * INSERT INTO `test` (`in1`,`str1`)VALUES ('1','2'),('2','2') ON DUPLICATE KEY UPDATE `in1`=VALUES(`in1`),`str1`=VALUES(`str1`);
  122 + * @param objectlist 对象列表
  123 + * @return
  124 + */
  125 + @UpdateProvider(type = PublicSQL.class, method = "saveOrUpdateObjectList")
  126 + void saveOrUpdateObjectList(List<Object> objectlist);
  127 +
  128 + /**
  129 + * 添加或更新对象
  130 + * INSERT INTO test(`in1`,`str1`) VALUES ('1','1');
  131 + * @param object 对象
  132 + * @return
  133 + */
  134 + @UpdateProvider(type = PublicSQL.class, method = "saveOrUpdateObject")
  135 + void saveOrUpdateObject(Object object);
  136 +
  137 + /**
  138 + * 通过id删除数据
  139 + * @return
  140 + */
  141 + @UpdateProvider(type = PublicSQL.class, method = "deleteObjectById")
  142 + void deleteObjectById(@Param("objectCalss") Class<?> oClass, @Param("id") String id);
  143 +
  144 + @Options(useGeneratedKeys = false)
  145 + @InsertProvider(type = PublicSQL.class, method = "updateBySql")
  146 + void insertIntoBySql(@Param("sql") String sql);
  147 +}
  1 +package com.ruoyi.system.service;
  2 +
  3 +import java.util.List;
  4 +import com.ruoyi.system.domain.IotProductTranslate;
  5 +
  6 +/**
  7 + * 产品指标翻译Service接口
  8 + *
  9 + * @author 钟来
  10 + * @date 2022-11-04
  11 + */
  12 +public interface IIotProductTranslateService
  13 +{
  14 + /**
  15 + * 查询产品指标翻译
  16 + *
  17 + * @param id 产品指标翻译主键
  18 + * @return 产品指标翻译
  19 + */
  20 + public IotProductTranslate selectIotProductTranslateById(Integer id);
  21 +
  22 + /**
  23 + * 查询产品指标翻译列表
  24 + *
  25 + * @param iotProductTranslate 产品指标翻译
  26 + * @return 产品指标翻译集合
  27 + */
  28 + public List<IotProductTranslate> selectIotProductTranslateList(IotProductTranslate iotProductTranslate);
  29 +
  30 + /**
  31 + * 新增产品指标翻译
  32 + *
  33 + * @param iotProductTranslate 产品指标翻译
  34 + * @return 结果
  35 + */
  36 + public int insertIotProductTranslate(IotProductTranslate iotProductTranslate);
  37 + int insertAll(List<IotProductTranslate> list);
  38 + /**
  39 + * 修改产品指标翻译
  40 + *
  41 + * @param iotProductTranslate 产品指标翻译
  42 + * @return 结果
  43 + */
  44 + public int updateIotProductTranslate(IotProductTranslate iotProductTranslate);
  45 +
  46 + /**
  47 + * 批量删除产品指标翻译
  48 + *
  49 + * @param ids 需要删除的产品指标翻译主键集合
  50 + * @return 结果
  51 + */
  52 + public int deleteIotProductTranslateByIds(Integer[] ids);
  53 +
  54 + /**
  55 + * 删除产品指标翻译信息
  56 + *
  57 + * @param id 产品指标翻译主键
  58 + * @return 结果
  59 + */
  60 + public int deleteIotProductTranslateById(Integer id);
  61 +}
@@ -58,4 +58,6 @@ public interface IIotTerminalService @@ -58,4 +58,6 @@ public interface IIotTerminalService
58 * @return 结果 58 * @return 结果
59 */ 59 */
60 public int deleteIotTerminalById(String id); 60 public int deleteIotTerminalById(String id);
  61 +
  62 + int deleteIotTerminalByDeviceId(String deviceId);
61 } 63 }
1 package com.ruoyi.system.service.impl; 1 package com.ruoyi.system.service.impl;
2 2
3 import java.util.List; 3 import java.util.List;
  4 +
  5 +import com.ruoyi.common.exception.ServiceException;
  6 +import com.ruoyi.common.utils.DateUtils;
  7 +import com.ruoyi.system.domain.IotProduct;
  8 +import com.ruoyi.system.service.IIotProductService;
4 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.stereotype.Service; 10 import org.springframework.stereotype.Service;
6 import com.ruoyi.system.mapper.IotDeviceMapper; 11 import com.ruoyi.system.mapper.IotDeviceMapper;
@@ -18,7 +23,8 @@ public class IotDeviceServiceImpl implements IIotDeviceService @@ -18,7 +23,8 @@ public class IotDeviceServiceImpl implements IIotDeviceService
18 { 23 {
19 @Autowired 24 @Autowired
20 private IotDeviceMapper iotDeviceMapper; 25 private IotDeviceMapper iotDeviceMapper;
21 - 26 + @Autowired
  27 + private IIotProductService iIotProductService;
22 /** 28 /**
23 * 查询null 29 * 查询null
24 * 30 *
@@ -52,6 +58,19 @@ public class IotDeviceServiceImpl implements IIotDeviceService @@ -52,6 +58,19 @@ public class IotDeviceServiceImpl implements IIotDeviceService
52 @Override 58 @Override
53 public int insertIotDevice(IotDevice iotDevice) 59 public int insertIotDevice(IotDevice iotDevice)
54 { 60 {
  61 + IotProduct iotProduct = iIotProductService.selectIotProductById(iotDevice.getProduct_id());
  62 + if(null == iotProduct)
  63 + {
  64 + throw new ServiceException("产品不存在");
  65 + }
  66 + IotDevice old = iotDeviceMapper.selectIotDeviceByClient_id(iotDevice.getClient_id());
  67 + if(null != old)
  68 + {
  69 + throw new ServiceException("设备已存在");
  70 + }
  71 + iotDevice.setMqtt_username(iotProduct.getMqtt_username());
  72 + iotDevice.setCreate_time(DateUtils.getNowTimeMilly());
  73 + iotDevice.setData_update_time(DateUtils.getNowTimeMilly());
55 return iotDeviceMapper.insertIotDevice(iotDevice); 74 return iotDeviceMapper.insertIotDevice(iotDevice);
56 } 75 }
57 76
  1 +package com.ruoyi.system.service.impl;
  2 +
  3 +import java.util.List;
  4 +
  5 +import com.ruoyi.common.core.redis.RedisCache;
  6 +import org.springframework.beans.factory.annotation.Autowired;
  7 +import org.springframework.stereotype.Service;
  8 +import com.ruoyi.system.mapper.IotProductTranslateMapper;
  9 +import com.ruoyi.system.domain.IotProductTranslate;
  10 +import com.ruoyi.system.service.IIotProductTranslateService;
  11 +
  12 +/**
  13 + * 产品指标翻译Service业务层处理
  14 + *
  15 + * @author 钟来
  16 + * @date 2022-11-04
  17 + */
  18 +@Service
  19 +public class IotProductTranslateServiceImpl implements IIotProductTranslateService
  20 +{
  21 + @Autowired
  22 + private IotProductTranslateMapper iotProductTranslateMapper;
  23 +
  24 + @Autowired
  25 + private RedisCache redisCache;
  26 +
  27 + private String productTranslateRedisKeyPath ="luhui:product:translate:";
  28 + /**
  29 + * 查询产品指标翻译
  30 + *
  31 + * @param id 产品指标翻译主键
  32 + * @return 产品指标翻译
  33 + */
  34 + @Override
  35 + public IotProductTranslate selectIotProductTranslateById(Integer id)
  36 + {
  37 + return iotProductTranslateMapper.selectIotProductTranslateById(id);
  38 + }
  39 +
  40 + /**
  41 + * 查询产品指标翻译列表
  42 + *
  43 + * @param iotProductTranslate 产品指标翻译
  44 + * @return 产品指标翻译
  45 + */
  46 + @Override
  47 + public List<IotProductTranslate> selectIotProductTranslateList(IotProductTranslate iotProductTranslate)
  48 + {
  49 + return iotProductTranslateMapper.selectIotProductTranslateList(iotProductTranslate);
  50 + }
  51 +
  52 + /**
  53 + * 新增产品指标翻译
  54 + *
  55 + * @param iotProductTranslate 产品指标翻译
  56 + * @return 结果
  57 + */
  58 + @Override
  59 + public int insertIotProductTranslate(IotProductTranslate iotProductTranslate)
  60 + {
  61 + int ri = iotProductTranslateMapper.insertIotProductTranslate(iotProductTranslate);
  62 + upCache(iotProductTranslate);
  63 + return ri;
  64 + }
  65 +
  66 + @Override
  67 + public int insertAll(List<IotProductTranslate> list) {
  68 + int ri = iotProductTranslateMapper.insertAll(list);
  69 + for(IotProductTranslate iotProductTranslate:list)
  70 + {
  71 + upCache(iotProductTranslate);
  72 + }
  73 + return ri;
  74 + }
  75 +
  76 + /**
  77 + * 修改产品指标翻译
  78 + *
  79 + * @param iotProductTranslate 产品指标翻译
  80 + * @return 结果
  81 + */
  82 + @Override
  83 + public int updateIotProductTranslate(IotProductTranslate iotProductTranslate)
  84 + {
  85 + int ri = iotProductTranslateMapper.updateIotProductTranslate(iotProductTranslate);
  86 + upCache(iotProductTranslate);
  87 + return ri;
  88 + }
  89 +
  90 + /**
  91 + * 批量删除产品指标翻译
  92 + *
  93 + * @param ids 需要删除的产品指标翻译主键
  94 + * @return 结果
  95 + */
  96 + @Override
  97 + public int deleteIotProductTranslateByIds(Integer[] ids)
  98 + {
  99 + List<IotProductTranslate> list = iotProductTranslateMapper.selectIotProductTranslateListByIds(ids);
  100 +
  101 + int ri = iotProductTranslateMapper.deleteIotProductTranslateByIds(ids);
  102 + for(IotProductTranslate iotProductTranslate:list)
  103 + {
  104 + remCache(iotProductTranslate);
  105 + }
  106 + return ri;
  107 + }
  108 +
  109 + /**
  110 + * 删除产品指标翻译信息
  111 + *
  112 + * @param id 产品指标翻译主键
  113 + * @return 结果
  114 + */
  115 + @Override
  116 + public int deleteIotProductTranslateById(Integer id)
  117 + {
  118 + IotProductTranslate iotProductTranslate = iotProductTranslateMapper.selectIotProductTranslateById(id);
  119 + if(null == iotProductTranslate)
  120 + {
  121 + return 0;
  122 + }
  123 + remCache(iotProductTranslate);
  124 + return iotProductTranslateMapper.deleteIotProductTranslateById(id);
  125 + }
  126 +
  127 + public void remCache(IotProductTranslate iotProductTranslate)
  128 + {
  129 + redisCache.delCacheMapValue(getProductTranslateRedisKey(iotProductTranslate.getProduct_id()),iotProductTranslate.getModel_identifier());
  130 + }
  131 +
  132 + public void upCache(IotProductTranslate iotProductTranslate)
  133 + {
  134 + redisCache.setCacheMapValue(getProductTranslateRedisKey(iotProductTranslate.getProduct_id()),iotProductTranslate.getModel_identifier(),iotProductTranslate.getTranslate_identifier());
  135 + }
  136 + private String getProductTranslateRedisKey(Integer productId)
  137 + {
  138 + return productTranslateRedisKeyPath+productId;
  139 + }
  140 +}
1 package com.ruoyi.system.service.impl; 1 package com.ruoyi.system.service.impl;
2 2
3 import java.util.List; 3 import java.util.List;
  4 +
  5 +import com.ruoyi.common.utils.DateUtils;
4 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.stereotype.Service; 7 import org.springframework.stereotype.Service;
6 import com.ruoyi.system.mapper.IotTerminalMapper; 8 import com.ruoyi.system.mapper.IotTerminalMapper;
@@ -90,4 +92,9 @@ public class IotTerminalServiceImpl implements IIotTerminalService @@ -90,4 +92,9 @@ public class IotTerminalServiceImpl implements IIotTerminalService
90 { 92 {
91 return iotTerminalMapper.deleteIotTerminalById(id); 93 return iotTerminalMapper.deleteIotTerminalById(id);
92 } 94 }
  95 +
  96 + @Override
  97 + public int deleteIotTerminalByDeviceId(String deviceId) {
  98 + return iotTerminalMapper.deleteIotTerminalByDeviceId(deviceId);
  99 + }
93 } 100 }
@@ -32,10 +32,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -32,10 +32,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
32 <result property="payload_type" column="payload_type" /> 32 <result property="payload_type" column="payload_type" />
33 <result property="things_model_config" column="things_model_config" /> 33 <result property="things_model_config" column="things_model_config" />
34 <result property="listen_service_ip" column="listen_service_ip" /> 34 <result property="listen_service_ip" column="listen_service_ip" />
  35 + <result property="device_life" column="device_life" />
  36 + <result property="data_update_time" column="data_update_time" />
  37 +
35 </resultMap> 38 </resultMap>
36 39
37 <sql id="selectIotDeviceVo"> 40 <sql id="selectIotDeviceVo">
38 - select active_time, client_id, completion_auth, create_by, create_time, del_flag, firmware_version, img_url, is_shadow, latitude, location_way, longitude, `name`, network_address, network_ip, remark, rssi, status, summary, things_model_value, update_by, update_time, product_id,mqtt_username,payload_type,things_model_config,listen_service_ip from iot_device 41 + select active_time, client_id, completion_auth, create_by, create_time, del_flag, firmware_version, img_url, is_shadow, latitude, location_way, longitude, `name`, network_address, network_ip, remark, rssi, status, summary, things_model_value, update_by, update_time, product_id,mqtt_username,payload_type,things_model_config,listen_service_ip,device_life,data_update_time from iot_device
39 </sql> 42 </sql>
40 43
41 <select id="selectIotDeviceList" parameterType="IotDevice" resultMap="IotDeviceResult"> 44 <select id="selectIotDeviceList" parameterType="IotDevice" resultMap="IotDeviceResult">
@@ -89,6 +92,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -89,6 +92,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
89 <if test="mqtt_username != null">mqtt_username,</if> 92 <if test="mqtt_username != null">mqtt_username,</if>
90 <if test="payload_type != null">payload_type,</if> 93 <if test="payload_type != null">payload_type,</if>
91 <if test="things_model_config != null">things_model_config,</if> 94 <if test="things_model_config != null">things_model_config,</if>
  95 + <if test="device_life != null">device_life,</if>
  96 + <if test="data_update_time != null">data_update_time,</if>
92 create_time, 97 create_time,
93 </trim> 98 </trim>
94 <trim prefix="values (" suffix=")" suffixOverrides=","> 99 <trim prefix="values (" suffix=")" suffixOverrides=",">
@@ -116,7 +121,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -116,7 +121,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
116 <if test="product_id != null">#{product_id},</if> 121 <if test="product_id != null">#{product_id},</if>
117 <if test="mqtt_username != null">#{mqtt_username},</if> 122 <if test="mqtt_username != null">#{mqtt_username},</if>
118 <if test="payload_type != null">#{payload_type},</if> 123 <if test="payload_type != null">#{payload_type},</if>
119 - <if test="things_model_config != null">things_model_config,</if> 124 + <if test="things_model_config != null">#{things_model_config},</if>
  125 + <if test="device_life != null">#{device_life},</if>
  126 + <if test="data_update_time != null">#{data_update_time},</if>
120 UNIX_TIMESTAMP(NOW()), 127 UNIX_TIMESTAMP(NOW()),
121 </trim> 128 </trim>
122 </insert> 129 </insert>
@@ -149,6 +156,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -149,6 +156,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
149 <if test="mqtt_username != null">mqtt_username = #{mqtt_username},</if> 156 <if test="mqtt_username != null">mqtt_username = #{mqtt_username},</if>
150 <if test="payload_type != null">payload_type = #{payload_type},</if> 157 <if test="payload_type != null">payload_type = #{payload_type},</if>
151 <if test="things_model_config != null">things_model_config = #{things_model_config},</if> 158 <if test="things_model_config != null">things_model_config = #{things_model_config},</if>
  159 + <if test="device_life != null">device_life = #{device_life},</if>
  160 + <if test="data_update_time != null">data_update_time = #{data_update_time},</if>
152 </trim> 161 </trim>
153 where client_id = #{client_id} 162 where client_id = #{client_id}
154 </update> 163 </update>
  1 +<?xml version="1.0" encoding="UTF-8" ?>
  2 +<!DOCTYPE mapper
  3 +PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4 +"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5 +<mapper namespace="com.ruoyi.system.mapper.IotProductTranslateMapper">
  6 +
  7 + <resultMap type="IotProductTranslate" id="IotProductTranslateResult">
  8 + <result property="create_time" column="create_time" />
  9 + <result property="id" column="id" />
  10 + <result property="model_identifier" column="model_identifier" />
  11 + <result property="product_id" column="product_id" />
  12 + <result property="translate_identifier" column="translate_identifier" />
  13 + </resultMap>
  14 +
  15 + <sql id="selectIotProductTranslateVo">
  16 + select `create_time`, `id`, `model_identifier`, `product_id`, `translate_identifier` from iot_product_translate
  17 + </sql>
  18 +
  19 + <select id="selectIotProductTranslateList" parameterType="IotProductTranslate" resultMap="IotProductTranslateResult">
  20 + <include refid="selectIotProductTranslateVo"/>
  21 + <where>
  22 + <if test="product_id !=null and product_id != ''">
  23 + and product_id = #{product_id}
  24 + </if>
  25 + </where>
  26 + </select>
  27 +
  28 + <select id="selectIotProductTranslateListByIds" parameterType="String" resultMap="IotProductTranslateResult">
  29 + <include refid="selectIotProductTranslateVo"/>
  30 + where id in
  31 + <foreach item="id" collection="array" open="(" separator="," close=")">
  32 + #{id}
  33 + </foreach>
  34 + </select>
  35 +
  36 + <select id="selectIotProductTranslateById" parameterType="Integer" resultMap="IotProductTranslateResult">
  37 + <include refid="selectIotProductTranslateVo"/>
  38 + where id = #{id}
  39 + </select>
  40 +
  41 + <insert id="insertIotProductTranslate" parameterType="IotProductTranslate" useGeneratedKeys="true" keyProperty="id">
  42 + insert into iot_product_translate
  43 + <trim prefix="(" suffix=")" suffixOverrides=",">
  44 + <if test="create_time != null">create_time,</if>
  45 + <if test="model_identifier != null">model_identifier,</if>
  46 + <if test="product_id != null">product_id,</if>
  47 + <if test="translate_identifier != null">translate_identifier,</if>
  48 + </trim>
  49 + <trim prefix="values (" suffix=")" suffixOverrides=",">
  50 + <if test="create_time != null">#{create_time},</if>
  51 + <if test="model_identifier != null">#{model_identifier},</if>
  52 + <if test="product_id != null">#{product_id},</if>
  53 + <if test="translate_identifier != null">#{translate_identifier},</if>
  54 + </trim>
  55 + </insert>
  56 +
  57 + <insert id="insertAll">
  58 + insert into iot_product_translate(`create_time`, `model_identifier`, `product_id`, `translate_identifier`) values
  59 + <foreach item="item" index="index" collection="list" separator=",">
  60 + ( UNIX_TIMESTAMP(NOW()),#{item.model_identifier},#{item.product_id},#{item.translate_identifier})
  61 + </foreach>
  62 + </insert>
  63 +
  64 + <update id="updateIotProductTranslate" parameterType="IotProductTranslate">
  65 + update iot_product_translate
  66 + <trim prefix="SET" suffixOverrides=",">
  67 + <if test="create_time != null">create_time = #{create_time},</if>
  68 + <if test="model_identifier != null">model_identifier = #{model_identifier},</if>
  69 + <if test="product_id != null">product_id = #{product_id},</if>
  70 + <if test="translate_identifier != null">translate_identifier = #{translate_identifier},</if>
  71 + </trim>
  72 + where id = #{id}
  73 + </update>
  74 +
  75 + <delete id="deleteIotProductTranslateById" parameterType="Integer">
  76 + delete from iot_product_translate where id = #{id}
  77 + </delete>
  78 +
  79 + <delete id="deleteIotProductTranslateByIds" parameterType="String">
  80 + delete from iot_product_translate where id in
  81 + <foreach item="id" collection="array" open="(" separator="," close=")">
  82 + #{id}
  83 + </foreach>
  84 + </delete>
  85 +</mapper>
@@ -13,10 +13,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -13,10 +13,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
13 <result property="things_model_config" column="things_model_config" /> 13 <result property="things_model_config" column="things_model_config" />
14 <result property="product_id" column="product_id" /> 14 <result property="product_id" column="product_id" />
15 <result property="mqtt_username" column="mqtt_username" /> 15 <result property="mqtt_username" column="mqtt_username" />
  16 + <result property="data_update_time" column="data_update_time" />
16 </resultMap> 17 </resultMap>
17 18
18 <sql id="selectIotTerminalVo"> 19 <sql id="selectIotTerminalVo">
19 - select device_id, id, `name`, things_model_value, update_time,things_model_config,product_id,mqtt_username from iot_terminal 20 + select device_id, id, `name`, things_model_value, update_time,things_model_config,product_id,mqtt_username,data_update_time from iot_terminal
20 </sql> 21 </sql>
21 22
22 <select id="selectIotTerminalList" parameterType="IotTerminal" resultMap="IotTerminalResult"> 23 <select id="selectIotTerminalList" parameterType="IotTerminal" resultMap="IotTerminalResult">
@@ -53,6 +54,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -53,6 +54,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
53 <if test="things_model_config != null">things_model_config,</if> 54 <if test="things_model_config != null">things_model_config,</if>
54 <if test="product_id != null">product_id,</if> 55 <if test="product_id != null">product_id,</if>
55 <if test="mqtt_username != null">mqtt_username,</if> 56 <if test="mqtt_username != null">mqtt_username,</if>
  57 + <if test="data_update_time != null">data_update_time,</if>
56 </trim> 58 </trim>
57 <trim prefix="values (" suffix=")" suffixOverrides=","> 59 <trim prefix="values (" suffix=")" suffixOverrides=",">
58 <if test="device_id != null">#{device_id},</if> 60 <if test="device_id != null">#{device_id},</if>
@@ -63,6 +65,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -63,6 +65,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
63 <if test="things_model_config != null">#{things_model_config},</if> 65 <if test="things_model_config != null">#{things_model_config},</if>
64 <if test="product_id != null">#{product_id},</if> 66 <if test="product_id != null">#{product_id},</if>
65 <if test="mqtt_username != null">#{mqtt_username},</if> 67 <if test="mqtt_username != null">#{mqtt_username},</if>
  68 + <if test="data_update_time != null">#{data_update_time},</if>
66 </trim> 69 </trim>
67 </insert> 70 </insert>
68 71
@@ -76,6 +79,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -76,6 +79,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
76 <if test="things_model_config != null">things_model_config = #{things_model_config},</if> 79 <if test="things_model_config != null">things_model_config = #{things_model_config},</if>
77 <if test="product_id != null">product_id = #{product_id},</if> 80 <if test="product_id != null">product_id = #{product_id},</if>
78 <if test="mqtt_username != null">mqtt_username = #{mqtt_username},</if> 81 <if test="mqtt_username != null">mqtt_username = #{mqtt_username},</if>
  82 + <if test="data_update_time != null">data_update_time = #{data_update_time},</if>
79 </trim> 83 </trim>
80 where id = #{id} 84 where id = #{id}
81 </update> 85 </update>
@@ -84,6 +88,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -84,6 +88,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
84 delete from iot_terminal where id = #{id} 88 delete from iot_terminal where id = #{id}
85 </delete> 89 </delete>
86 90
  91 + <delete id="deleteIotTerminalByDeviceId" parameterType="String">
  92 + delete from iot_terminal where device_id = #{device_id}
  93 + </delete>
  94 +
87 <delete id="deleteIotTerminalByIds" parameterType="String"> 95 <delete id="deleteIotTerminalByIds" parameterType="String">
88 delete from iot_terminal where id in 96 delete from iot_terminal where id in
89 <foreach item="id" collection="array" open="(" separator="," close=")"> 97 <foreach item="id" collection="array" open="(" separator="," close=")">