作者 钟来

新版x6开发

正在显示 37 个修改的文件 包含 1244 行增加368 行删除
package com.zhonglai.luhui.admin.controller.iot;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Message;
import com.ruoyi.common.core.domain.MessageCode;
import com.ruoyi.common.enums.BusinessType;
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 com.ruoyi.system.service.DeviceControlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Api(tags = "设备控制")
... ... @@ -32,19 +22,7 @@ import java.util.Map;
@RequestMapping("/iot/iotDeviceControl")
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");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
}
return "http://"+iotDevice.getListen_service_ip()+"device/control/"+imei;
}
private DeviceControlService deviceControlService;
@ApiOperation("固件版本更新")
@ApiImplicitParams({
... ... @@ -55,20 +33,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/firmwareUp/{imei}")
public String firmwareUp(HttpServletResponse response,@PathVariable String imei,String firmwareVersion,Integer code) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Map<String,Object> map = new HashMap<>();
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("firmwareVersion",firmwareVersion);
valueMap.put("code",code);
Response response1 = HttpUtils.postJsonBody(url, formBody -> {
formBody.put("0", valueMap);
});
return response1.body().string();
public Message firmwareUp(@PathVariable String imei,String firmwareVersion,Integer code) throws IOException {
return deviceControlService.firmwareUp(imei,firmwareVersion,code);
}
@ApiOperation("设备重启")
... ... @@ -80,18 +46,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/restart/{imei}/{restart}")
public String restart(HttpServletResponse response,@PathVariable String imei ,@PathVariable Integer restart) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("restart",restart);
Response response1 = HttpUtils.postJsonBody(url, formBody -> {
formBody.put("0",valueMap);
});
return response1.body().string();
public Message restart(@PathVariable String imei ,@PathVariable Integer restart) {
return deviceControlService.restart(imei,restart);
}
@ApiOperation("获取指定设备版本信息")
... ... @@ -100,20 +56,8 @@ public class IotDeviceControlController {
})
@ResponseBody
@PostMapping("/getFirmwareVersion/{imei}")
public String getFirmwareVersion(HttpServletResponse response,@PathVariable String imei) throws IOException {
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
response.setCharacterEncoding("UTF-8");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/getFirmwareVersion/"+iotDevice.getMqtt_username();
Response response1 = HttpUtils.postFromBody(url, builder -> {
}, formBody -> {
});
return response1.body().string();
public Message getFirmwareVersion(@PathVariable String imei) {
return deviceControlService.getFirmwareVersion(imei);
}
@ApiOperation("强行断开链接")
... ... @@ -122,20 +66,8 @@ public class IotDeviceControlController {
})
@ResponseBody
@PostMapping("/closeSession/{imei}")
public String closeSession(HttpServletResponse response,@PathVariable String imei) throws IOException {
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
response.setCharacterEncoding("UTF-8");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/closeSession/"+imei;
Response response1 = HttpUtils.postFromBody(url, builder -> {
}, formBody -> {
});
return response1.body().string();
public Message closeSession(@PathVariable String imei) {
return deviceControlService.closeSession(imei);
}
@ApiOperation("删除主机")
... ... @@ -145,28 +77,8 @@ public class IotDeviceControlController {
@Transactional
@ResponseBody
@PostMapping("/delIotDevice/{imei}")
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()))
{
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/delIotDevice/"+imei;
try {
String str = HttpUtils.getResponseString(HttpUtils.postFromBody(url, builder -> {
}, formBody -> {
}));
if(null != str)
{
return str;
}
} catch (IOException e) {
}
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
public Message delIotDevice(@PathVariable String imei) {
return deviceControlService.delIotDevice(imei);
}
... ... @@ -176,9 +88,8 @@ public class IotDeviceControlController {
})
@ResponseBody
@PostMapping("/delIotTerminal/{imei}/{number}")
public String delIotTerminal(HttpServletResponse response,@PathVariable String imei,@PathVariable String number) {
response.setCharacterEncoding("UTF-8");
return iIotTerminalService.deleteIotTerminalById(imei,number);
public Message delIotTerminal(@PathVariable String imei,@PathVariable String number) {
return deviceControlService.delIotTerminal(imei,number);
}
@ApiOperation(value = "读取属性")
... ... @@ -191,19 +102,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/readAttribute/{imei}/{sensor_number}")
public String readAttribute(HttpServletResponse response,@PathVariable String imei,@PathVariable String sensor_number,String attributes) throws IOException {
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
response.setCharacterEncoding("UTF-8");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/read/"+imei;
Map<String,Object> map = new HashMap<>();
map.put(sensor_number,attributes);
Response response1 = HttpUtils.postJsonBody(url, jsonObject -> jsonObject.putAll(map));
return response1.body().string();
public Message readAttribute(@PathVariable String imei,@PathVariable String sensor_number,String attributes) {
return deviceControlService.readAttribute(imei,sensor_number,attributes);
}
@ApiOperation(value = "设置主机自定义参数",notes = "自定义数据模型:\n" +
... ... @@ -222,18 +122,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/upSummary/{imei}")
public String upSummary(HttpServletResponse response,@PathVariable String imei,String summary) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("summary",JSONObject.parseObject(summary));
Response response1 = HttpUtils.postJsonBody(url,formBody -> {
formBody.put("0", valueMap);
});
return response1.body().string();
public Message upSummary(@PathVariable String imei,String summary) {
return deviceControlService.upSummary(imei,summary);
}
@ApiOperation(value = "修改指定终端属性",notes = "配置参数模型:\n" +
... ... @@ -251,16 +141,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/upTerminalConfig/{imei}/{number}")
public String upTerminalConfig(HttpServletResponse response, @PathVariable String imei,@PathVariable String number,@RequestBody Map<String,Object> config) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Map<String,Object> map = new HashMap<>();
map.put(number,config);
Response response1 = HttpUtils.postJsonBody(url, jsonObject -> jsonObject.putAll(map));
return response1.body().string();
public Message upTerminalConfig(@PathVariable String imei,@PathVariable String number,@RequestBody Map<String,Object> config) {
return deviceControlService.upTerminalConfig(imei,number,config);
}
@ApiOperation(value = "批量修改终端属性",notes = "批量数据模型:\n" +
... ... @@ -286,22 +168,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/batchUpTerminalConfig/{imei}")
public String batchUpTerminalConfig(HttpServletResponse response,@PathVariable String imei,@RequestBody Map<String,Object> map) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Response response1 = HttpUtils.postJsonBody(url, builder -> {
}, formBody -> {
for (String key:map.keySet())
{
formBody.put(key, map.get(key));
}
});
return response1.body().string();
public Message batchUpTerminalConfig(@PathVariable String imei,@RequestBody Map<String,Object> map) {
return deviceControlService.batchUpTerminalConfig(imei,map);
}
}
... ...
# 项目相关配置 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 rediskey: lh-admin # 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 rediskey: lh-admin # 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 # NameServer地址 rocketmq: name-server: 47.115.144.179:9876 # 默认的消息组 producer: group: deviceCommand send-message-timeout: 30000 send-topic: lh-mqtt-service-deviceCommand-test send-tags: 1
\ No newline at end of file
... ...
package com.zhonglai.luhui.api.controller.iot;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.Message;
import com.ruoyi.common.core.domain.MessageCode;
import com.ruoyi.common.enums.BusinessType;
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 com.ruoyi.system.service.DeviceControlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Api(tags = "设备控制")
... ... @@ -31,20 +21,8 @@ import java.util.Map;
@RequestMapping("/iot/iotDeviceControl")
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");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
}
return "http://"+iotDevice.getListen_service_ip()+"device/control/"+imei;
}
private DeviceControlService deviceControlService;
@ApiOperation("固件版本更新")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
... ... @@ -53,20 +31,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/firmwareUp/{imei}")
public String firmwareUp(HttpServletResponse response,@PathVariable String imei,String firmwareVersion,Integer code) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Map<String,Object> map = new HashMap<>();
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("firmwareVersion",firmwareVersion);
valueMap.put("code",code);
Response response1 = HttpUtils.postJsonBody(url, formBody -> {
formBody.put("0", valueMap);
});
return response1.body().string();
public Message firmwareUp(@PathVariable String imei,String firmwareVersion,Integer code) throws IOException {
return deviceControlService.firmwareUp(imei,firmwareVersion,code);
}
@ApiOperation("设备重启")
... ... @@ -77,18 +43,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/restart/{imei}/{restart}")
public String restart(HttpServletResponse response,@PathVariable String imei ,@PathVariable Integer restart) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("restart",restart);
Response response1 = HttpUtils.postJsonBody(url, formBody -> {
formBody.put("0",valueMap);
});
return response1.body().string();
public Message restart(@PathVariable String imei ,@PathVariable Integer restart) {
return deviceControlService.restart(imei,restart);
}
@ApiOperation("获取指定设备版本信息")
... ... @@ -97,20 +53,8 @@ public class IotDeviceControlController {
})
@ResponseBody
@PostMapping("/getFirmwareVersion/{imei}")
public String getFirmwareVersion(HttpServletResponse response,@PathVariable String imei) throws IOException {
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
response.setCharacterEncoding("UTF-8");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/getFirmwareVersion/"+iotDevice.getMqtt_username();
Response response1 = HttpUtils.postFromBody(url, builder -> {
}, formBody -> {
});
return response1.body().string();
public Message getFirmwareVersion(@PathVariable String imei) {
return deviceControlService.getFirmwareVersion(imei);
}
@ApiOperation("强行断开链接")
... ... @@ -119,20 +63,8 @@ public class IotDeviceControlController {
})
@ResponseBody
@PostMapping("/closeSession/{imei}")
public String closeSession(HttpServletResponse response,@PathVariable String imei) throws IOException {
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
response.setCharacterEncoding("UTF-8");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/closeSession/"+imei;
Response response1 = HttpUtils.postFromBody(url, builder -> {
}, formBody -> {
});
return response1.body().string();
public Message closeSession(@PathVariable String imei) {
return deviceControlService.closeSession(imei);
}
@ApiOperation("删除主机")
... ... @@ -142,29 +74,8 @@ public class IotDeviceControlController {
@Transactional
@ResponseBody
@PostMapping("/delIotDevice/{imei}")
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()))
{
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/delIotDevice/"+imei;
try {
String str = HttpUtils.getResponseString(HttpUtils.postFromBody(url, builder -> {
}, formBody -> {
}));
if(null != str)
{
return str;
}
} catch (IOException e) {
}
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
public Message delIotDevice(@PathVariable String imei) {
return deviceControlService.delIotDevice(imei);
}
@ApiOperation("删除终端")
... ... @@ -173,8 +84,8 @@ public class IotDeviceControlController {
})
@ResponseBody
@PostMapping("/delIotTerminal/{imei}/{number}")
public String delIotTerminal(@PathVariable String imei,@PathVariable String number) {
return iIotTerminalService.deleteIotTerminalById(imei,number);
public Message delIotTerminal(@PathVariable String imei,@PathVariable String number) {
return deviceControlService.delIotTerminal(imei,number);
}
@ApiOperation(value = "读取属性")
... ... @@ -186,19 +97,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/readAttribute/{imei}/{sensor_number}")
public String readAttribute(HttpServletResponse response,@PathVariable String imei,@PathVariable String sensor_number,String attributes) throws IOException {
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
response.setCharacterEncoding("UTF-8");
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
response.getWriter().print(new Message(MessageCode.DEFAULT_FAIL_CODE,"未找到设备监听服务地址"));
return null;
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/read/"+imei;
Map<String,Object> map = new HashMap<>();
map.put(sensor_number,attributes);
Response response1 = HttpUtils.postJsonBody(url, jsonObject -> jsonObject.putAll(map));
return response1.body().string();
public Message readAttribute(@PathVariable String imei,@PathVariable String sensor_number,String attributes) {
return deviceControlService.readAttribute(imei,sensor_number,attributes);
}
@ApiOperation(value = "设置主机自定义参数",notes = "自定义数据模型:\n" +
... ... @@ -216,18 +116,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/upSummary/{imei}")
public String upSummary(HttpServletResponse response,@PathVariable String imei,String summary) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("summary",JSONObject.parseObject(summary));
Response response1 = HttpUtils.postJsonBody(url,formBody -> {
formBody.put("0", valueMap);
});
return response1.body().string();
public Message upSummary(@PathVariable String imei,String summary) {
return deviceControlService.upSummary(imei,summary);
}
@ApiOperation(value = "修改指定终端属性",notes = "配置参数模型:\n" +
... ... @@ -244,16 +134,8 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/upTerminalConfig/{imei}/{number}")
public String upTerminalConfig(HttpServletResponse response, @PathVariable String imei,@PathVariable String number,@RequestBody Map<String,Object> config) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Map<String,Object> map = new HashMap<>();
map.put(number,config);
Response response1 = HttpUtils.postJsonBody(url, jsonObject -> jsonObject.putAll(map));
return response1.body().string();
public Message upTerminalConfig( @PathVariable String imei,@PathVariable String number,@RequestBody Map<String,Object> config) {
return deviceControlService.upTerminalConfig(imei,number,config);
}
@ApiOperation(value = "批量修改终端属性",notes = "批量数据模型:\n" +
... ... @@ -278,23 +160,7 @@ public class IotDeviceControlController {
@Log(title = "设备控制", businessType = BusinessType.UPDATE)
@ResponseBody
@PostMapping("/batchUpTerminalConfig/{imei}")
public String batchUpTerminalConfig(HttpServletResponse response,@PathVariable String imei,@RequestBody Map<String,Object> map) throws IOException {
String url = getServiceAdrres(response,imei);
if(null == url)
{
return null;
}
Response response1 = HttpUtils.postJsonBody(url, builder -> {
}, formBody -> {
for (String key:map.keySet())
{
formBody.put(key, map.get(key));
}
});
return response1.body().string();
public Message batchUpTerminalConfig(@PathVariable String imei,@RequestBody Map<String,Object> map) {
return deviceControlService.batchUpTerminalConfig(imei,map);
}
}
... ...
<?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-backups</artifactId>
<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>
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>ruoyi-framework</artifactId>
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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-backups</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.backups.LhBackupsApplication</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
... ...
package com.zhonglai.luhui.backups;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = {
"com.ruoyi.common",
"com.ruoyi.system",
"com.zhonglai.luhui.backups.config",
"com.zhonglai.luhui.backups.controller",
})
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class LhBackupsApplication {
public static void main(String[] args) {
SpringApplication.run(LhBackupsApplication.class,args);
System.out.println("启动成功");
}
}
... ...
package com.zhonglai.luhui.backups.config;
import com.ruoyi.common.config.RuoYiConfig;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/** 系统基础配置 */
@Autowired
private RuoYiConfig ruoyiConfig;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
/**
* 添加摘要信息
*/
private ApiInfo apiInfo()
{
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("标题:后台管理员端")
// 描述
.description("描述:用于通过mqtt发送指令控制PC端操作")
// 作者信息
.contact(new Contact(ruoyiConfig.getName(), null, null))
// 版本
.version("版本号:" + ruoyiConfig.getVersion())
.build();
}
}
\ No newline at end of file
... ...
package com.zhonglai.luhui.backups.task;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.PublicService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class BackupsDb {
@Autowired
private PublicService publicService;
private static String savePath = "F:/webdav/db";
/**
* 归档
*/
@Scheduled(fixedRate=1000)
private void file() {
Long ct = publicService.selectCountBySql("SELECT COUNT(*) FROM information_schema.TABLES WHERE table_schema = 'ly-device-data'");
if(null != ct)
{
int pageSize = 10;
Long pageNo = ct/pageSize;
if(ct%pageSize>0)
{
pageNo +=1;
}
for(int i=0;i<pageNo;i++)
{
StringBuffer tablesql = new StringBuffer("SELECT TABLE_NAME FROM information_schema.TABLES WHERE table_schema = 'ly-device-data' LIMIT ");
tablesql.append(pageNo);
tablesql.append(",");
tablesql.append(pageSize);
List<Map<String,Object>> tableList = publicService.getObjectListBySQL(""+pageNo+","+pageSize);
if(null != tableList && tableList.size() !=0)
{
for(Map<String,Object> map:tableList)
{
String table_name = (String) map.get("TABLE_NAME");
String path = table_name.split("-")[0];
File pathFile = new File(savePath+"/"+path);
if(!pathFile.exists())
{
pathFile.mkdirs();
}
List<Map<String,Object>> dataList = publicService.getObjectListBySQL("SELECT * FROM `"+table_name+"`");
if(null != dataList && dataList.size() != 0)
{
File saveFile = new File(pathFile.getAbsolutePath()+"/"+table_name+".csv");
try {
FileWriter fileWriter = new FileWriter(saveFile);
for(Map<String,Object> data:dataList)
{
fileWriter.write(mapToString(data));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
private String mapToString(Map<String,Object> data)
{
if(null == data)
{
return null;
}
StringBuffer stringBuffer = new StringBuffer();
for(String key:data.keySet())
{
if(stringBuffer.length()!=0)
{
stringBuffer.append(",");
}
stringBuffer.append(data.get(key));
}
return stringBuffer.toString();
}
/**
* 转移
*/
@Scheduled(fixedRate=1000)
private void transfer() {
}
}
... ...
# 数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 主库数据源
master:
url: jdbc:mysql://rm-wz9740un21f09iokuao.mysql.rds.aliyuncs.com:3306/mqtt_broker?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: luhui
password: Luhui586
# 从库数据源
slave:
# 从数据源开关/默认关闭
enabled: false
url:
username:
password:
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 设置白名单,不填则允许所有访问
allow:
url-pattern: /druid/*
# 控制台管理用户名和密码
login-username: ruoyi
login-password: 123456
filter:
stat:
enabled: true
# 慢SQL记录
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
\ 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: 18080 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 rediskey: lh-api # 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/ApiLogin/*
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<assembly>
<id>bin</id>
<!-- 最终打包成一个用于发布的zip文件 -->
<formats>
<format>zip</format>
</formats>
<!-- Adds dependencies to zip package under lib directory -->
<dependencySets>
<dependencySet>
<!--
不使用项目的artifact,第三方jar不要解压,打包进zip文件的lib目录
-->
<useProjectArtifact>false</useProjectArtifact>
<outputDirectory>lib</outputDirectory>
<unpack>false</unpack>
</dependencySet>
</dependencySets>
<fileSets>
<!-- 把项目相关的说明文件,打包进zip文件的根目录 -->
<fileSet>
<directory>${project.basedir}</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>README*</include>
<include>LICENSE*</include>
<include>NOTICE*</include>
</includes>
</fileSet>
<!-- 把项目的配置文件,打包进zip文件的config目录 -->
<fileSet>
<directory>${project.basedir}\src\main\resources\configs</directory>
<outputDirectory>../configs</outputDirectory>
<includes>
<include>*.properties</include>
</includes>
</fileSet>
<!-- 把项目的配置文件,提出来 -->
<fileSet>
<directory>${project.basedir}\src\main\resources</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>*.properties</include>
<include>*.yml</include>
</includes>
</fileSet>
<!-- 把项目的脚本文件目录( src/main/scripts )中的启动脚本文件,打包进zip文件的跟目录 -->
<fileSet>
<directory>${project.basedir}\bin</directory>
<outputDirectory></outputDirectory>
<includes>
<include>start.*</include>
<include>stop.*</include>
</includes>
</fileSet>
<!-- 把项目自己编译出来的jar文件,打包进zip文件的根目录 -->
<fileSet>
<directory>${project.build.directory}</directory>
<outputDirectory></outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
... ...
... ... @@ -19,7 +19,7 @@ import org.springframework.stereotype.Service;
@Service
@RocketMQMessageListener(consumerGroup = "deviceCommand", topic = "${rocketmq.send-topic:}",selectorType = SelectorType.TAG,selectorExpression = "${rocketmq.send-tag:}")
public class RocketMqService implements RocketMQReplyListener<MessageExt, Message> {
private static final Logger log = LoggerFactory.getLogger(MqttCallback.class);
private static final Logger log = LoggerFactory.getLogger(RocketMqService.class);
@Autowired
private DeviceService deviceService ;
... ...
... ... @@ -58,7 +58,7 @@ public class BusinessDataUpdateService {
* @param type
* @param topic
*/
public void updataDta(Type type, Topic topic, boolean isOperLog, ServerDto serverDto)
public void updataDta(Type type, Topic topic, ServerDto serverDto)
{
IotDevice olddevice = cacheService.getIotDevice(topic.getClientid());
... ... @@ -81,7 +81,7 @@ public class BusinessDataUpdateService {
JSONObject jsData = data.getJSONObject(key);
if("0".equals(key)) //主机
{
IotDevice iotDevice = translateDevice(type,olddevice,jsData,isOperLog,serverDto);
IotDevice iotDevice = translateDevice(type,olddevice,jsData,serverDto);
if(isText)
{
iotDevice.setListen_service_ip("127.0.0.1"+":"+port+contextPath);
... ... @@ -97,7 +97,7 @@ public class BusinessDataUpdateService {
iotDevice.setName(olddevice.getName());
serverDto.setIotDevice(iotDevice);
}else{ //终端
IotTerminal iotTerminal = translateTerminal(type,key,olddevice,jsData,isOperLog,serverDto);
IotTerminal iotTerminal = translateTerminal(type,key,olddevice,jsData,serverDto);
iotTerminal.setData_update_time(DateUtils.getNowTimeMilly());
if(null== iotTerminal.getOnline() || 1 == iotTerminal.getOnline() || 4==iotTerminal.getOnline())
{
... ... @@ -117,7 +117,7 @@ public class BusinessDataUpdateService {
* @param serverDto
* @return
*/
private IotDevice translateDevice(Type type, IotDevice olddevice , JSONObject jsData,boolean isOperLog, ServerDto serverDto)
private IotDevice translateDevice(Type type, IotDevice olddevice , JSONObject jsData, ServerDto serverDto)
{
JSONObject summaryObjec = null;
if(jsData.containsKey("summary") && null != jsData.get("summary") && jsData.get("summary") instanceof JSONObject)
... ... @@ -134,19 +134,19 @@ public class BusinessDataUpdateService {
device.setSummary(summaryObjec.toString());
}
SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( olddevice.getClient_id(),olddevice.getMqtt_username(),jsData,"主机本地",isOperLog,serverDto);
SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( olddevice.getClient_id(),olddevice.getMqtt_username(),jsData,serverDto);
//更新数据
if(null != olddevice && ("ADD".equals(type.name())|| "READ".equals(type.name())))
{
String str = olddevice.getThings_model_value();
String newStr = deviceService.getNewAdddate(str,saveDataDto.getData()).toJSONString();
String newStr = deviceService.getNewAdddate(device.getClient_id(),str,saveDataDto.getData(),serverDto.getLogDeviceOperationList()).toJSONString();
device.setThings_model_value(newStr);
}else{
device.setThings_model_value(saveDataDto.getData().toJSONString());
}
//配置只做增量
String str = (null!=olddevice?olddevice.getThings_model_config():null);
String newStr = deviceService.getNewAdddate(str,saveDataDto.getConfig()).toJSONString();
String newStr = deviceService.getNewAdddate(device.getClient_id(),str,saveDataDto.getConfig(),serverDto.getLogDeviceOperationList()).toJSONString();
device.setThings_model_config(newStr);
return device;
... ... @@ -161,10 +161,10 @@ public class BusinessDataUpdateService {
* @param serverDto
* @return
*/
private IotTerminal translateTerminal(Type type,String key, IotDevice olddevice , JSONObject jsData,boolean isOperLog,ServerDto serverDto)
private IotTerminal translateTerminal(Type type,String key, IotDevice olddevice , JSONObject jsData,ServerDto serverDto)
{
String id = olddevice.getClient_id()+"_"+key;
SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( id,olddevice.getMqtt_username(),jsData,"终端本地",isOperLog,serverDto);
SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( id,olddevice.getMqtt_username(),jsData,serverDto);
IotTerminal terminal = new IotTerminal();
terminal.setId(id);
terminal.setDevice_id(olddevice.getClient_id());
... ... @@ -172,10 +172,12 @@ public class BusinessDataUpdateService {
terminal.setMqtt_username(olddevice.getMqtt_username());
//更新数据
IotTerminal oldterminal = cacheService.getIotTerminal(id);
//记录操作日志
if(null != oldterminal && ("ADD".equals(type.name())|| "READ".equals(type.name())))
{
String str = oldterminal.getThings_model_value();
terminal.setThings_model_value(deviceService.getNewAdddate(str,saveDataDto.getData()).toJSONString());
terminal.setThings_model_value(deviceService.getNewAdddate(id,str,saveDataDto.getData(),serverDto.getLogDeviceOperationList()).toJSONString());
}else{
terminal.setThings_model_value(saveDataDto.getData().toJSONString());
}
... ... @@ -184,7 +186,7 @@ public class BusinessDataUpdateService {
System.out.println(saveDataDto);
}
String str = (null!=oldterminal?oldterminal.getThings_model_config():null);
terminal.setThings_model_config(deviceService.getNewAdddate(str,saveDataDto.getConfig()).toJSONString());
terminal.setThings_model_config(deviceService.getNewAdddate(id,str,saveDataDto.getConfig(),serverDto.getLogDeviceOperationList()).toJSONString());
terminal.setName(oldterminal.getName());
return terminal;
}
... ...
... ... @@ -33,9 +33,6 @@ public class DataModeAnalysisService {
private BaseDao baseDao = new BaseDao();
@Autowired
private DeviceLogService dviceLogService;
@Autowired
private TerminalDataThingsModeService terminalDataThingsModeService;
/**
... ... @@ -64,7 +61,7 @@ public class DataModeAnalysisService {
/**
* 解析物模型数据
*/
public SaveDataDto analysisThingsModelValue(String id,String userName ,JSONObject jsData,String controlModel,boolean isOperLog, ServerDto serverDto)
public SaveDataDto analysisThingsModelValue(String id,String userName ,JSONObject jsData, ServerDto serverDto)
{
if(null != jsData && jsData.size() != 0 )
{
... ... @@ -113,12 +110,6 @@ public class DataModeAnalysisService {
serverDto.getDeviceSensorDataList().add(sensorData);
}
//记录操作日志
if(isOperLog && null != serverDto.getLogDeviceOperationList())
{
serverDto.getLogDeviceOperationList().add(dviceLogService.newLogDeviceOperation(id,thingsModelBase.getSaveView(),null,controlModel+thingsModelItemBase.getName()+"为"+thingsModelBase.getView(),jsData.toString()));
}
switch (thingsModel.getIs_config())
{
case 0:
... ...
... ... @@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.IotDevice;
import com.ruoyi.system.domain.IotTerminal;
import com.ruoyi.system.domain.IotThingsModel;
import com.zhonglai.luhui.mqtt.comm.dao.BaseDao;
import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelBase;
... ... @@ -89,4 +90,17 @@ public class DeviceController {
return new Message(MessageCode.DEFAULT_SUCCESS_CODE,map);
}
@ApiOperation("更新主机")
@RequestMapping(value = "updateIotDevice",method = RequestMethod.POST)
public Message updateIotDevice(@RequestBody IotDevice iotDevice) {
return deviceService.updateIotDevice(iotDevice);
}
@ApiOperation("更新终端")
@RequestMapping(value = "updateIotTerminal",method = RequestMethod.POST)
public Message updateIotTerminal(@RequestBody IotTerminal iotTerminal) {
return deviceService.updateIotTerminal(iotTerminal);
}
}
... ...
... ... @@ -8,4 +8,11 @@ public enum ApiName {
delIotTerminal,
control,
getFirmwareVersion,
updateIotDevice,
updateIotTerminal,
delDeviceHost,
delDeviceInfoFromDeviceId,
delDeviceInfo,
transferPond,
updateDeviceInfo
}
... ...
package com.zhonglai.luhui.mqtt.dto;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.IotDevice;
import com.ruoyi.system.domain.IotTerminal;
import com.zhonglai.luhui.mqtt.service.db.DeviceService;
import org.eclipse.paho.client.mqttv3.MqttException;
... ... @@ -26,7 +29,27 @@ public class DeviceCommandApi {
case delIotTerminal:
return deviceService.delIotTerminal(deviceCommandApiParameter.getClient_id(),deviceCommandApiParameter.getNumber());
case getFirmwareVersion:
deviceCommandApiParameter.setClient_id(deviceCommandApiParameter.getData());
return deviceService.getFirmwareVersion(deviceCommandApiParameter.getData());
case updateIotDevice:
IotDevice iotDevice = JSONObject.parseObject(JSONObject.toJSONString(deviceCommandApiParameter.getMap()), IotDevice.class);
deviceCommandApiParameter.setClient_id(iotDevice.getClient_id());
return deviceService.updateIotDevice(iotDevice);
case updateIotTerminal:
IotTerminal iotTerminal = JSONObject.parseObject(JSONObject.toJSONString(deviceCommandApiParameter.getMap()), IotTerminal.class);
deviceCommandApiParameter.setClient_id(iotTerminal.getId());
return deviceService.updateIotTerminal(iotTerminal);
case delDeviceHost:
return deviceService.delDeviceHost(deviceCommandApiParameter.getClient_id());
case delDeviceInfo:
deviceCommandApiParameter.setClient_id(deviceCommandApiParameter.getData());
return deviceService.delDeviceInfo(deviceCommandApiParameter.getData());
case delDeviceInfoFromDeviceId:
return deviceService.delDeviceInfoFromDeviceId(deviceCommandApiParameter.getClient_id());
case transferPond:
return deviceService.transferPond(deviceCommandApiParameter.getClient_id(),deviceCommandApiParameter.getMap());
case updateDeviceInfo:
return deviceService.updateDeviceInfo(deviceCommandApiParameter.getClient_id(),deviceCommandApiParameter.getMap());
default:
return new Message(MessageCode.DEFAULT_FAIL_CODE,"接口不存在");
}
... ...
... ... @@ -140,11 +140,25 @@ public class CacheServiceImpl implements CacheService {
return null;
}
public boolean hasIotDeviceToRedis(String iotDeviceId)
{
return redisService.hasKey(getRedicDeviceKey(iotDeviceId));
}
/**
* 设置缓存终端
*/
public boolean hasIotTerminalToRedis(String iotTerminalId)
{
return redisService.hasKey(getRedicTerminalKey(iotTerminalId));
}
/**
* 设置缓存主机
* @param iotDevice
*/
private void setIotDeviceToRedis(IotDevice iotDevice)
public void setIotDeviceToRedis(IotDevice iotDevice)
{
redisService.hmset(getRedicDeviceKey(iotDevice.getClient_id()),iotDevice);
}
... ... @@ -153,7 +167,7 @@ public class CacheServiceImpl implements CacheService {
* 设置缓存终端
* @param iotTerminal
*/
private void setIotTerminalToRedis(IotTerminal iotTerminal)
public void setIotTerminalToRedis(IotTerminal iotTerminal)
{
redisService.hmset(getRedicTerminalKey(iotTerminal.getId()),iotTerminal);
}
... ...
... ... @@ -8,10 +8,14 @@ import com.ruoyi.system.domain.IotTerminal;
import com.ruoyi.system.domain.IotThingsModel;
import com.zhonglai.luhui.mqtt.comm.config.RedisConfig;
import com.zhonglai.luhui.mqtt.comm.dao.BaseDao;
import com.zhonglai.luhui.mqtt.comm.dto.DeviceInfoDto;
import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;
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.Topic;
import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService;
import com.zhonglai.luhui.mqtt.comm.service.DeviceLogService;
import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService;
import com.zhonglai.luhui.mqtt.comm.util.DateUtils;
import com.zhonglai.luhui.mqtt.dto.Message;
... ... @@ -26,10 +30,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
@Service
public class DeviceService {
... ... @@ -44,6 +45,12 @@ public class DeviceService {
@Autowired
private CacheServiceImpl cacheServiceImpl;
@Autowired
private RedisService redisService ;
@Autowired
private DeviceLogService dviceLogService;
private BaseDao baseDao = new BaseDao();
/**
... ... @@ -83,15 +90,24 @@ public class DeviceService {
* @param saveJson
* @return
*/
public JSONObject getNewAdddate(String oldstr, JSONObject saveJson)
public JSONObject getNewAdddate(String id,String oldstr, JSONObject saveJson, List<LogDeviceOperation> logDeviceOperationList)
{
JSONObject oldjs = new JSONObject();
if(StringUtils.isNoneBlank(oldstr))
{
oldjs = JSONObject.parseObject(oldstr);
}
for (String sk:saveJson.keySet())
{
ThingsModelItemBase thingsModelItemBase = (ThingsModelItemBase) saveJson.get(sk);
if(null != thingsModelItemBase.getIs_save_log() && 1==thingsModelItemBase.getIs_save_log() && null != logDeviceOperationList)
{
if(null!=thingsModelItemBase.getSaveView() && null != oldjs && oldjs.containsKey(sk) && !thingsModelItemBase.getSaveView().equals(oldjs.getJSONObject(sk).getString("saveView")))
{
logDeviceOperationList.add(dviceLogService.newLogDeviceOperation(id,thingsModelItemBase.getSaveView(),oldjs.getJSONObject(sk).getString("saveView"),"本地操作"+thingsModelItemBase.getName()+"为"+thingsModelItemBase.getView(),null));
}
}
oldjs.put(sk,saveJson.get(sk));
}
return oldjs;
... ... @@ -143,6 +159,12 @@ public class DeviceService {
mqttMessage.setPayload(bs);
Message message = clienNoticeService.sendMessage(topic,mqttMessage);
if(1==message.getCode())
{
List<LogDeviceOperation> list = new ArrayList<>();
list.add(dviceLogService.newLogDeviceOperation(clienid,null!=message.getData()?JSON.toJSONString(message.getData()):null,null,"远程操作控制设备","controlHex?"+data));
dviceLogService.saveOperationLog(list);
}
return message;
}
... ... @@ -171,10 +193,54 @@ public class DeviceService {
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());
Message message = clienNoticeService.sendMessage(topic,mqttMessage);
if(1==message.getCode())
{
List<LogDeviceOperation> list = new ArrayList<>();
list.add(dviceLogService.newLogDeviceOperation(clienid,JSON.toJSONString(message.getData()),null,"远程操作读取配置参数","read?"+JSON.toJSONString(map).trim()));
dviceLogService.saveOperationLog(list);
}
return message;
}
/**
* 更新主机
* @return
* @throws MqttException
* @throws InterruptedException
*/
public Message updateIotDevice(IotDevice iotDevice) {
if(cacheServiceImpl.hasIotDeviceToRedis(iotDevice.getClient_id()))
{
cacheServiceImpl.setIotDeviceToRedis(iotDevice);
}
baseDao.update(iotDevice,"client_id");
List<LogDeviceOperation> list = new ArrayList<>();
list.add(dviceLogService.newLogDeviceOperation(iotDevice.getClient_id(),null,null,"远程操作更新主机","updateIotDevice?"+JSON.toJSONString(iotDevice)));
dviceLogService.saveOperationLog(list);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
/**
* 更新终端
* @return
* @throws MqttException
* @throws InterruptedException
*/
public Message updateIotTerminal(IotTerminal iotTerminal) {
if(cacheServiceImpl.hasIotTerminalToRedis(iotTerminal.getId()))
{
cacheServiceImpl.setIotTerminalToRedis(iotTerminal);
}
baseDao.update(iotTerminal,"id");
List<LogDeviceOperation> list = new ArrayList<>();
list.add(dviceLogService.newLogDeviceOperation(iotTerminal.getId(),null,null,"远程操作更新终端","updateIotTerminal?"+JSON.toJSONString(iotTerminal)));
dviceLogService.saveOperationLog(list);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
/**
* 强行断开链接
* @param clienid
* @return
... ... @@ -188,6 +254,9 @@ public class DeviceService {
mqttMessage.setPayload(bs);
clienNoticeService.sendMessage("CLOSE",mqttMessage);
List<LogDeviceOperation> list = new ArrayList<>();
list.add(dviceLogService.newLogDeviceOperation(clienid,null,null,"远程操作强行断开链接","closeSession?"));
dviceLogService.saveOperationLog(list);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE,"端口请求已发送");
}
... ... @@ -201,6 +270,11 @@ public class DeviceService {
public Message delIotDevice(String client_id) throws MqttException, InterruptedException {
closeSession(client_id); //强制下线
cacheServiceImpl.deletRedisDevice(client_id);
baseDao.updateBySql("delete from iot_device where client_id='"+client_id+"'");
baseDao.updateBySql("delete from iot_terminal where device_id='"+client_id+"'");
List<LogDeviceOperation> list = new ArrayList<>();
list.add(dviceLogService.newLogDeviceOperation(client_id,null,null,"远程操作删除主机","delIotDevice?"));
dviceLogService.saveOperationLog(list);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
... ... @@ -215,6 +289,10 @@ public class DeviceService {
public Message delIotTerminal(String client_id,String number) throws MqttException, InterruptedException {
closeSession(client_id); //强制下线
cacheServiceImpl.deletRedisTerminal(client_id+"_"+number);
baseDao.updateBySql("delete from iot_terminal where id='"+client_id+"_"+number+"'");
List<LogDeviceOperation> list = new ArrayList<>();
list.add(dviceLogService.newLogDeviceOperation(client_id,null,null,"远程操作删除终端","delIotTerminal?"));
dviceLogService.saveOperationLog(list);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
... ... @@ -274,6 +352,12 @@ public class DeviceService {
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());
Message message = clienNoticeService.sendMessage(topic,mqttMessage);
if(1==message.getCode())
{
List<LogDeviceOperation> list = new ArrayList<>();
list.add(dviceLogService.newLogDeviceOperation(clienid,JSON.toJSONString(message.getData()),null,"远程操作控制","control?"+JSON.toJSONString(map).trim()));
dviceLogService.saveOperationLog(list);
}
return message;
}
... ... @@ -305,6 +389,85 @@ public class DeviceService {
topic.setMessageid(DateUtils.getNowTimeMilly()+"");
return topic;
}
private static String x6deviceKeyPath = "ly:x6:devices:";
private static String x6hostKeyPath = "ly:x6:hosts:";
public Message delDeviceHost(String deviceId)
{
String key =x6hostKeyPath+deviceId;
if(redisService.hasKey(key))
{
redisService.del(key);
}
List<LogDeviceOperation> oplist = new ArrayList<>();
oplist.add(dviceLogService.newLogDeviceOperation(deviceId,null,null,"远程操作删除x6主机","delDeviceHost?"));
dviceLogService.saveOperationLog(oplist);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
public Message delDeviceInfoFromDeviceId(String deviceId)
{
String key =x6deviceKeyPath+deviceId;
redisService.del(key);
Set<String> keys = redisService.keys(x6deviceKeyPath+deviceId+"*");
redisService.del(keys.toArray(new String[keys.size()]));
List<LogDeviceOperation> oplist = new ArrayList<>();
oplist.add(dviceLogService.newLogDeviceOperation(deviceId,null,null,"远程操作删除x6终端","delDeviceInfoFromDeviceId?"));
dviceLogService.saveOperationLog(oplist);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
public Message delDeviceInfo(String deviceInfoId)
{
String key =x6deviceKeyPath+deviceInfoId;
if(redisService.hasKey(key))
{
redisService.del(key);
}
List<LogDeviceOperation> oplist = new ArrayList<>();
oplist.add(dviceLogService.newLogDeviceOperation(deviceInfoId,null,null,"远程操作删除x6终端","delDeviceInfo?"));
dviceLogService.saveOperationLog(oplist);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
/**
* 移塘
* @return
*/
public Message transferPond(String deviceInfoId,Map<String,Object> map)
{
String key =x6deviceKeyPath+deviceInfoId;
if(redisService.hasKey(key))
{
redisService.hmset(key,map);
}
List<LogDeviceOperation> oplist = new ArrayList<>();
oplist.add(dviceLogService.newLogDeviceOperation(deviceInfoId,null,null,"远程操作移塘","updateDeviceInfo?"));
dviceLogService.saveOperationLog(oplist);
return updateDeviceInfo(deviceInfoId,map);
}
/**
* 修改设备信息
* @return
*/
public Message updateDeviceInfo(String deviceInfoId,Map<String,Object> map)
{
String key =x6deviceKeyPath+deviceInfoId;
if(redisService.hasKey(key))
{
redisService.hmset(key,map);
}
List<LogDeviceOperation> oplist = new ArrayList<>();
oplist.add(dviceLogService.newLogDeviceOperation(deviceInfoId,null,null,"远程操作修改终端信息","updateDeviceInfo?"));
dviceLogService.saveOperationLog(oplist);
return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
}
/**
* 把16进制字符串转换成字节数组
*
... ...
... ... @@ -22,7 +22,7 @@ public class AddPostTopic implements BusinessAgreement<AddPostDto> {
private BusinessDataUpdateService businessDataUpdateService ;
@Override
public ServerDto analysis(Topic topic, AddPostDto data) {
businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ADD,topic,true,data);
businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ADD,topic,data);
return data;
}
... ...
... ... @@ -23,7 +23,7 @@ public class AllPostTopic implements BusinessAgreement<AllPostDto> {
private BusinessDataUpdateService businessDataUpdateService ;
@Override
public ServerDto analysis(Topic topic, AllPostDto data) throws Exception {
businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ALL,topic,false,data);
businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ALL,topic,data);
return data;
}
... ...
package com.zhonglai.luhui.mqtt.service.topic;
import com.ruoyi.system.domain.IotDevice;
import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
import com.zhonglai.luhui.mqtt.comm.dto.business.BusinessDto;
import com.zhonglai.luhui.mqtt.comm.factory.BusinessAgreement;
import com.zhonglai.luhui.mqtt.comm.factory.Topic;
import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService;
import com.zhonglai.luhui.mqtt.dto.topic.OnlineDto;
import com.zhonglai.luhui.mqtt.service.CacheServiceImpl;
import com.zhonglai.luhui.mqtt.service.db.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
... ... @@ -14,11 +17,16 @@ import org.springframework.stereotype.Service;
public class OnlineTopic implements BusinessAgreement<OnlineDto> {
@Autowired
private DeviceService deviceService ;
@Autowired
private CacheServiceImpl cacheServiceImpl;
@Override
public ServerDto analysis(Topic topic, OnlineDto data) throws Exception {
if(1==data.getState()) //在线
{
IotDevice iotDevice = deviceService.getDeviceById(topic.getClientid());
cacheServiceImpl.setIotDeviceToRedis(iotDevice);
}else{ //离线
deviceService.deviceOffLine(topic.getClientid());
}
... ...
... ... @@ -17,6 +17,7 @@
<module>lh-domain</module>
<module>lh-api</module>
<module>lh-central-control</module>
<module>lh-backups</module>
</modules>
<packaging>pom</packaging>
... ... @@ -48,6 +49,7 @@
<zxing.version>3.4.0</zxing.version>
<okhttp.version>3.3.1</okhttp.version>
<tkmapper.version>4.2.1</tkmapper.version>
<shiro.version>1.10.1</shiro.version>
</properties>
<!-- 依赖声明 -->
... ... @@ -336,6 +338,7 @@
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
... ...
... ... @@ -25,4 +25,19 @@ public enum MessageCode implements MessageCodeType{
this.code = code;
this.message = message;
}
public static MessageCode getMessageCode(int code)
{
MessageCode[] messageCodes = MessageCode.values();
for(MessageCode messageCode:messageCodes)
{
if(messageCode.code==code)
{
return messageCode;
}
}
return DEFAULT_FAIL_CODE;
}
}
... ...
package com.ruoyi.common.core.redis;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
... ... @@ -240,4 +241,19 @@ public class RedisCache
{
return redisTemplate.keys(pattern);
}
/**
*
* @param key
* @return 判断key是否存在
*/
public boolean hasKey(String key){
return redisTemplate.hasKey(key);
}
public void hmset(String key,Object object){
String s = JSONObject.toJSONString(object);
Map<String, String> map = JSONObject.parseObject(s,HashMap.class);
setCacheMap(key, map);
}
}
... ...
... ... @@ -72,6 +72,11 @@
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
... ...
package com.ruoyi.system.dto;
public enum ApiName {
controlHex,
read,
closeSession,
delIotDevice,
delIotTerminal,
control,
getFirmwareVersion,
updateIotDevice,
updateIotTerminal
}
... ...
package com.ruoyi.system.dto;
/**
* 设备指令接口
*/
public class DeviceCommandApi {
private ApiName apiName; //指令接口名称
private DeviceCommandApiParameter deviceCommandApiParameter; //参数
public static DeviceCommandApi getDeviceCommandApi()
{
return new DeviceCommandApi();
}
public DeviceCommandApi bindApiName(ApiName apiName)
{
setApiName(apiName);
return this;
}
public DeviceCommandApi bindDeviceCommandApiParameter(DeviceCommandApiParameter deviceCommandApiParameter)
{
setDeviceCommandApiParameter(deviceCommandApiParameter);
return this;
}
public ApiName getApiName() {
return apiName;
}
public void setApiName(ApiName apiName) {
this.apiName = apiName;
}
public DeviceCommandApiParameter getDeviceCommandApiParameter() {
return deviceCommandApiParameter;
}
public void setDeviceCommandApiParameter(DeviceCommandApiParameter deviceCommandApiParameter) {
this.deviceCommandApiParameter = deviceCommandApiParameter;
}
}
... ...
package com.ruoyi.system.dto;
import java.util.Map;
public class DeviceCommandApiParameter {
private String client_id;
private Map<String,Object> map;
private String data;
private String number;
public static DeviceCommandApiParameter getDeviceCommandApiParameter()
{
return new DeviceCommandApiParameter();
}
public DeviceCommandApiParameter bindClient_id(String client_id)
{
setClient_id(client_id);
return this;
}
public DeviceCommandApiParameter bindMap(Map<String,Object> map)
{
setMap(map);
return this;
}
public DeviceCommandApiParameter bindData(String data)
{
setData(data);
return this;
}
public DeviceCommandApiParameter bindNumber(String number)
{
setNumber(number);
return this;
}
public String getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
public Map<String,Object> getMap() {
return map;
}
public void setMap(Map<String,Object> map) {
this.map = map;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
... ...
... ... @@ -757,6 +757,19 @@ public class PublicSQL {
return sql;
}
public String selectCountBySql(String sql)
{
if(!sql.toUpperCase().startsWith("SELECT COUNT("))
{
try {
throw new Exception("不是count查询");
} catch (Exception e) {
e.printStackTrace();
}
}
return sql;
}
public static String escapeSql(String str) {
return str == null ? null : StringUtils.replace(str, "'", "''");
}
... ...
... ... @@ -63,7 +63,7 @@ public class LoginService {
// }
// 用户验证
Authentication authentication = userPasswordVerification(username,password,SysLogininforType.lhAdmin);
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,SysLogininforType.lhAdmin, Constants.LOGIN_SUCCESS, MessageUtils.message("sysuser.login.success")));
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,SysLogininforType.lhAdmin, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
SysLoginUser loginUser = (SysLoginUser) authentication.getPrincipal();
loginUser.setSysLogininforType(SysLogininforType.lhAdmin);
recordLoginInfo(loginUser.getUserId());
... ...
... ... @@ -64,6 +64,8 @@ public interface PublicMapper {
@SelectProvider(type = PublicSQL.class, method = "getObject")
<T> T getObject(@Param("class") Class<?> clas, @Param("idName") String idName, @Param("values") String values);
@SelectProvider(type = PublicSQL.class, method = "selectCountBySql")
Long selectCountBySql(@Param("sql") String sql);
/**
* 查询 通过条件查询
* @param clas
... ...
package com.ruoyi.system.rocketmq;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.Message;
import com.ruoyi.common.core.domain.MessageCode;
import com.ruoyi.common.core.domain.MessageCodeType;
import com.ruoyi.system.dto.DeviceCommandApi;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.exception.RequestTimeoutException;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class RocketMqService {
@Value("${rocketmq.producer.send-topic}")
private String sendTopic; //客户端操作时间
@Value("${rocketmq.producer.send-tags}")
private String sendTags; //客户端操作时间
@Autowired
private RocketMQTemplate rocketMQTemplate;
public Message send(DeviceCommandApi deviceCommandApi)
{
return send(sendTopic, JSONObject.toJSONBytes(deviceCommandApi));
}
public Message send(String topic,String payload)
{
return send(topic,payload.getBytes());
}
public Message send(String topic,byte[] payload)
{
org.apache.rocketmq.common.message.Message msg = new org.apache.rocketmq.common.message.Message(topic,sendTags,payload);
try {
org.apache.rocketmq.common.message.Message ms = rocketMQTemplate.getProducer().request(msg,30000l);
JSONObject jsonObject = (JSONObject) JSON.parse(new String(ms.getBody()));
return new Message(MessageCode.getMessageCode(jsonObject.getInteger("code")),jsonObject.getString("message"),jsonObject.get("data"));
} catch (RequestTimeoutException e) {
e.printStackTrace();
} catch (MQClientException e) {
e.printStackTrace();
} catch (RemotingException e) {
e.printStackTrace();
} catch (MQBrokerException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Message(MessageCode.DEFAULT_FAIL_CODE);
}
}
... ...
package com.ruoyi.system.service;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.Message;
import com.ruoyi.common.core.domain.MessageCode;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.IotDevice;
import com.ruoyi.system.dto.ApiName;
import com.ruoyi.system.dto.DeviceCommandApi;
import com.ruoyi.system.dto.DeviceCommandApiParameter;
import com.ruoyi.system.rocketmq.RocketMqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Service
public class DeviceControlService {
@Autowired
protected RocketMqService rocketMqService;
@Autowired
private IIotDeviceService iIotDeviceService;
private DeviceCommandApi getDeviceCommandApi(String imei, Map<String,Object> map) {
DeviceCommandApi deviceCommandApi = new DeviceCommandApi();
deviceCommandApi.setApiName(ApiName.control);
DeviceCommandApiParameter deviceCommandApiParameter = new DeviceCommandApiParameter();
deviceCommandApiParameter.setClient_id(imei);
deviceCommandApiParameter.setMap(map);
deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
return deviceCommandApi;
}
/**
* 固件版本更新
* @param imei
* @param firmwareVersion
* @param code
* @return
* @throws IOException
*/
public Message firmwareUp( String imei, String firmwareVersion, Integer code) throws IOException {
Map<String,Object> map = new HashMap<>();
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("firmwareVersion",firmwareVersion);
valueMap.put("code",code);
map.put("0",valueMap);
DeviceCommandApi deviceCommandApi = getDeviceCommandApi(imei,map);
return rocketMqService.send(deviceCommandApi);
}
/**
* 设备重启
* @param imei
* @param restart
* @return
* @throws IOException
*/
public Message restart( String imei , Integer restart) {
Map<String,Object> map = new HashMap<>();
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("restart",restart);
map.put("0",valueMap);
DeviceCommandApi deviceCommandApi = getDeviceCommandApi(imei,map);
return rocketMqService.send(deviceCommandApi);
}
/**
* 获取指定设备版本信息
* @param imei
* @return
*/
public Message getFirmwareVersion( String imei) {
IotDevice iotDevice = iIotDeviceService.selectIotDeviceByClient_id(imei);
if(null == iotDevice || StringUtils.isBlank(iotDevice.getMqtt_username()))
{
return new Message(MessageCode.DEFAULT_FAIL_CODE,"设备或者设备类型不存在");
}
DeviceCommandApi deviceCommandApi = new DeviceCommandApi();
deviceCommandApi.setApiName(ApiName.getFirmwareVersion);
DeviceCommandApiParameter deviceCommandApiParameter = new DeviceCommandApiParameter();
deviceCommandApiParameter.setClient_id(imei);
deviceCommandApiParameter.setData(iotDevice.getMqtt_username());
deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
return rocketMqService.send(deviceCommandApi);
}
/**
* 强行断开链接
* @param imei
* @return
*/
public Message closeSession( String imei) {
DeviceCommandApi deviceCommandApi = new DeviceCommandApi();
deviceCommandApi.setApiName(ApiName.closeSession);
DeviceCommandApiParameter deviceCommandApiParameter = new DeviceCommandApiParameter();
deviceCommandApiParameter.setClient_id(imei);
deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
return rocketMqService.send(deviceCommandApi);
}
/**
* 删除主机
* @param imei
* @return
*/
public Message delIotDevice( String imei) {
DeviceCommandApi deviceCommandApi = new DeviceCommandApi();
deviceCommandApi.setApiName(ApiName.delIotDevice);
DeviceCommandApiParameter deviceCommandApiParameter = new DeviceCommandApiParameter();
deviceCommandApiParameter.setClient_id(imei);
deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
return rocketMqService.send(deviceCommandApi);
}
/**
* 删除终端
* @param imei
* @param number
* @return
*/
public Message delIotTerminal( String imei, String number) {
DeviceCommandApi deviceCommandApi = new DeviceCommandApi();
deviceCommandApi.setApiName(ApiName.delIotTerminal);
DeviceCommandApiParameter deviceCommandApiParameter = new DeviceCommandApiParameter();
deviceCommandApiParameter.setClient_id(imei);
deviceCommandApiParameter.setNumber(number);
deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
return rocketMqService.send(deviceCommandApi);
}
/**
* 读取属性
* @param imei
* @param sensor_number
* @param attributes
* @return
*/
public Message readAttribute( String imei, String sensor_number,String attributes) {
Map<String,Object> map = new HashMap<>();
map.put(sensor_number,attributes);
DeviceCommandApi deviceCommandApi = new DeviceCommandApi();
deviceCommandApi.setApiName(ApiName.read);
DeviceCommandApiParameter deviceCommandApiParameter = new DeviceCommandApiParameter();
deviceCommandApiParameter.setClient_id(imei);
deviceCommandApiParameter.setMap(map);
deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
return rocketMqService.send(deviceCommandApi);
}
/**
* 设置主机自定义参数
* @param imei
* @param summary
* @return
*/
public Message upSummary( String imei,String summary) {
Map<String,Object> map = new HashMap<>();
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("summary", JSONObject.parseObject(summary));
map.put("0", valueMap);
DeviceCommandApi deviceCommandApi = getDeviceCommandApi(imei,map);
return rocketMqService.send(deviceCommandApi);
}
/**
* 修改指定终端属性
* @param imei
* @param number
* @param config
* @return
*/
public Message upTerminalConfig( String imei, String number, Map<String,Object> config) {
Map<String,Object> map = new HashMap<>();
map.put(number,config);
DeviceCommandApi deviceCommandApi = getDeviceCommandApi(imei,map);
return rocketMqService.send(deviceCommandApi);
}
/**
* 批量修改终端属性
* @param imei
* @param map
* @return
*/
public Message batchUpTerminalConfig( String imei, Map<String,Object> map) {
DeviceCommandApi deviceCommandApi = getDeviceCommandApi(imei,map);
return rocketMqService.send(deviceCommandApi);
}
}
... ...
... ... @@ -124,4 +124,6 @@ public interface PublicService {
int deleteObjectById( Class<?> oClass, String id);
int insertIntoBySql(String sql);
public Long selectCountBySql(String sql);
}
... ...
package com.ruoyi.system.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.Message;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.IotProduct;
import com.ruoyi.system.dto.ApiName;
import com.ruoyi.system.dto.DeviceCommandApi;
import com.ruoyi.system.dto.DeviceCommandApiParameter;
import com.ruoyi.system.rocketmq.RocketMqService;
import com.ruoyi.system.service.IIotProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
... ... @@ -25,6 +33,8 @@ public class IotDeviceServiceImpl implements IIotDeviceService
private IotDeviceMapper iotDeviceMapper;
@Autowired
private IIotProductService iIotProductService;
@Autowired
protected RocketMqService rocketMqService;
/**
* 查询null
*
... ... @@ -83,7 +93,18 @@ public class IotDeviceServiceImpl implements IIotDeviceService
@Override
public int updateIotDevice(IotDevice iotDevice)
{
return iotDeviceMapper.updateIotDevice(iotDevice);
DeviceCommandApi deviceCommandApi = new DeviceCommandApi();
deviceCommandApi.setApiName(ApiName.updateIotDevice);
DeviceCommandApiParameter deviceCommandApiParameter = new DeviceCommandApiParameter();
Map<String,Object> map = JSONObject.parseObject(JSONObject.toJSONString(iotDevice), HashMap.class);
deviceCommandApiParameter.setMap(map);
deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
Message clJs = rocketMqService.send(deviceCommandApi);
if(clJs.getCode()==1)
{
return 1;
}
return 0;
}
/**
... ...
package com.ruoyi.system.service.impl;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
... ... @@ -11,6 +12,10 @@ import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.html.HttpUtils;
import com.ruoyi.system.domain.IotDevice;
import com.ruoyi.system.dto.ApiName;
import com.ruoyi.system.dto.DeviceCommandApi;
import com.ruoyi.system.dto.DeviceCommandApiParameter;
import com.ruoyi.system.rocketmq.RocketMqService;
import com.ruoyi.system.service.IIotDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
... ... @@ -31,6 +36,9 @@ public class IotTerminalServiceImpl implements IIotTerminalService
private IotTerminalMapper iotTerminalMapper;
@Autowired
private IIotDeviceService iotDeviceService;
@Autowired
protected RocketMqService rocketMqService;
/**
* 查询null
*
... ... @@ -87,7 +95,18 @@ public class IotTerminalServiceImpl implements IIotTerminalService
@Override
public int updateIotTerminal(IotTerminal iotTerminal)
{
return iotTerminalMapper.updateIotTerminal(iotTerminal);
DeviceCommandApi deviceCommandApi = new DeviceCommandApi();
deviceCommandApi.setApiName(ApiName.updateIotTerminal);
DeviceCommandApiParameter deviceCommandApiParameter = new DeviceCommandApiParameter();
Map<String,Object> map = JSONObject.parseObject(JSONObject.toJSONString(iotTerminal), HashMap.class);
deviceCommandApiParameter.setMap(map);
deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
Message clJs = rocketMqService.send(deviceCommandApi);
if(clJs.getCode()==1)
{
return 1;
}
return 0;
}
/**
... ... @@ -110,27 +129,12 @@ public class IotTerminalServiceImpl implements IIotTerminalService
@Override
public String deleteIotTerminalById(String imei, String number)
{
IotDevice iotDevice = iotDeviceService.selectIotDeviceByClient_id(imei);
if(StringUtils.isEmpty(iotDevice.getListen_service_ip()))
{
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
}
String url = "http://"+iotDevice.getListen_service_ip()+"device/delIotTerminal/"+imei+"/"+number;
String str = null;
try {
str = HttpUtils.getResponseString(HttpUtils.postFromBody(url, builder -> {
}, formBody -> {
}));
} catch (IOException e) {
}
iotTerminalMapper.deleteIotTerminalById(imei+"_"+number);
if(null != str)
{
return str;
}
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
DeviceCommandApi deviceCommandApi = new DeviceCommandApi();
deviceCommandApi.setApiName(ApiName.delIotTerminal);
DeviceCommandApiParameter deviceCommandApiParameter = new DeviceCommandApiParameter();
deviceCommandApiParameter.setClient_id(imei);
deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
return JSONObject.toJSONString(rocketMqService.send(deviceCommandApi));
}
@Override
... ...
... ... @@ -3,6 +3,7 @@ package com.ruoyi.system.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.mapper.PublicMapper;
import com.ruoyi.system.service.PublicService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
... ... @@ -164,6 +165,17 @@ public class PublicServiceImpl implements PublicService {
{
return publicMapper.getObjectListBySQL(sql);
}
/**
* 自定义sql语句查询数量
* @param sql
* @return
*/
public Long selectCountBySql(String sql)
{
return publicMapper.selectCountBySql(sql);
}
/**
* 添加或更新对象列表
* INSERT INTO `test` (`in1`,`str1`)VALUES ('1','2'),('2','2') ON DUPLICATE KEY UPDATE `in1`=VALUES(`in1`),`str1`=VALUES(`str1`);
... ...