作者 钟来

初始提交

正在显示 51 个修改的文件 包含 2814 行增加102 行删除
... ... @@ -10,16 +10,16 @@ import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.html.HttpUtils;
import com.ruoyi.system.domain.IotDevice;
import com.ruoyi.system.service.IIotDeviceService;
import com.ruoyi.system.service.IIotTerminalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
... ... @@ -33,7 +33,8 @@ import java.util.Map;
public class IotDeviceControlController {
@Autowired
private IIotDeviceService iotDeviceService;
@Autowired
private IIotTerminalService iIotTerminalService;
private String getServiceAdrres(HttpServletResponse response,String imei) throws IOException {
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
response.setCharacterEncoding("UTF-8");
... ... @@ -142,22 +143,32 @@ public class IotDeviceControlController {
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
})
@Transactional
@ResponseBody
@PostMapping("/delIotDevice/{imei}")
public String delIotDevice(HttpServletResponse response,@PathVariable String imei) throws IOException {
public String delIotDevice(HttpServletResponse response,@PathVariable String imei) {
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
iotDeviceService.deleteIotDeviceByClient_id(imei);
iIotTerminalService.deleteIotTerminalByDeviceId(imei);
response.setCharacterEncoding("UTF-8");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/delIotDevice/"+imei;
Response response1 = HttpUtils.postFromBody(url, builder -> {
try {
String str = HttpUtils.getResponseString(HttpUtils.postFromBody(url, builder -> {
}, formBody -> {
});
return response1.body().string();
}));
if(null != str)
{
return str;
}
} catch (IOException e) {
}
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
}
@ApiOperation("删除终端")
... ... @@ -166,20 +177,28 @@ public class IotDeviceControlController {
})
@ResponseBody
@PostMapping("/delIotTerminal/{imei}/{number}")
public String delIotTerminal(HttpServletResponse response,@PathVariable String imei,@PathVariable String number) throws IOException {
public String delIotTerminal(HttpServletResponse response,@PathVariable String imei,@PathVariable String number) {
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
iIotTerminalService.deleteIotTerminalById(imei+"_"+number);
response.setCharacterEncoding("UTF-8");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/delIotTerminal/"+imei+"/"+number;
Response response1 = HttpUtils.postFromBody(url, builder -> {
String str = null;
try {
str = HttpUtils.getResponseString(HttpUtils.postFromBody(url, builder -> {
}, formBody -> {
});
return response1.body().string();
}));
} catch (IOException e) {
}
if(null != str)
{
return str;
}
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
}
@ApiOperation(value = "读取属性")
... ...
... ... @@ -41,8 +41,6 @@ public class IotDeviceController extends BaseController
{
@Autowired
private IIotDeviceService iotDeviceService;
@Autowired
private IIotProductService iIotProductService;
/**
* 查询主机/网关列表
*/
... ... @@ -90,11 +88,8 @@ public class IotDeviceController extends BaseController
@PostMapping("add")
public AjaxResult add(@RequestBody IotDevice iotDevice)
{
IotProduct iotProduct = iIotProductService.selectIotProductById(iotDevice.getProduct_id());
iotDevice.setMqtt_username(iotProduct.getMqtt_username());
iotDevice.setCreate_by(getUsername());
iotDevice.setCreate_time(DateUtils.getNowTimeMilly());
iotDevice.setUpdate_time(DateUtils.getNowTimeMilly());
return toAjax(iotDeviceService.insertIotDevice(iotDevice));
}
... ...
package com.zhonglai.luhui.admin.controller.iot;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.IotProductTranslate;
import com.ruoyi.system.service.IIotProductTranslateService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
/**
* 产品指标翻译Controller
*
* @author 钟来
* @date 2022-11-04
*/
@Api(tags = "产品指标翻译")
@RestController
@RequestMapping("/iot/IotProductTranslate")
public class IotProductTranslateController extends BaseController
{
@Autowired
private IIotProductTranslateService iotProductTranslateService;
/**
* 查询产品指标翻译列表
*/
@ApiOperation("查询产品指标翻译列表")
@PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:list')")
@GetMapping("/list")
public TableDataInfo list(IotProductTranslate iotProductTranslate)
{
startPage();
List<IotProductTranslate> list = iotProductTranslateService.selectIotProductTranslateList(iotProductTranslate);
return getDataTable(list);
}
/**
* 导出产品指标翻译列表
*/
@ApiOperation("导出产品指标翻译列表")
@PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:export')")
@Log(title = "产品指标翻译", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, IotProductTranslate iotProductTranslate)
{
List<IotProductTranslate> list = iotProductTranslateService.selectIotProductTranslateList(iotProductTranslate);
ExcelUtil<IotProductTranslate> util = new ExcelUtil<IotProductTranslate>(IotProductTranslate.class);
util.exportExcel(response, list, "产品指标翻译数据");
}
/**
* 获取产品指标翻译详细信息
*/
@ApiOperation("获取产品指标翻译详细信息")
@PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Integer id)
{
return AjaxResult.success(iotProductTranslateService.selectIotProductTranslateById(id));
}
/**
* 新增产品指标翻译
*/
@ApiOperation("新增产品指标翻译")
@PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:add')")
@Log(title = "产品指标翻译", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody IotProductTranslate iotProductTranslate)
{
iotProductTranslate.setCreate_time(DateUtils.getNowTimeMilly());
return toAjax(iotProductTranslateService.insertIotProductTranslate(iotProductTranslate));
}
@ApiOperation("批量新增产品指标翻译")
@PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:addAll')")
@Log(title = "产品指标翻译", businessType = BusinessType.INSERT)
@PostMapping("/addAll")
public AjaxResult addAll(@RequestBody List<IotProductTranslate> list)
{
return toAjax(iotProductTranslateService.insertAll(list));
}
/**
* 修改产品指标翻译
*/
@ApiOperation("修改产品指标翻译")
@PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:edit')")
@Log(title = "产品指标翻译", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody IotProductTranslate iotProductTranslate)
{
return toAjax(iotProductTranslateService.updateIotProductTranslate(iotProductTranslate));
}
/**
* 删除产品指标翻译
*/
@ApiOperation("删除产品指标翻译")
@PreAuthorize("@ss.hasPermi('iot:IotProductTranslate:remove')")
@Log(title = "产品指标翻译", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Integer[] ids)
{
return toAjax(iotProductTranslateService.deleteIotProductTranslateByIds(ids));
}
}
... ...
... ... @@ -3,6 +3,8 @@ package com.zhonglai.luhui.admin.controller.iot;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.IIotProductTranslateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
... ... @@ -97,6 +99,7 @@ public class IotTerminalController extends BaseController
@PutMapping
public AjaxResult edit(@RequestBody IotTerminal iotTerminal)
{
iotTerminal.setUpdate_time(DateUtils.getNowTimeMilly());
return toAjax(iotTerminalService.updateIotTerminal(iotTerminal));
}
... ...
# 项目相关配置 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
\ No newline at end of file
# 项目相关配置 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
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Luhui</artifactId>
<groupId>com.zhonglai.luhui</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>lh-api</artifactId>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>ruoyi-framework</artifactId>
</dependency>
<!-- 代码生成模块-->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>ruoyi-generator</artifactId>
</dependency>
<!-- 代码生成模块-->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>lh-mqtt-service</artifactId>
</dependency>
<!-- 文档 -->
<dependency >
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--https://mvnrepository.com/artifact/io.swagger/swagger-models-->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger-models.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui &ndash;&gt;-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>${swagger-ui.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
</dependencies>
<build>
<finalName>lh-api</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<!--
生成的jar中,不要包含pom.xml和pom.properties这两个文件
-->
<addMavenDescriptor>false</addMavenDescriptor>
<manifest>
<!--
是否要把第三方jar放到manifest的classpath中
-->
<addClasspath>true</addClasspath>
<!--
生成的manifest中classpath的前缀,因为要把第三方jar放到lib目录下,所以classpath的前缀是lib/
-->
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.zhonglai.luhui.admin.AdminApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<!-- The configuration of maven-assembly-plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<descriptors>
<descriptor>src/main/resources/package.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Luhui</artifactId>
<groupId>com.zhonglai.luhui</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>lh-central-control</artifactId>
<description>
中控平台
</description>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<!-- SpringBoot Web容器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring框架基本的核心工具 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- SpringWeb模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- servlet包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
</dependency>
<!-- 文档 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--https://mvnrepository.com/artifact/io.swagger/swagger-models-->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger-models.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui &ndash;&gt;-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>${swagger-ui.version}</version>
</dependency>
<!-- mqtt -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
</dependency>
<dependency>
<groupId>net.jodah</groupId>
<artifactId>expiringmap</artifactId>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- redis 缓存操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>lh-domain</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
... ...
package com.zhonglai.luhui.central.control;
public class LhCentralControlApplication {
}
... ...
package com.zhonglai.luhui.central.control.comm;
public class Message {
private int code;
private String message;
private Object data;
public Message() {
}
public Message(MessageCodeType code, String message, Object data) {
this.code = code.getCode();
this.message = message;
if (null == message || "".equals(message)) {
this.message = code.getMessage();
}
this.data = data;
}
public Message(MessageCodeType code, Object data) {
this.code = code.getCode();
this.message = code.getMessage();
this.data = data;
}
public Message(MessageCodeType code, String message) {
this.code = code.getCode();
this.message = message;
this.data = null;
}
public Message(MessageCodeType code) {
this.code = code.getCode();
this.message = code.getMessage();
}
public void setCode(MessageCode messageCode )
{
code = messageCode.code;
}
public void setCode(MessageCodeType code) {
this.code = code.getCode();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
... ...
package com.zhonglai.luhui.central.control.comm;
public enum MessageCode implements MessageCodeType{
DEFAULT_FAIL_CODE(0, "请求失败"),
DEFAULT_SUCCESS_CODE(1, "请求成功"),
SESSION_TIME_OUT(2, "会话超时,请刷新令牌"),
USER_INVALID(4, "用户失效,请重新登录"),
SYS_ERROR(3, "已知系统错误"),
REQUEST_METHOD_ERROR(6, "请求方式错误"),
REQUEST_PATH_ERROR(7, "请求路径错误"),
UNKNOWN_SYS_ERROR(5, "未知系统错误");
public int code;
public String message;
public int getCode() {
return this.code;
}
public String getMessage() {
return this.message;
}
private MessageCode(int code, String message) {
this.code = code;
this.message = message;
}
}
... ...
package com.zhonglai.luhui.central.control.comm;
public interface MessageCodeType {
int getCode();
String getMessage();
}
... ...
package com.zhonglai.luhui.central.control.comm;
/**
* mqtt消息解析结果
*/
public enum MqttAnalysisMessageResult {
/**
* 成功
*/
Success,
/**
* 失败
*/
Fail,
/**
*topic异常
*/
TopicException,
/**
*设备不存在
*/
DeviceDoesNotExist,
/**
*payload解析异常
*/
PayloadParsingException
}
... ...
package com.zhonglai.luhui.central.control.comm;
public class MyException extends RuntimeException{
private static final long serialVersionUID = 8827598182853467258L;
private Message errmge;
public MyException(Message myMessage) {
super(myMessage.getMessage());
this.errmge = myMessage;
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(String message) {
super(message);
}
}
... ...
package com.zhonglai.luhui.central.control.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
public class SysParameter {
private static Logger log = LoggerFactory.getLogger(SysParameter.class);
public static String service_ip = ""; //服务所在地址
@Value("${mqtt.topicconfig:/{{roleid}}/{{username}}/{{clientid}}/{{topicType}}/{{messageid}}}")
public String tempTopicconfig ; //topic 配置
@Value("${mqtt.topics")
public String topics ; //topic
public static String topicconfig ; //topic 配置
@PostConstruct
public void init() {
inittopicconfig();
}
public void inittopicconfig()
{
topicconfig = tempTopicconfig;
}
}
... ...
package com.zhonglai.luhui.central.control.comm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.Optional;
public class Topic {
private static final Logger log = LoggerFactory.getLogger(Topic.class);
private String roleid;
private String username;
private String clientid;
private String topicType;
private String messageid;
private String payloadtype;
public Topic() {
}
public Topic(String roleid, String username, String clientid, String topicType, String payloadtype) {
this.roleid = roleid;
this.username = username;
this.clientid = clientid;
this.topicType = topicType;
this.payloadtype = payloadtype;
}
public Topic(String roleid, String username, String clientid, String topicType, String messageid, String payloadtype) {
this.roleid = roleid;
this.username = username;
this.clientid = clientid;
this.topicType = topicType;
this.messageid = messageid;
this.payloadtype = payloadtype;
}
public Topic(String topic)
{
topic = Optional.ofNullable(topic).orElseThrow(()->new MyException("topic为空"));
String[] sts = topic.split("/");
String[] config = SysParameter.topicconfig.split("/");
int number = sts.length;
if(number>config.length)
{
number = config.length;
}
for(int i=1;i<number;i++)
{
String cf = config[i].replace("{{","").replace("}}","");
try {
Field field = this.getClass().getDeclaredField(cf);
field.set(this,sts[i]);
} catch (NoSuchFieldException e) {
log.info("{}生成topic时没有属性{}",topic,cf);
} catch (IllegalAccessException e) {
log.info("{}生成topic时无法给{}赋值{}",topic,cf,sts[i]);
}
}
if("ONLINE".equals(topicType.toUpperCase()))
{
this.payloadtype = "String";
}
}
/**
* 生成缓存关键字
* @return
*/
public String generateRedicKey()
{
return generate(":");
}
/**
* 生成发送消息的topic
* @return
*/
public String generateSendMessageTopic()
{
return "/"+generate("/");
}
/**
* 生成客户端关键字
* @return
*/
public String generateClienKey()
{
return "/"+generate("/");
}
private String generate(String division)
{
String str = SysParameter.topicconfig;
if(StringUtils.isEmpty(roleid))
{
roleid = "2";
}
str = str.replace("/{{roleid}}",roleid+division);
if(StringUtils.isEmpty(username))
{
username = "+";
}
str = str.replace("/{{username}}",username+division);
if(StringUtils.isEmpty(clientid))
{
clientid = "+";
}
str = str.replace("/{{clientid}}",clientid+division);
if(StringUtils.isEmpty(payloadtype))
{
payloadtype = "String";
}
str = str.replace("/{{payloadtype}}",payloadtype+division);
if(StringUtils.isEmpty(topicType))
{
topicType = "PUT";
}
str = str.replace("/{{topicType}}",topicType+division);
if(StringUtils.isNotEmpty(messageid))
{
str = str.replace("/{{messageid}}",messageid);
}
return str;
}
public String getRoleid() {
return roleid;
}
public void setRoleid(String roleid) {
this.roleid = roleid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getClientid() {
return clientid;
}
public void setClientid(String clientid) {
this.clientid = clientid;
}
public String getTopicType() {
return topicType;
}
public void setTopicType(String topicType) {
this.topicType = topicType;
}
public String getMessageid() {
return messageid;
}
public void setMessageid(String messageid) {
this.messageid = messageid;
}
public String getPayloadtype() {
return payloadtype;
}
public void setPayloadtype(String payloadtype) {
this.payloadtype = payloadtype;
}
}
... ...
package com.zhonglai.luhui.central.control.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MqttConfig {
@Value("${mqtt.broker}")
private String broker;
@Value("${mqtt.clientId}")
private String clientId;
@Value("${mqtt.topics}")
private String topics;
@Value("${mqtt.username}")
private String username;
@Value("${mqtt.password}")
private String password;
public String getBroker() {
return broker;
}
public void setBroker(String broker) {
this.broker = broker;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getTopics() {
return topics;
}
public void setTopics(String topics) {
this.topics = topics;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
... ...
package com.zhonglai.luhui.central.control.service;
import com.ruoyi.system.domain.IotDevice;
public interface DeviceService {
IotDevice getDeviceById(String clientId);
}
... ...
package com.zhonglai.luhui.central.control.service;
import com.zhonglai.luhui.central.control.config.MqttConfig;
import com.zhonglai.luhui.central.control.util.ByteUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class MqttClientService {
private Logger log = LoggerFactory.getLogger(MqttClientService.class);
@Autowired
private MqttConfig mqttConfig;
@Autowired
private MqttMessageArrivedService mqttMessageArrivedService;
@Autowired
private MqttOperation mqttOperation;
private MqttClient mqttclient;
private MqttConnectOptions options;
{
if(null == mqttclient)
{
try {
mqttclient = new MqttClient(mqttConfig.getBroker(), mqttConfig.getClientId(), new MemoryPersistence());
} catch (MqttException e) {
e.printStackTrace();
}
options = new MqttConnectOptions();
options.setCleanSession(true);
options.setConnectionTimeout(15);
//设置断开后重新连接
options.setAutomaticReconnect(true);
mqttclient.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean b, String s) {
log.info("连接成功");
try {
subscribe();
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void connectionLost(Throwable cause) {
log.error("连接丢失",cause);
}
@Override
public void messageArrived(String topic, MqttMessage message) {
log.info("接收到消息topc:{}, mqttMessage {},payload 十六进制 {}",topic,message, ByteUtil.hexStringToSpace(ByteUtil.toHexString(message.getPayload())));
mqttMessageArrivedService.analysisMessage(topic,message);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
try {
log.info("成功发出消息 messageid{}",token.getMessage());
} catch (MqttException e) {
e.printStackTrace();
}
}
});
}
}
@PostConstruct
public void init() throws MqttException {
log.info("-----------终端数据模型配置成功--------------------");
connect();
log.info("-----------mqtt连接服务器成功--------------------");
subscribe();
log.info("-----------订阅{}成功--------------------",mqttConfig.getTopics());
}
private void connect() throws MqttException {
options.setUserName(mqttConfig.getUsername());
options.setPassword(mqttConfig.getPassword().toCharArray());
mqttclient.connect(options);
}
private void subscribe() throws MqttException {
mqttOperation.subscribe(mqttclient,mqttConfig.getTopics().split(","));
}
}
... ...
package com.zhonglai.luhui.central.control.service;
import com.ruoyi.system.domain.IotDevice;
import com.zhonglai.luhui.central.control.comm.MqttAnalysisMessageResult;
import com.zhonglai.luhui.central.control.comm.Topic;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 数据解析业务
*/
@Service
public class MqttMessageArrivedService {
@Autowired
private DeviceService deviceService ;
private Logger log = LoggerFactory.getLogger(MqttMessageArrivedService.class);
public MqttAnalysisMessageResult analysisMessage(String topicStr, MqttMessage message)
{
Topic topic = new Topic(topicStr);
if(null == topic)
{
log.error("消息{},解析出来的topic为空,不做解析",topicStr);
return MqttAnalysisMessageResult.TopicException;
}
IotDevice iotDevice = deviceService.getDeviceById(topic.getClientid());
if(null == iotDevice)
{
log.info("设备{}不存在",topic.getClientid());
return MqttAnalysisMessageResult.DeviceDoesNotExist;
}
//消息分发
try {
// messageDistribution();
}catch (Exception e)
{
log.info("消息解析异常",e);
return MqttAnalysisMessageResult.PayloadParsingException;
}
return MqttAnalysisMessageResult.Success;
}
}
... ...
package com.zhonglai.luhui.central.control.service;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
@Service
public class MqttOperation {
public void subscribe(MqttClient mqttclient,String[] topicFilters) throws MqttException {
mqttclient.subscribe(topicFilters);
}
public void publish(MqttClient mqttclient,String topic, MqttMessage message) throws MqttException {
mqttclient.publish(topic,message);
}
public void publish(MqttClient mqttclient,String topic, String messageStr) throws MqttException {
MqttMessage message = new MqttMessage();
message.setPayload(messageStr.getBytes());
mqttclient.publish(topic,message);
}
public void closeClient (MqttClient mqttclient,String clientId,String code,String messageStr) throws MqttException {
String topic = "SYSOPERATION/CLOSE";
MqttMessage message = new MqttMessage();
Charset charset = Charset.forName("utf-8");
ByteBuffer payload = charset.encode(clientId+","+code+","+messageStr);
message.setPayload(payload.array());
mqttclient.publish(topic,message);
}
}
... ...
package com.zhonglai.luhui.central.control.util;
import java.util.Arrays;
public class ByteUtil {
/**
* byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用
*
* @param src
* byte数组
* @param offset
* 从数组的第offset位开始
* @return int数值
*/
public static long bytesToLongASC(byte[] src, int offset,int lenth) {
int value = 0;
for(int i=0;i<lenth;i++)
{
value = value | ((src[offset+i] & 0xFF)<<(8*i));
}
return value;
}
/**
* 把16进制字符串转换成字节数组
*
* @param hex
* @return
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
/**
* 把16进制字符串转换成字节数组
*
* @param hex
* @return
*/
public static String hexStringToSpace(String hex) {
if (null == hex) {
return null;
} else {
StringBuilder sb = new StringBuilder(hex.length() << 1);
for(int i = 0; i < hex.length(); i+=2) {
sb.append(hex.substring(i,i+2)).append(" ");
}
return sb.toString();
}
}
/**
* 把原数组加点目标数组后面
* @param dest 目标数组
* @param src 原数组
* @return
*/
public static byte[] addBytes(byte[] dest,byte[] src )
{
int dl = dest.length;
int sl = src.length;
dest = Arrays.copyOf(dest, dl+sl);//数组扩容
System.arraycopy(src,0,dest,dl,src.length);
return dest;
}
/**
* 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。 和bytesToInt2()配套使用
*/
public static byte[] intToBytesDESC(long value,int lenth)
{
byte[] src = new byte[lenth];
for(int i=0;i<lenth;i++)
{
src[i] = (byte) ((value>>(8*(lenth-i-1))) & 0xFF);
}
return src;
}
/**
* 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。 和bytesToInt()配套使用
* @param value
* 要转换的int值
* @return byte数组
*/
public static byte[] intToBytesASC( long value,int lenth)
{
byte[] src = new byte[lenth];
for(int i=lenth;i>0;i--)
{
src[i-1] = (byte) ((value>>(8*(i-1))) & 0xFF);
}
return src;
}
public static void main(String[] args) {
System.out.println(ByteUtil.toHexString( ByteUtil.intToBytesASC(2011239256,4)));
}
/**
* ip转化位4byte
* @param ip
* @return
*/
public static byte[] ipTo4Byte(String ip)
{
String[] ips = ip.split(".");
return new byte[]{(byte) Integer.parseInt(ips[0]),(byte) Integer.parseInt(ips[1]),(byte) Integer.parseInt(ips[2]),(byte) Integer.parseInt(ips[3])};
}
/**
* byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。和intToBytes2()配套使用
*/
public static long bytesToLongDESC(byte[] src, int offset,int lenth) {
long value = 0;
for(int i=lenth;i>0;i--)
{
value = value | ((src[offset+(lenth-i)] & 0xFF)<<(8*(i-1)));
}
return value;
}
private static final char[] hex = "0123456789abcdef".toCharArray();
public static String toHexString(byte[] bytes) {
if (null == bytes) {
return null;
} else {
StringBuilder sb = new StringBuilder(bytes.length << 1);
for(int i = 0; i < bytes.length; ++i) {
sb.append(hex[(bytes[i] & 240) >> 4]).append(hex[bytes[i] & 15]);
}
return sb.toString();
}
}
/**
* 计算CRC16/Modbus校验码 低位在前,高位在后
*
* @param str 十六进制字符串
* @return
*/
public static String getCRC16(String str) {
byte[] bytes = hexStringToByte(str);
return getCRC16(bytes);
}
/**
* 计算CRC16/Modbus校验码 低位在前,高位在后
*
* @return
*/
public static String getCRC16( byte[] bytes) {
int CRC = 0x0000ffff;
int POLYNOMIAL = 0x0000a001;
int i, j;
for (i = 0; i < bytes.length; i++) {
CRC ^= ((int) bytes[i] & 0x000000ff);
for (j = 0; j < 8; j++) {
if ((CRC & 0x00000001) != 0) {
CRC >>= 1;
CRC ^= POLYNOMIAL;
} else {
CRC >>= 1;
}
}
}
String crc = Integer.toHexString(CRC);
if (crc.length() == 2) {
crc = "00" + crc;
} else if (crc.length() == 3) {
crc = "0" + crc;
}
crc = crc.substring(2, 4) + crc.substring(0, 2);
return crc.toUpperCase();
}
}
... ...
... ... @@ -44,7 +44,7 @@ public class IotDevice implements Serializable
/** 固件版本 */
@ApiModelProperty("固件版本")
private Float firmware_version;
private String firmware_version;
/** 图片地址 */
@ApiModelProperty("图片地址")
... ... @@ -120,6 +120,28 @@ public class IotDevice implements Serializable
@ApiModelProperty("描述")
private String remark;
@ApiModelProperty("设备生命周期")
private Long device_life;
@ApiModelProperty("数据更新时间")
private Integer data_update_time;
public Integer getData_update_time() {
return data_update_time;
}
public void setData_update_time(Integer data_update_time) {
this.data_update_time = data_update_time;
}
public Long getDevice_life() {
return device_life;
}
public void setDevice_life(Long device_life) {
this.device_life = device_life;
}
public String getListen_service_ip() {
return listen_service_ip;
}
... ... @@ -199,12 +221,12 @@ public class IotDevice implements Serializable
{
return del_flag;
}
public void setFirmware_version(Float firmware_version)
public void setFirmware_version(String firmware_version)
{
this.firmware_version = firmware_version;
}
public Float getFirmware_version()
public String getFirmware_version()
{
return firmware_version;
}
... ...
package com.ruoyi.system.domain;
import com.ruoyi.system.domain.tool.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* 产品指标翻译对象 iot_product_translate
*
* @author 钟来
* @date 2022-11-04
*/
@ApiModel("产品指标翻译")
public class IotProductTranslate extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 创建时间 */
@ApiModelProperty("创建时间")
private Integer create_time;
/** 主键 */
@ApiModelProperty("主键")
private Integer id;
/** 模型标识 */
@ApiModelProperty("模型标识")
private String model_identifier;
/** 产品id */
@ApiModelProperty("产品id")
private Integer product_id;
/** 翻译的模型标识(支持两层josn键值,用英文点分割) */
@ApiModelProperty("翻译的模型标识(支持两层josn键值,用英文点分割如:11:start)")
private String translate_identifier;
public void setCreate_time(Integer create_time)
{
this.create_time = create_time;
}
public Integer getCreate_time()
{
return create_time;
}
public void setId(Integer id)
{
this.id = id;
}
public Integer getId()
{
return id;
}
public void setModel_identifier(String model_identifier)
{
this.model_identifier = model_identifier;
}
public String getModel_identifier()
{
return model_identifier;
}
public void setProduct_id(Integer product_id)
{
this.product_id = product_id;
}
public Integer getProduct_id()
{
return product_id;
}
public void setTranslate_identifier(String translate_identifier)
{
this.translate_identifier = translate_identifier;
}
public String getTranslate_identifier()
{
return translate_identifier;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("create_time", getCreate_time())
.append("id", getId())
.append("model_identifier", getModel_identifier())
.append("product_id", getProduct_id())
.append("translate_identifier", getTranslate_identifier())
.toString();
}
}
... ...
... ... @@ -46,6 +46,16 @@ public class IotTerminal implements Serializable
@ApiModelProperty("产品名称")
private String mqtt_username;
@ApiModelProperty("数据更新时间")
private Integer data_update_time;
public Integer getData_update_time() {
return data_update_time;
}
public void setData_update_time(Integer data_update_time) {
this.data_update_time = data_update_time;
}
public Integer getProduct_id() {
return product_id;
}
... ...
... ... @@ -21,14 +21,14 @@
# rssi 设备强度(信号极好[-55— 0],信号好[-70— -55],信号一般[-85— -70],信号差[-100— -85])
# status 设备状态,固定为3,表示在线
# userId 用户的ID,1=admin
# firmwareVersion 固件版本
# firmware_version 固件版本
# longitude 经度,可选,使用设备定位时需要上传
# latitude 纬度,可选,使用设备定位时需要上传
# summary 摘要,可选,设备的配置信息等,json格式,对象可自定义
{
"0":{
"rssi": -43,
"firmwareVersion": 1.2,
"firmware_version": 1.2,
"longitude": 0,
"latitude": 0,
"summary": {
... ... @@ -134,7 +134,7 @@
{
"0":{
"restart": 1,
"firmwareVersion": 1.2,
"firmware_version": 1.2,
"longitude": 0,
"latitude": 0,
"summary": {
... ...
... ... @@ -139,8 +139,17 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
... ...
package com.zhonglai.luhui.mqtt.comm.agreement;
import com.alibaba.fastjson.JSONObject;
import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;
import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreementFactory;
import com.zhonglai.luhui.mqtt.comm.factory.Topic;
... ...
package com.zhonglai.luhui.mqtt.comm.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
... ... @@ -54,7 +55,7 @@ public class RedisConfig {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
om.activateDefaultTyping(om.getPolymorphicTypeValidator(),ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
jackson2JsonRedisSerializer.setObjectMapper(om);
//普通的值采用jackson方式自动序列化
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
... ...
... ... @@ -13,12 +13,16 @@ import com.zhonglai.luhui.mqtt.dto.topic.AddPostDto;
import com.zhonglai.luhui.mqtt.service.db.DeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.*;
/**
* 业务数据更新服务
... ... @@ -50,11 +54,6 @@ public class BusinessDataUpdateService {
*/
public void updataDta(Type type,Topic topic, JSONObject data,boolean isOperLog,List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list)
{
if(1==deviceService.getlockIotDevice(topic.getClientid()))
{
logger.info("设备锁定等待解锁");
return;
}
IotDevice olddevice = deviceService.getRedicDevice(topic.getClientid());
for(String key:data.keySet())
... ... @@ -77,11 +76,15 @@ public class BusinessDataUpdateService {
{
iotDevice.setStatus(3);
}
iotDevice.setDevice_life(olddevice.getDevice_life());
iotDevice.setData_update_time(DateUtils.getNowTimeMilly());
iotDevice.setName(olddevice.getName());
deviceService.updataDevice(iotDevice);
}else{ //终端
IotTerminal iotTerminal = translateTerminal(type,key,olddevice,jsData,isOperLog,operateHisList,list);
logger.info("更新终端数据{}",iotTerminal);
deviceService.updataTerminal(iotTerminal);
iotTerminal.setData_update_time(DateUtils.getNowTimeMilly());
deviceService.updataTerminal(iotTerminal,olddevice.getDevice_life());
}
}
}
... ... @@ -106,10 +109,7 @@ public class BusinessDataUpdateService {
jsData.remove("summary");
}
IotDevice device = JSONObject.parseObject(JSONObject.toJSONString(jsData),IotDevice.class);
device.setClient_id(olddevice.getClient_id());
device.setUpdate_time(DateUtils.getNowTimeMilly());
device.setMqtt_username(olddevice.getMqtt_username());
device.setProduct_id(olddevice.getProduct_id());
device = (IotDevice) mergerData(olddevice,device);
if(null != summaryObjec)
{
device.setSummary(summaryObjec.toString());
... ... @@ -148,7 +148,6 @@ public class BusinessDataUpdateService {
SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( id,olddevice.getMqtt_username(),jsData,"终端本地",isOperLog,operateHisList,list);
IotTerminal terminal = new IotTerminal();
terminal.setId(id);
terminal.setUpdate_time(DateUtils.getNowTimeMilly());
terminal.setDevice_id(olddevice.getClient_id());
terminal.setProduct_id(olddevice.getProduct_id());
terminal.setMqtt_username(olddevice.getMqtt_username());
... ... @@ -162,7 +161,7 @@ public class BusinessDataUpdateService {
oldterminal.setMqtt_username(olddevice.getMqtt_username());
oldterminal.setName(olddevice.getMqtt_username()+"终端"+key);
oldterminal.setProduct_id(olddevice.getProduct_id());
deviceService.updataTerminal(oldterminal);
deviceService.updataTerminal(oldterminal,olddevice.getDevice_life());
}
if(null != oldterminal && ("ADD".equals(type.name())|| "READ".equals(type.name())))
{
... ... @@ -177,7 +176,7 @@ public class BusinessDataUpdateService {
}
String str = (null!=oldterminal?oldterminal.getThings_model_config():null);
terminal.setThings_model_config(deviceService.getNewAdddate(str,saveDataDto.getConfig()).toJSONString());
terminal.setName(oldterminal.getName());
return terminal;
}
... ... @@ -185,4 +184,54 @@ public class BusinessDataUpdateService {
{
ADD,ALL
}
public static void main(String[] args) {
IotDevice sourceBean = new IotDevice();
sourceBean.setName("sss");
sourceBean.setUpdate_time(21313);
IotDevice targetBean = new IotDevice();
targetBean.setClient_id("21321");
targetBean.setName("bbb");
Object newO = mergerData(sourceBean,targetBean);
System.out.println(JSONObject.toJSONString(newO));
}
private static Object mergerData(Object sourceBean, Object targetBean)
{
if(null == sourceBean)
{
return targetBean;
}
if(null == targetBean)
{
return sourceBean;
}
Object newtargetBean = BeanUtils.instantiateClass(targetBean.getClass());
BeanUtils.copyProperties(targetBean,newtargetBean);
BeanUtils.copyProperties(sourceBean,newtargetBean,getNotNullField(newtargetBean));
return newtargetBean;
}
/**
* 获取属性中为空的字段
*
* @param target
* @return
*/
private static String[] getNotNullField(Object target) {
BeanWrapper beanWrapper = new BeanWrapperImpl(target);
PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
Set<String> notNullFieldSet = new HashSet<>();
if (propertyDescriptors.length > 0) {
for (PropertyDescriptor p : propertyDescriptors) {
String name = p.getName();
Object value = beanWrapper.getPropertyValue(name);
if (Objects.nonNull(value)) {
notNullFieldSet.add(name);
}
}
}
String[] notNullField = new String[notNullFieldSet.size()];
return notNullFieldSet.toArray(notNullField);
}
}
... ...
... ... @@ -41,7 +41,12 @@ public class DataModeAnalysisService {
*/
public void initDataThingsMode(String roleIds,String usernames)
{
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+")";
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 ";
if(StringUtils.isNotEmpty(roleIds))
{
sql += " AND b.`role_id` IN("+roleIds+")";
}
if(StringUtils.isNotEmpty(usernames))
{
sql += " AND b.`username` IN("+usernames+")";
... ... @@ -108,13 +113,21 @@ public class DataModeAnalysisService {
operateHisList.add(dviceLogService.newLogDeviceOperation(id,thingsModelBase.getSaveView(),null,controlModel+thingsModelItemBase.getName()+"为"+thingsModelBase.getView(),jsData.toString()));
}
if(1==thingsModel.getIs_config())
if(null != thingsModel && null != thingsModel.getType() && 2==thingsModel.getType())
{
config.put(key,thingsModelBase);
data.put(key,thingsModelBase);
}else
{
if(null != thingsModel && null !=thingsModel.getIs_config() && 1==thingsModel.getIs_config())
{
config.put(key,thingsModelBase);
}else{
data.put(key,thingsModelBase);
}
}
}
SaveDataDto saveDataDto = new SaveDataDto();
saveDataDto.setConfig(config);
saveDataDto.setData(data);
... ...
... ... @@ -68,7 +68,11 @@ public class MqttCallback implements MqttCallbackExtended {
//准备数据
byte[] data = mqttMessage.getPayload();
IotDevice iotDevice = deviceService.getDeviceById(topic.getClientid());
if(null == iotDevice)
{
log.info("设备{}不存在",topic.getClientid());
return;
}
if("ONLINE".equals(topic.getTopicType().toUpperCase()))
{
topic.setPayloadtype("String");
... ...
... ... @@ -107,7 +107,7 @@ public class TerminalService {
if(null != topic)
{
String rild = topic.getRoleid();
if(StringUtils.isNoneBlank(rild))
if(StringUtils.isNoneBlank(rild) && !"+".equals(rild))
{
if(!"".equals(roleids))
{
... ...
... ... @@ -23,8 +23,6 @@ public class RedisService {
@Resource
private RedisTemplate<String,Object> redisTemplate;
@Value("${mqtt.client.device_life}")
private long device_life; //设备生命周期
/**
* @param key
... ... @@ -51,7 +49,7 @@ public class RedisService {
* @param value
* @return
*/
public boolean setexDevice(String key,Object value){
public boolean setexDevice(String key,long device_life,Object value){
try{//TimeUnit.SECONDS指定类型为秒
redisTemplate.opsForValue().set(key,value,device_life, TimeUnit.SECONDS);
return true;
... ...
... ... @@ -99,11 +99,8 @@ public class DeviceController {
@Transactional
@RequestMapping(value = "delIotDevice/{client_id}",method = RequestMethod.POST)
public Message delIotDevice(@PathVariable String client_id) throws MqttException, InterruptedException {
deviceService.lockIotDevice(client_id);//先锁定
closeSession(client_id); //强制下线
baseDao.updateBySql("DELETE FROM `iot_terminal` WHERE device_id='"+client_id+"'");
baseDao.updateBySql("DELETE FROM `iot_device` WHERE client_id='"+client_id+"'");
deviceService.unlockIotDevice(client_id);//解锁
deviceService.deletRedisDevice(client_id);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
... ... @@ -111,10 +108,8 @@ public class DeviceController {
@Transactional
@RequestMapping(value = "delIotTerminal/{client_id}/{number}",method = RequestMethod.POST)
public Message delIotTerminal(@PathVariable String client_id,@PathVariable String number) throws MqttException, InterruptedException {
deviceService.lockIotDevice(client_id);//先锁定
closeSession(client_id); //强制下线
baseDao.updateBySql("DELETE FROM `iot_terminal` WHERE id='"+client_id+"_"+number+"'");
deviceService.unlockIotDevice(client_id);//解锁
deviceService.deletRedisTerminal(client_id+"_"+number);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
... ...
... ... @@ -11,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
@Service
public class DeviceService {
... ... @@ -56,12 +57,14 @@ public class DeviceService {
*/
public IotDevice getRedicDevice(String id)
{
Object object = redisService.get(RedisConfig.FIELD+RedisConfig.DEVICE+id);
Object object = redisService.get(getRedicDeviceKey(id));
if(null != object)
{
return (IotDevice)object;
}else{
return getDeviceById(id);
IotDevice iotDevice = getDeviceById(id);
setRedicDevice(iotDevice);
return iotDevice;
}
}
... ... @@ -78,7 +81,8 @@ public class DeviceService {
*/
private boolean setRedicDevice(IotDevice device)
{
return redisService.setexDevice(getRedicDeviceKey(device.getClient_id()),device);
System.out.println("更新 "+device.getClient_id()+" 缓存,生命周期为 "+device.getDevice_life());
return redisService.setexDevice(getRedicDeviceKey(device.getClient_id()),device.getDevice_life(),device);
}
public String getRedicDeviceKey(String client_id)
... ... @@ -86,6 +90,11 @@ public class DeviceService {
return getRedicDeviceKeyPath()+client_id;
}
public String getRedicTerminalFromClientId(String client_id)
{
return RedisConfig.FIELD+"*:"+client_id+"*";
}
public String getRedicDeviceKeyPath()
{
return RedisConfig.FIELD+RedisConfig.DEVICE;
... ... @@ -98,7 +107,7 @@ public class DeviceService {
*/
public IotTerminal getRedicTerminal(String id)
{
Object object = redisService.get(RedisConfig.FIELD+RedisConfig.TERMINAL+id);
Object object = redisService.get(getRedicTerminalKey(id));
if(null == object)
{
IotTerminal terminal = getTerminalById(id);
... ... @@ -117,9 +126,9 @@ public class DeviceService {
* @param terminal
* @return
*/
private boolean setRedicTerminal(IotTerminal terminal)
private boolean setRedicTerminal(IotTerminal terminal,long device_life)
{
return redisService.setexDevice(getRedicTerminalKey(terminal.getId()),terminal);
return redisService.setexDevice(getRedicTerminalKey(terminal.getId()),device_life,terminal);
}
public String getRedicTerminalKey(String terminal_id)
... ... @@ -132,9 +141,9 @@ public class DeviceService {
return RedisConfig.FIELD+RedisConfig.TERMINAL;
}
public void updataTerminal(IotTerminal terminal)
public void updataTerminal(IotTerminal terminal,long device_life)
{
setRedicTerminal(terminal);
setRedicTerminal(terminal,device_life);
baseDao.saveOrUpdateObject(terminal);
}
... ... @@ -159,33 +168,29 @@ public class DeviceService {
}
/**
* 上锁
* @param clint_id
*/
public void lockIotDevice(String clint_id)
{
redisService.setexDevice(RedisConfig.FIELD+RedisConfig.LOCK+clint_id,1);
}
/**
* 获取锁
* @param clint_id
* 删除主机
* @param client_id
*/
public int getlockIotDevice(String clint_id)
public void deletRedisDevice(String client_id)
{
Object object = redisService.get(RedisConfig.FIELD+RedisConfig.LOCK+clint_id);
if(null==object)
Set<String> keys = redisService.keys(getRedicTerminalFromClientId(client_id));
if(null != keys && keys.size() != 0)
{
return 0;
redisService.del(keys.toArray(new String[keys.size()]));
}
return (int)object;
}
/**
* 解锁锁
* @param clint_id
* 删除终端
* @param client_ids
*/
public void unlockIotDevice(String clint_id)
public void deletRedisTerminal(String... client_ids)
{
redisService.del(RedisConfig.FIELD+RedisConfig.LOCK+clint_id);
String[] keys = new String[client_ids.length];
for (int i=0;i<client_ids.length;i++)
{
keys[i] = getRedicTerminalKey(client_ids[i]);
}
redisService.del(keys);
}
}
... ...
... ... @@ -3,20 +3,14 @@ package com.zhonglai.luhui.mqtt.service.topic;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.IotThingsModel;
import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;
import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto;
import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelBase;
import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelDataTypeEnum;
import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelItemBase;
import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;
import com.zhonglai.luhui.mqtt.comm.factory.Topic;
import com.zhonglai.luhui.mqtt.comm.service.BusinessDataUpdateService;
import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService;
import com.zhonglai.luhui.mqtt.comm.service.DataModeAnalysisService;
import com.zhonglai.luhui.mqtt.comm.util.DateUtils;
import com.zhonglai.luhui.mqtt.dto.SaveDataDto;
import com.zhonglai.luhui.mqtt.dto.topic.AddPostDto;
import com.zhonglai.luhui.mqtt.dto.topic.ReadReqDto;
import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService;
import org.apache.commons.lang3.EnumUtils;
... ...
... ... @@ -18,7 +18,7 @@ spring:
##redic配置
redis:
database: 0
database: 1
# Redis服务器地址 写你的ip
host: 47.112.163.61
# Redis服务器连接端口
... ... @@ -42,9 +42,9 @@ mqtt:
#链接地址
broker: tcp://175.24.61.68:1883
#唯一标识
clientId: lh-mqtt-service-003
clientId: ${random.uuid}
#订阅的topic
topics: "/2/+/+/+/ADD_POST,/2/+/+/+/ALL_POST,/2/+/+/+/DB_TOPIC_DISTRIBUTE,/2/+/+/+/GET/+,/2/+/+/+/online,/2/+/+/+/PUT_REQ/+,/2/+/+/+/READ_REQ/+"
topics: "/+/+/+/+/ADD_POST,/+/+/+/+/ALL_POST,/+/+/+/+/DB_TOPIC_DISTRIBUTE,/+/+/+/+/GET/+,/+/+/+/+/online,/+/+/+/+/PUT_REQ/+,/+/+/+/+/READ_REQ/+"
topicconfig: "/{{roleid}}/{{username}}/{{clientid}}/{{payloadtype}}/{{topicType}}/{{messageid}}"
top_return_map: '{"PUT":"PUT_REQ","READ":"READ_REQ"}'
username: sysuser
... ... @@ -52,7 +52,6 @@ mqtt:
client:
#客户端操作时间
operationTime: 5
device_life: 180
redis:
key:
#角色
... ... @@ -63,4 +62,4 @@ mqtt:
sys:
redis:
field: "luhui:mqttservice:device:"
isText: true
isText: false
... ...
... ... @@ -15,6 +15,8 @@
<module>lh-admin</module>
<module>lh-mqtt-service</module>
<module>lh-domain</module>
<module>lh-api</module>
<module>lh-central-control</module>
</modules>
<packaging>pom</packaging>
... ... @@ -322,6 +324,12 @@
<artifactId>expiringmap</artifactId>
<version>0.5.8</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.3</version>
</dependency>
</dependencies>
... ...
... ... @@ -35,6 +35,15 @@ public class HttpUtils {
.writeTimeout(20, TimeUnit.SECONDS)
.build();
public static String getResponseString(Response response)
{
try {
return response.body().string();
} catch (IOException e) {
}
return null;
}
public static Response postJsonBody(String url,JsonBody jsonBody) throws IOException {
return postJsonBody(url,null,jsonBody);
}
... ...
package com.ruoyi.system.dto;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
public class PublicSQL {
private String changTableNameFromObject(Object object)
{
return com.ruoyi.common.utils.StringUtils.toUnderScoreCase(object.getClass().getName());
}
private String insertListSql(List<?> list, String tableName)
{
if(StringUtils.isBlank(tableName))
{
tableName = changTableNameFromObject(list.get(0));
}
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO "+tableName);
String values = "";
String mfStr = "";
Field[] fields = list.get(0).getClass().getDeclaredFields( );
for(Field field:fields)
{
if(!"".equals(values) )
{
mfStr += ",";
values += ",";
}
values += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`";
mfStr += "#'{'list[{0}]."+field.getName()+"}";
}
sb.append("("+values+")");
sb.append("VALUES ");
MessageFormat mf = new MessageFormat("("+mfStr+")");
for (int i = 0; i < list.size(); i++) {
sb.append(mf.format(new Object[]{i}));
if (i < list.size() - 1) {
sb.append(",");
}
}
return sb.toString();
}
public String insertAllToTable(Map map)
{
List<?> list = (List<?>) map.get("list");
String tableName = (String) map.get("tableName");
return insertListSql(list,tableName);
}
/**
* 添加对象
* @return
*/
public String insertAll(Map map)
{
List<?> list = (List<?>) map.get("list");
return insertListSql(list,null);
}
/**
* 添加对象
* @param object 对象
* @return
*/
public String insert(Object object)
{
StringBuffer stringBuffer = new StringBuffer("insert into ");
String tableName = changTableNameFromObject(object);
stringBuffer.append(tableName + "(");
Field[] fields = object.getClass().getDeclaredFields( );
StringBuffer values = new StringBuffer("(");
for(Field field:fields)
{//
Method method;
try {
method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(null != value)
{
if(!"(".equals(values.toString()) )
{
stringBuffer.append(",");
values.append( ",");
}
stringBuffer.append( "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`");
values.append( "'"+ escapeSql(value+"")+"'");
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
stringBuffer.append( ")");
values.append( ")");
return stringBuffer.append(" values ").append(values).toString();
}
/**
* 指定表名添加对象
* @param object
* @return
*/
public String insertToTable(Object object)
{
String tableName = changTableNameFromObject(object);
StringBuffer sql = new StringBuffer();
sql.append("insert into ");
sql.append(tableName + "(");
Field[] fields = object.getClass().getDeclaredFields( );
String values = "(";
for(Field field:fields)
{//
Method method;
try {
method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(null != value)
{
if(!"(".equals(values) )
{
sql.append(",");
values += ",";
}
sql.append("`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`");
values += "'"+escapeSql(value+"")+"'";
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sql.append(")");
values += ")";
return sql.toString()+" values "+values;
}
/**
* 更新对象不为空的属性
* @param para
* @return
*/
public String updateObject(Map<String,Object> para)
{
Object object = para.get("object");
String whereFieldNames = (String) para.get("whereFieldNames");
String tableName = changTableNameFromObject(object);
String sql = "update ";
sql += tableName;
Field[] fields = object.getClass().getDeclaredFields();
if(null != fields && fields.length !=0 )
{
sql += " set ";
int j = 0;
for(int i=0;i<fields.length;i++)
{
Field field = fields[i];
try {
Method method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(null != value)
{
if(j!=0)
{
sql += ",";
}
sql += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+"='"+escapeSql(value+"")+"'";
j++;
// if(i!=0)
// {
// sql += ",";
// }
// sql += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+"='"+value+"'";
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sql += " where 1=1 ";
String[] wheres = whereFieldNames.split(",");
if(StringUtils.isNotBlank(whereFieldNames))
{
for(int i =0;i<wheres.length;i++)
{
try {
Method method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(wheres[i]));
Object value = method.invoke(object);
sql += " and ";
sql += com.ruoyi.common.utils.StringUtils.toUnderScoreCase(wheres[i]) + "='"+escapeSql(value+"")+"'";
// sql += com.ruoyi.common.utils.StringUtils.getName(wheres[i]) + "='"+value+"'";
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return sql;
}
/**
* 获得对象
*/
public String getObject(Map<String, Object> para)
{
Class<?> clas = (Class<?>) para.get("class");
String idName = (String) para.get("idName");
String values = (String) para.get("values");
String tableName = null;
if(para.containsKey("tableName"))
{
tableName = (String) para.get("tableName");
}
String select = "*";
if(para.containsKey("select") && null != para.get("select"))
{
select = (String) para.get("select");
}
if(StringUtils.isBlank(tableName))
{
tableName = com.ruoyi.common.utils.StringUtils.toUnderScoreCase(clas.getSimpleName());
}
String[] idnames = idName.split(",");
String[] valuess = values.split(",");
String where = "";
for(int i=0;i<idnames.length;i++)
{
if(i != 0)
{
where += " and ";
}
where += "`"+idnames[i]+"`='"+escapeSql(valuess[i]+"")+"'";
}
String sql = "select "+select+" from "+tableName + " where " +where;
return sql;
}
/**
* 通过条件删除数据
* @param para
* @return
*/
public String deleteObjectByContent(Map<String, Object> para)
{
Class<?> objectCalss = (Class<?>) para.get("objectCalss");
String tableName = null;
if(para.containsKey("tableName"))
{
tableName = (String) para.get("tableName");
}
@SuppressWarnings("unchecked")
Map<String,String> map = (Map<String, String>) para.get("map");
if(StringUtils.isBlank(tableName))
{
tableName = com.ruoyi.common.utils.StringUtils.toUnderScoreCase(objectCalss.getSimpleName());
}
String sql = "delete from ";
sql += tableName + " where 1=1 ";
for(String key:map.keySet())
{
sql += " and "+"`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(key)+"`"+"='"+escapeSql(map.get(key)+"")+"'";
}
return sql;
}
/**
* 通过id删除数据
* @param para
* @return
*/
public String deleteObjectById(Map<String, Object> para)
{
Class<?> objectCalss = (Class<?>) para.get("objectCalss");
String tableName = null;
if(para.containsKey("tableName"))
{
tableName = (String) para.get("tableName");
}
String id = (String) para.get("id");
if(StringUtils.isBlank(tableName))
{
tableName = com.ruoyi.common.utils.StringUtils.toUnderScoreCase(objectCalss.getSimpleName());
}
String sql = "delete from ";
sql += tableName + " where 1=1 ";
sql += " and "+"`id`"+"='"+escapeSql(id)+"'";
return sql;
}
/**
* 获取对象列表总数
*/
public String getObjectListTotle(Map<String, Object> para)
{
Object object = para.get("object");
@SuppressWarnings("unchecked")
Map<String,String> whereMap = (Map<String, String>) para.get("whereMap");
String tableName = changTableNameFromObject(object);
String sql = "select count(*) from "+tableName;
String where = " where 1=1 ";
String like = "";
Field[] fields = object.getClass().getDeclaredFields();
if(null != fields && fields.length !=0 )
{
for(Field field:fields)
{
try {
Method method;
method = object.getClass().getMethod("get"+ com.ruoyi.common.utils.StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(null != value)
{
String orther = "";
String s = "=";
if(null != whereMap && null != whereMap.get(field.getName()))
{
s = whereMap.get(field.getName());
if("like".equals(s))
{
value = "%"+value+"%";
like += " or " + "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" '"+escapeSql(value+"")+"'"+orther ;
continue;
}
if("time".equals(s))
{
s = ">";
orther = " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`< '"+whereMap.get("end_"+field.getName())+"'";
}
if("in".equals(s))
{
s = "in";
value = (value+"").replace(",","','");
where += " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" ("+"'"+value+"'"+")"+orther;
continue;
}
}
where += " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" '"+escapeSql(value+"")+"'"+orther;
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
sql += where;
if(StringUtils.isNoneBlank(like))
{
sql += " and (1=2 "+like+")";
}
return sql;
}
/**
* 获取对象列表
*/
public String getObjectList(Map<String, Object> para)
{
Object object = para.get("object");
@SuppressWarnings("unchecked")
Map<String,String> whereMap = (Map<String, String>) para.get("whereMap");
String selectStr = " * ";
String order = "";
if(para.containsKey("order") && null != para.get("order"))
{
order = para.get("order") +"";
}
Integer pageSize = 0;
if(para.containsKey("pageSize") && null != para.get("pageSize"))
{
pageSize = (Integer) para.get("pageSize");
}
Integer pageNo = 0;
if(para.containsKey("pageNo") && null != para.get("pageNo"))
{
pageNo = (Integer) para.get("pageNo");
}
if(para.containsKey("selectStr") && null != para.get("selectStr"))
{
selectStr = para.get("selectStr")+"";
}
String tableName = changTableNameFromObject(object);
if(para.containsKey("tableName") && null != para.get("tableName"))
{
tableName = para.get("tableName")+"";
}
String sql = "select "+selectStr+" from "+tableName;
String where = " where 1=1 ";
String like = "";
Field[] fields = object.getClass().getDeclaredFields();
if(null != fields && fields.length !=0 )
{
for(int i=0;i<fields.length;i++)
{
Field field = fields[i];
try {
Method method;
method = object.getClass().getMethod("get"+ com.ruoyi.common.utils.StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(!(null == value))
{
String orther = "";
String s = "=";
if(!(null == whereMap || null == whereMap.get(field.getName())))
{
s = whereMap.get(field.getName());
if("like".equals(s))
{
value = "%"+value+"%";
like += " or " + "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" '"+escapeSql(value+"")+"'"+orther ;
continue;
}
if("time".equals(s))
{
s = ">";
orther = " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`< '"+whereMap.get("end_"+field.getName())+"'";
}
if("in".equals(s))
{
s = "in";
value = (value+"").replace(",","','");
where += " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" ("+"'"+value+"'"+")"+orther;
continue;
}
}
where += " and `"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+s+" '"+escapeSql(value+"")+"'"+orther;
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
sql += where;
if(StringUtils.isNoneBlank(like))
{
sql += " and (1=2 "+like+")";
}
if(StringUtils.isNotBlank(order))
{
sql += " order by "+order;
}
if(0 != pageSize && 0 != pageNo)
{
sql += " limit "+((pageNo-1)*pageSize)+","+pageSize;
}
return sql;
}
/**
* 添加或更新对象
* INSERT INTO test(`in1`,`str1`) VALUES ('1','1');
* @param object 对象
* @return
*/
public String saveOrUpdateObject(Object object)
{
String sql = "insert into ";
String tableName = changTableNameFromObject(object);
sql += tableName + "(";
Field[] fields = object.getClass().getDeclaredFields( );
String values = "(";
String update = "";
for(Field field:fields)
{//
Method method;
try {
method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(null != value)
{
if(!"(".equals(values) )
{
sql += ",";
values += ",";
update += ",";
}
sql += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`";
values += "'"+ escapeSql(value+"")+"'";
update += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+"=VALUES("+"`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`)";
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sql += ")";
values += ")";
return sql+" values "+values+" ON DUPLICATE KEY UPDATE "+update;
}
/**
* 添加或更新对象列表
* INSERT INTO `test` (`in1`,`str1`)VALUES ('1','2'),('2','2') ON DUPLICATE KEY UPDATE `in1`=VALUES(`in1`),`str1`=VALUES(`str1`);
* @param objectlist 对象列表
* @return
*/
public String saveOrUpdateObjectList(List<Object> objectlist)
{
StringBuffer sb =new StringBuffer();
String update = "";
for(int i = 0; i<objectlist.size();i++)
{
Object object = objectlist.get(i);
Field[] fields = object.getClass().getDeclaredFields( );
if(i==0)
{
String tableName = changTableNameFromObject(object);
sb.append("INSERT INTO `"+tableName+"` ");
sb.append("(");
for(Field field:fields)
{
if(!"".equals(update) )
{
sb.append(",");
update += ",";
}
sb.append("`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`");
update += "`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`"+"=VALUES("+"`"+com.ruoyi.common.utils.StringUtils.toUnderScoreCase(field.getName())+"`)";
}
sb.append(")");
sb.append("VALUES ");
}else{
sb.append(",");
}
for(int j=0;j<fields.length;j++)
{
Field field = fields[j];
Method method;
try {
method = object.getClass().getMethod("get"+com.ruoyi.common.utils.StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(null == value)
{
value = "";
}
if(j!=0)
{
sb.append(",");
}else{
sb.append("(");
}
sb.append("'"+ escapeSql(value+"")+"'");
if(j==fields.length-1)
{
sb.append(")");
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
sb.append(" ON DUPLICATE KEY UPDATE ");
sb.append(update);
return sb.toString();
}
public String getObjectListBySQL(Map<String, Object> para)
{
return para.get("sql")+"";
}
public String updateBySql(Map<String, Object> para)
{
return para.get("sql")+"";
}
public static String escapeSql(String str) {
return str == null ? null : StringUtils.replace(str, "'", "''");
}
}
... ...
package com.ruoyi.system.mapper;
import java.util.List;
import com.ruoyi.system.domain.IotProductTranslate;
/**
* 产品指标翻译Mapper接口
*
* @author 钟来
* @date 2022-11-04
*/
public interface IotProductTranslateMapper
{
/**
* 查询产品指标翻译
*
* @param id 产品指标翻译主键
* @return 产品指标翻译
*/
public IotProductTranslate selectIotProductTranslateById(Integer id);
/**
* 查询产品指标翻译列表
*
* @param iotProductTranslate 产品指标翻译
* @return 产品指标翻译集合
*/
public List<IotProductTranslate> selectIotProductTranslateList(IotProductTranslate iotProductTranslate);
/**
* 新增产品指标翻译
*
* @param iotProductTranslate 产品指标翻译
* @return 结果
*/
public int insertIotProductTranslate(IotProductTranslate iotProductTranslate);
int insertAll(List<IotProductTranslate> list);
/**
* 修改产品指标翻译
*
* @param iotProductTranslate 产品指标翻译
* @return 结果
*/
public int updateIotProductTranslate(IotProductTranslate iotProductTranslate);
/**
* 删除产品指标翻译
*
* @param id 产品指标翻译主键
* @return 结果
*/
public int deleteIotProductTranslateById(Integer id);
/**
* 批量删除产品指标翻译
*
* @param ids 需要删除的数据主键集合
* @return 结果
*/
public int deleteIotProductTranslateByIds(Integer[] ids);
List<IotProductTranslate> selectIotProductTranslateListByIds(Integer[] ids);
}
... ...
... ... @@ -58,4 +58,5 @@ public interface IotTerminalMapper
* @return 结果
*/
public int deleteIotTerminalByIds(String[] ids);
int deleteIotTerminalByDeviceId(String deviceId);
}
... ...
package com.ruoyi.system.mapper;
import com.ruoyi.system.dto.PublicSQL;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Map;
/**
* 公用mapper
*/
public interface PublicMapper {
/**
* 添加对象
*/
@InsertProvider(type = PublicSQL.class, method = "insert")
int insert(Object object);
/**
* 指定表名添加
*/
@InsertProvider(type = PublicSQL.class, method = "insertToTable")
int insertToTable(Object object,String tableName);
/**
* 添加对象集合
*/
@InsertProvider(type = PublicSQL.class, method = "insertAll")
int insertAll(List<?> list);
/**
* 指定表名添加对象集合
*/
@InsertProvider(type = PublicSQL.class, method = "insertAllToTable")
int insertAllToTable(List<?> list,String tableName);
/**
* 更新对象不为空的属性
* @param object
* @param whereFieldNames
*/
@UpdateProvider(type = PublicSQL.class, method = "updateObject")
void updateObject(@Param("object") Object object, @Param("whereFieldNames") String whereFieldNames);
/**
* 自定义sql更新
* @param sql
*/
@UpdateProvider(type = PublicSQL.class, method = "updateBySql")
void updateBySql(String sql);
/**
* 查询 通过条件查询
* @param clas
* @param idName
* @param values
* @return
*/
@SelectProvider(type = PublicSQL.class, method = "getObject")
<T> T getObject(@Param("class") Class<?> clas, @Param("idName") String idName, @Param("values") String values);
/**
* 查询 通过条件查询
* @param clas
* @param idName
* @param values
* @return
*/
@SelectProvider(type = PublicSQL.class, method = "getObject")
Map<String,Object> getObjectForTableName(@Param("class") Class<?> clas, @Param("idName") String idName, @Param("values") String values, @Param("tableName") String tableName);
/**
* 查询 通过条件查询单个指定项目
* @param clas 類型
* @param select 查詢結果
* @param idName 主鍵名稱
* @param values 主鍵值
* @return
*/
@SelectProvider(type = PublicSQL.class, method = "getObject")
Map<String,Object> getObjectSelectTableName(@Param("class") Class<?> clas, @Param("select") String select, @Param("idName") String idName, @Param("values") String values, @Param("tableName") String tableName);
/**
* 查询list
* @param object
* @param whereMap 如果是时间,whereMap里面对应的字段比较符为time,同时添加一个end_字段名的值 表示是结束时间
* @param order
* @param pagetSize
* @param pageNo
* @return
*/
@SelectProvider(type = PublicSQL.class, method = "getObjectList")
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);
/**
* 查詢totle
* @param object
* @param whereMap 如果是时间,whereMap里面对应的字段比较符为time,同时添加一个end_字段名的值 表示是结束时间
* @return
*/
@SelectProvider(type = PublicSQL.class, method = "getObjectListTotle")
Long getObjectListTotle(@Param("object") Object object, @Param("whereMap") Map<String, String> whereMap);
/**
* 通过条件删除对象
* @param oClass
* @param map
*/
@UpdateProvider(type = PublicSQL.class, method = "deleteObjectByContent")
void deleteObjectByContent(@Param("objectCalss") Class<?> oClass, @Param("map") Map<String, String> map);
/**
* 自定义sql语句查询list
* @param sql
* @return
*/
@SelectProvider(type = PublicSQL.class, method = "getObjectListBySQL")
List<Map<String,Object>> getObjectListBySQL(@Param("sql") String sql);
/**
* 添加或更新对象列表
* INSERT INTO `test` (`in1`,`str1`)VALUES ('1','2'),('2','2') ON DUPLICATE KEY UPDATE `in1`=VALUES(`in1`),`str1`=VALUES(`str1`);
* @param objectlist 对象列表
* @return
*/
@UpdateProvider(type = PublicSQL.class, method = "saveOrUpdateObjectList")
void saveOrUpdateObjectList(List<Object> objectlist);
/**
* 添加或更新对象
* INSERT INTO test(`in1`,`str1`) VALUES ('1','1');
* @param object 对象
* @return
*/
@UpdateProvider(type = PublicSQL.class, method = "saveOrUpdateObject")
void saveOrUpdateObject(Object object);
/**
* 通过id删除数据
* @return
*/
@UpdateProvider(type = PublicSQL.class, method = "deleteObjectById")
void deleteObjectById(@Param("objectCalss") Class<?> oClass, @Param("id") String id);
@Options(useGeneratedKeys = false)
@InsertProvider(type = PublicSQL.class, method = "updateBySql")
void insertIntoBySql(@Param("sql") String sql);
}
... ...
package com.ruoyi.system.service;
import java.util.List;
import com.ruoyi.system.domain.IotProductTranslate;
/**
* 产品指标翻译Service接口
*
* @author 钟来
* @date 2022-11-04
*/
public interface IIotProductTranslateService
{
/**
* 查询产品指标翻译
*
* @param id 产品指标翻译主键
* @return 产品指标翻译
*/
public IotProductTranslate selectIotProductTranslateById(Integer id);
/**
* 查询产品指标翻译列表
*
* @param iotProductTranslate 产品指标翻译
* @return 产品指标翻译集合
*/
public List<IotProductTranslate> selectIotProductTranslateList(IotProductTranslate iotProductTranslate);
/**
* 新增产品指标翻译
*
* @param iotProductTranslate 产品指标翻译
* @return 结果
*/
public int insertIotProductTranslate(IotProductTranslate iotProductTranslate);
int insertAll(List<IotProductTranslate> list);
/**
* 修改产品指标翻译
*
* @param iotProductTranslate 产品指标翻译
* @return 结果
*/
public int updateIotProductTranslate(IotProductTranslate iotProductTranslate);
/**
* 批量删除产品指标翻译
*
* @param ids 需要删除的产品指标翻译主键集合
* @return 结果
*/
public int deleteIotProductTranslateByIds(Integer[] ids);
/**
* 删除产品指标翻译信息
*
* @param id 产品指标翻译主键
* @return 结果
*/
public int deleteIotProductTranslateById(Integer id);
}
... ...
... ... @@ -58,4 +58,6 @@ public interface IIotTerminalService
* @return 结果
*/
public int deleteIotTerminalById(String id);
int deleteIotTerminalByDeviceId(String deviceId);
}
... ...
package com.ruoyi.system.service.impl;
import java.util.List;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.IotProduct;
import com.ruoyi.system.service.IIotProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.IotDeviceMapper;
... ... @@ -18,7 +23,8 @@ public class IotDeviceServiceImpl implements IIotDeviceService
{
@Autowired
private IotDeviceMapper iotDeviceMapper;
@Autowired
private IIotProductService iIotProductService;
/**
* 查询null
*
... ... @@ -52,6 +58,19 @@ public class IotDeviceServiceImpl implements IIotDeviceService
@Override
public int insertIotDevice(IotDevice iotDevice)
{
IotProduct iotProduct = iIotProductService.selectIotProductById(iotDevice.getProduct_id());
if(null == iotProduct)
{
throw new ServiceException("产品不存在");
}
IotDevice old = iotDeviceMapper.selectIotDeviceByClient_id(iotDevice.getClient_id());
if(null != old)
{
throw new ServiceException("设备已存在");
}
iotDevice.setMqtt_username(iotProduct.getMqtt_username());
iotDevice.setCreate_time(DateUtils.getNowTimeMilly());
iotDevice.setData_update_time(DateUtils.getNowTimeMilly());
return iotDeviceMapper.insertIotDevice(iotDevice);
}
... ...
package com.ruoyi.system.service.impl;
import java.util.List;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.IotProductTranslateMapper;
import com.ruoyi.system.domain.IotProductTranslate;
import com.ruoyi.system.service.IIotProductTranslateService;
/**
* 产品指标翻译Service业务层处理
*
* @author 钟来
* @date 2022-11-04
*/
@Service
public class IotProductTranslateServiceImpl implements IIotProductTranslateService
{
@Autowired
private IotProductTranslateMapper iotProductTranslateMapper;
@Autowired
private RedisCache redisCache;
private String productTranslateRedisKeyPath ="luhui:product:translate:";
/**
* 查询产品指标翻译
*
* @param id 产品指标翻译主键
* @return 产品指标翻译
*/
@Override
public IotProductTranslate selectIotProductTranslateById(Integer id)
{
return iotProductTranslateMapper.selectIotProductTranslateById(id);
}
/**
* 查询产品指标翻译列表
*
* @param iotProductTranslate 产品指标翻译
* @return 产品指标翻译
*/
@Override
public List<IotProductTranslate> selectIotProductTranslateList(IotProductTranslate iotProductTranslate)
{
return iotProductTranslateMapper.selectIotProductTranslateList(iotProductTranslate);
}
/**
* 新增产品指标翻译
*
* @param iotProductTranslate 产品指标翻译
* @return 结果
*/
@Override
public int insertIotProductTranslate(IotProductTranslate iotProductTranslate)
{
int ri = iotProductTranslateMapper.insertIotProductTranslate(iotProductTranslate);
upCache(iotProductTranslate);
return ri;
}
@Override
public int insertAll(List<IotProductTranslate> list) {
int ri = iotProductTranslateMapper.insertAll(list);
for(IotProductTranslate iotProductTranslate:list)
{
upCache(iotProductTranslate);
}
return ri;
}
/**
* 修改产品指标翻译
*
* @param iotProductTranslate 产品指标翻译
* @return 结果
*/
@Override
public int updateIotProductTranslate(IotProductTranslate iotProductTranslate)
{
int ri = iotProductTranslateMapper.updateIotProductTranslate(iotProductTranslate);
upCache(iotProductTranslate);
return ri;
}
/**
* 批量删除产品指标翻译
*
* @param ids 需要删除的产品指标翻译主键
* @return 结果
*/
@Override
public int deleteIotProductTranslateByIds(Integer[] ids)
{
List<IotProductTranslate> list = iotProductTranslateMapper.selectIotProductTranslateListByIds(ids);
int ri = iotProductTranslateMapper.deleteIotProductTranslateByIds(ids);
for(IotProductTranslate iotProductTranslate:list)
{
remCache(iotProductTranslate);
}
return ri;
}
/**
* 删除产品指标翻译信息
*
* @param id 产品指标翻译主键
* @return 结果
*/
@Override
public int deleteIotProductTranslateById(Integer id)
{
IotProductTranslate iotProductTranslate = iotProductTranslateMapper.selectIotProductTranslateById(id);
if(null == iotProductTranslate)
{
return 0;
}
remCache(iotProductTranslate);
return iotProductTranslateMapper.deleteIotProductTranslateById(id);
}
public void remCache(IotProductTranslate iotProductTranslate)
{
redisCache.delCacheMapValue(getProductTranslateRedisKey(iotProductTranslate.getProduct_id()),iotProductTranslate.getModel_identifier());
}
public void upCache(IotProductTranslate iotProductTranslate)
{
redisCache.setCacheMapValue(getProductTranslateRedisKey(iotProductTranslate.getProduct_id()),iotProductTranslate.getModel_identifier(),iotProductTranslate.getTranslate_identifier());
}
private String getProductTranslateRedisKey(Integer productId)
{
return productTranslateRedisKeyPath+productId;
}
}
... ...
package com.ruoyi.system.service.impl;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.IotTerminalMapper;
... ... @@ -90,4 +92,9 @@ public class IotTerminalServiceImpl implements IIotTerminalService
{
return iotTerminalMapper.deleteIotTerminalById(id);
}
@Override
public int deleteIotTerminalByDeviceId(String deviceId) {
return iotTerminalMapper.deleteIotTerminalByDeviceId(deviceId);
}
}
... ...
... ... @@ -32,10 +32,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="payload_type" column="payload_type" />
<result property="things_model_config" column="things_model_config" />
<result property="listen_service_ip" column="listen_service_ip" />
<result property="device_life" column="device_life" />
<result property="data_update_time" column="data_update_time" />
</resultMap>
<sql id="selectIotDeviceVo">
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
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
</sql>
<select id="selectIotDeviceList" parameterType="IotDevice" resultMap="IotDeviceResult">
... ... @@ -89,6 +92,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="mqtt_username != null">mqtt_username,</if>
<if test="payload_type != null">payload_type,</if>
<if test="things_model_config != null">things_model_config,</if>
<if test="device_life != null">device_life,</if>
<if test="data_update_time != null">data_update_time,</if>
create_time,
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
... ... @@ -116,7 +121,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="product_id != null">#{product_id},</if>
<if test="mqtt_username != null">#{mqtt_username},</if>
<if test="payload_type != null">#{payload_type},</if>
<if test="things_model_config != null">things_model_config,</if>
<if test="things_model_config != null">#{things_model_config},</if>
<if test="device_life != null">#{device_life},</if>
<if test="data_update_time != null">#{data_update_time},</if>
UNIX_TIMESTAMP(NOW()),
</trim>
</insert>
... ... @@ -149,6 +156,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="mqtt_username != null">mqtt_username = #{mqtt_username},</if>
<if test="payload_type != null">payload_type = #{payload_type},</if>
<if test="things_model_config != null">things_model_config = #{things_model_config},</if>
<if test="device_life != null">device_life = #{device_life},</if>
<if test="data_update_time != null">data_update_time = #{data_update_time},</if>
</trim>
where client_id = #{client_id}
</update>
... ...
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.system.mapper.IotProductTranslateMapper">
<resultMap type="IotProductTranslate" id="IotProductTranslateResult">
<result property="create_time" column="create_time" />
<result property="id" column="id" />
<result property="model_identifier" column="model_identifier" />
<result property="product_id" column="product_id" />
<result property="translate_identifier" column="translate_identifier" />
</resultMap>
<sql id="selectIotProductTranslateVo">
select `create_time`, `id`, `model_identifier`, `product_id`, `translate_identifier` from iot_product_translate
</sql>
<select id="selectIotProductTranslateList" parameterType="IotProductTranslate" resultMap="IotProductTranslateResult">
<include refid="selectIotProductTranslateVo"/>
<where>
<if test="product_id !=null and product_id != ''">
and product_id = #{product_id}
</if>
</where>
</select>
<select id="selectIotProductTranslateListByIds" parameterType="String" resultMap="IotProductTranslateResult">
<include refid="selectIotProductTranslateVo"/>
where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</select>
<select id="selectIotProductTranslateById" parameterType="Integer" resultMap="IotProductTranslateResult">
<include refid="selectIotProductTranslateVo"/>
where id = #{id}
</select>
<insert id="insertIotProductTranslate" parameterType="IotProductTranslate" useGeneratedKeys="true" keyProperty="id">
insert into iot_product_translate
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="create_time != null">create_time,</if>
<if test="model_identifier != null">model_identifier,</if>
<if test="product_id != null">product_id,</if>
<if test="translate_identifier != null">translate_identifier,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="create_time != null">#{create_time},</if>
<if test="model_identifier != null">#{model_identifier},</if>
<if test="product_id != null">#{product_id},</if>
<if test="translate_identifier != null">#{translate_identifier},</if>
</trim>
</insert>
<insert id="insertAll">
insert into iot_product_translate(`create_time`, `model_identifier`, `product_id`, `translate_identifier`) values
<foreach item="item" index="index" collection="list" separator=",">
( UNIX_TIMESTAMP(NOW()),#{item.model_identifier},#{item.product_id},#{item.translate_identifier})
</foreach>
</insert>
<update id="updateIotProductTranslate" parameterType="IotProductTranslate">
update iot_product_translate
<trim prefix="SET" suffixOverrides=",">
<if test="create_time != null">create_time = #{create_time},</if>
<if test="model_identifier != null">model_identifier = #{model_identifier},</if>
<if test="product_id != null">product_id = #{product_id},</if>
<if test="translate_identifier != null">translate_identifier = #{translate_identifier},</if>
</trim>
where id = #{id}
</update>
<delete id="deleteIotProductTranslateById" parameterType="Integer">
delete from iot_product_translate where id = #{id}
</delete>
<delete id="deleteIotProductTranslateByIds" parameterType="String">
delete from iot_product_translate where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>
\ No newline at end of file
... ...
... ... @@ -13,10 +13,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="things_model_config" column="things_model_config" />
<result property="product_id" column="product_id" />
<result property="mqtt_username" column="mqtt_username" />
<result property="data_update_time" column="data_update_time" />
</resultMap>
<sql id="selectIotTerminalVo">
select device_id, id, `name`, things_model_value, update_time,things_model_config,product_id,mqtt_username from iot_terminal
select device_id, id, `name`, things_model_value, update_time,things_model_config,product_id,mqtt_username,data_update_time from iot_terminal
</sql>
<select id="selectIotTerminalList" parameterType="IotTerminal" resultMap="IotTerminalResult">
... ... @@ -53,6 +54,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="things_model_config != null">things_model_config,</if>
<if test="product_id != null">product_id,</if>
<if test="mqtt_username != null">mqtt_username,</if>
<if test="data_update_time != null">data_update_time,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="device_id != null">#{device_id},</if>
... ... @@ -63,6 +65,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="things_model_config != null">#{things_model_config},</if>
<if test="product_id != null">#{product_id},</if>
<if test="mqtt_username != null">#{mqtt_username},</if>
<if test="data_update_time != null">#{data_update_time},</if>
</trim>
</insert>
... ... @@ -76,6 +79,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="things_model_config != null">things_model_config = #{things_model_config},</if>
<if test="product_id != null">product_id = #{product_id},</if>
<if test="mqtt_username != null">mqtt_username = #{mqtt_username},</if>
<if test="data_update_time != null">data_update_time = #{data_update_time},</if>
</trim>
where id = #{id}
</update>
... ... @@ -84,6 +88,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
delete from iot_terminal where id = #{id}
</delete>
<delete id="deleteIotTerminalByDeviceId" parameterType="String">
delete from iot_terminal where device_id = #{device_id}
</delete>
<delete id="deleteIotTerminalByIds" parameterType="String">
delete from iot_terminal where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
... ...