作者 钟来

Merge remote-tracking branch 'origin/master'

# Conflicts:
#	lh-admin/src/main/resources/application-druid.yml
正在显示 77 个修改的文件 包含 2935 行增加621 行删除

要显示太多修改。

为保证性能只显示 77 of 77+ 个文件。

... ... @@ -35,7 +35,11 @@
<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>
... ...
... ... @@ -12,6 +12,8 @@ import org.springframework.context.annotation.ComponentScan;
"com.ruoyi.generator",
"com.zhonglai.luhui.admin.config",
"com.zhonglai.luhui.admin.controller",
"com.zhonglai.luhui.mqtt.comm.service.redis",
"com.zhonglai.luhui.mqtt.service.db.mode"
})
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class AdminApplication {
... ...
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 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 = "设备控制")
@Controller
@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;
}
@ApiOperation("固件版本更新")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
@ApiImplicitParam(value = "版本号",name = "firmwareVersion")
})
@PreAuthorize("@ss.hasPermi('iot:iotDeviceControl:firmwareUp')")
@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();
}
@ApiOperation("设备重启")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
@ApiImplicitParam(value = "restart 1重启,2复位,3恢复出厂值",name = "restart"),
})
@PreAuthorize("@ss.hasPermi('iot:iotDeviceControl:restart')")
@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> map = new HashMap<>();
Map<String,Object> valueMap = new HashMap<>();
valueMap.put("restart",restart);
Response response1 = HttpUtils.postJsonBody(url, formBody -> {
formBody.put("0",valueMap);
});
return response1.body().string();
}
@ApiOperation("获取指定设备版本信息")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
})
@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();
}
@ApiOperation("强行断开链接")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
})
@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();
}
@ApiOperation("删除主机")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
})
@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,"删除成功"));
}
@ApiOperation("删除终端")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
})
@ResponseBody
@PostMapping("/delIotTerminal/{imei}/{number}")
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()))
{
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) {
}
if(null != str)
{
return str;
}
return JSONObject.toJSONString(new Message(MessageCode.DEFAULT_SUCCESS_CODE,"删除成功"));
}
@ApiOperation(value = "读取属性")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
@ApiImplicitParam(value = "传感器编号(0,1_1,10_1)",name = "sensor_number"),
@ApiImplicitParam(value = "属性集合(id1,id2,id3)",name = "attributes"),
})
@PreAuthorize("@ss.hasPermi('iot:iotDeviceControl:upSummary')")
@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();
}
@ApiOperation(value = "设置主机自定义参数",notes = "自定义数据模型:\n" +
"{\n" +
" \t \"name\": \"wumei-smart\",\n" +
" \t \"chip\": \"esp8266\",\n" +
" \t \"author\": \"kerwincui\",\n" +
" \t \"version\": 1.2,\n" +
" \t \"createTime\": \"2022-06-06\"\n" +
" }")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
@ApiImplicitParam(value = "自定义数据json字符串",name = "summary")
})
@PreAuthorize("@ss.hasPermi('iot:iotDeviceControl:upSummary')")
@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();
}
@ApiOperation(value = "修改指定终端属性",notes = "配置参数模型:\n" +
"{\n" +
" \"id1\":\"value1\",\n" +
" \"id2\":\"value2\",\n" +
" \"id3\":\"value3\"\n" +
" }")
@ApiImplicitParams({
@ApiImplicitParam(value = "主机imei",name = "imei"),
@ApiImplicitParam(value = "终端编号(如:1_1)",name = "number"),
@ApiImplicitParam(value = "配置参数json字符串",name = "config")
})
@PreAuthorize("@ss.hasPermi('iot:iotDeviceControl:upTerminalConfig')")
@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();
}
@ApiOperation(value = "批量修改终端属性",notes = "批量数据模型:\n" +
"{\n" +
" \"1\":{\n" +
" \"id1\":\"value1\",\n" +
" \"id2\":\"value2\",\n" +
" \"id3\":\"value3\"\n" +
" },\n" +
" \"3\":{\n" +
" \"id1\":\"value1\",\n" +
" \"id2\":\"value2\",\n" +
" \"id3\":\"value3\"\n" +
" },\n" +
" \"4\":{\n" +
" \"id1\":\"value1\",\n" +
" \"id2\":\"value2\",\n" +
" \"id3\":\"value3\"\n" +
" }\n" +
"}")
@ApiImplicitParam(value = "批量数据json字符串",name = "map")
@PreAuthorize("@ss.hasPermi('iot:iotDeviceControl:batchUpTerminalConfig')")
@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();
}
}
... ...
... ... @@ -3,6 +3,10 @@ package com.zhonglai.luhui.admin.controller.iot;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.core.domain.Message;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.IotProduct;
import com.ruoyi.system.service.IIotProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
... ... @@ -37,7 +41,6 @@ public class IotDeviceController extends BaseController
{
@Autowired
private IIotDeviceService iotDeviceService;
/**
* 查询主机/网关列表
*/
... ... @@ -82,9 +85,11 @@ public class IotDeviceController extends BaseController
@ApiOperation("新增主机/网关")
@PreAuthorize("@ss.hasPermi('iot:IotDevice:add')")
@Log(title = "主机/网关", businessType = BusinessType.INSERT)
@PostMapping
@PostMapping("add")
public AjaxResult add(@RequestBody IotDevice iotDevice)
{
iotDevice.setCreate_by(getUsername());
iotDevice.setUpdate_time(DateUtils.getNowTimeMilly());
return toAjax(iotDeviceService.insertIotDevice(iotDevice));
}
... ... @@ -94,9 +99,11 @@ public class IotDeviceController extends BaseController
@ApiOperation("修改主机/网关")
@PreAuthorize("@ss.hasPermi('iot:IotDevice:edit')")
@Log(title = "主机/网关", businessType = BusinessType.UPDATE)
@PutMapping
@PutMapping("edit")
public AjaxResult edit(@RequestBody IotDevice iotDevice)
{
iotDevice.setUpdate_by(getUsername());
iotDevice.setUpdate_time(DateUtils.getNowTimeMilly());
return toAjax(iotDeviceService.updateIotDevice(iotDevice));
}
... ...
... ... @@ -19,8 +19,8 @@ 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.IotUser;
import com.ruoyi.system.service.IIotUserService;
import com.ruoyi.system.domain.IotProduct;
import com.ruoyi.system.service.IIotProductService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
... ... @@ -32,22 +32,22 @@ import com.ruoyi.common.core.page.TableDataInfo;
*/
@Api(tags = "产品")
@RestController
@RequestMapping("/iot/IotUser")
public class IotUserController extends BaseController
@RequestMapping("/iot/IotProduct")
public class IotProductController extends BaseController
{
@Autowired
private IIotUserService iotUserService;
private IIotProductService IotProductService;
/**
* 查询产品列表
*/
@ApiOperation("查询产品列表")
@PreAuthorize("@ss.hasPermi('iot:IotUser:list')")
@PreAuthorize("@ss.hasPermi('iot:IotProduct:list')")
@GetMapping("/list")
public TableDataInfo list(IotUser iotUser)
public TableDataInfo list(IotProduct iotProduct)
{
startPage();
List<IotUser> list = iotUserService.selectIotUserList(iotUser);
List<IotProduct> list = IotProductService.selectIotProductList(iotProduct);
return getDataTable(list);
}
... ... @@ -55,13 +55,13 @@ public class IotUserController extends BaseController
* 导出产品列表
*/
@ApiOperation("导出产品列表")
@PreAuthorize("@ss.hasPermi('iot:IotUser:export')")
@PreAuthorize("@ss.hasPermi('iot:IotProduct:export')")
@Log(title = "产品", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, IotUser iotUser)
public void export(HttpServletResponse response, IotProduct iotProduct)
{
List<IotUser> list = iotUserService.selectIotUserList(iotUser);
ExcelUtil<IotUser> util = new ExcelUtil<IotUser>(IotUser.class);
List<IotProduct> list = IotProductService.selectIotProductList(iotProduct);
ExcelUtil<IotProduct> util = new ExcelUtil<IotProduct>(IotProduct.class);
util.exportExcel(response, list, "产品数据");
}
... ... @@ -69,46 +69,46 @@ public class IotUserController extends BaseController
* 获取产品详细信息
*/
@ApiOperation("获取产品详细信息")
@PreAuthorize("@ss.hasPermi('iot:IotUser:query')")
@PreAuthorize("@ss.hasPermi('iot:IotProduct:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Integer id)
{
return AjaxResult.success(iotUserService.selectIotUserById(id));
return AjaxResult.success(IotProductService.selectIotProductById(id));
}
/**
* 新增产品
*/
@ApiOperation("新增产品")
@PreAuthorize("@ss.hasPermi('iot:IotUser:add')")
@PreAuthorize("@ss.hasPermi('iot:IotProduct:add')")
@Log(title = "产品", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody IotUser iotUser)
public AjaxResult add(@RequestBody IotProduct iotProduct)
{
return toAjax(iotUserService.insertIotUser(iotUser));
return toAjax(IotProductService.insertIotProduct(iotProduct));
}
/**
* 修改产品
*/
@ApiOperation("修改产品")
@PreAuthorize("@ss.hasPermi('iot:IotUser:edit')")
@PreAuthorize("@ss.hasPermi('iot:IotProduct:edit')")
@Log(title = "产品", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody IotUser iotUser)
public AjaxResult edit(@RequestBody IotProduct iotProduct)
{
return toAjax(iotUserService.updateIotUser(iotUser));
return toAjax(IotProductService.updateIotProduct(iotProduct));
}
/**
* 删除产品
*/
@ApiOperation("删除产品")
@PreAuthorize("@ss.hasPermi('iot:IotUser:remove')")
@PreAuthorize("@ss.hasPermi('iot:IotProduct:remove')")
@Log(title = "产品", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Integer[] ids)
{
return toAjax(iotUserService.deleteIotUserByIds(ids));
return toAjax(IotProductService.deleteIotProductByIds(ids));
}
}
... ...
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));
}
... ...
package com.zhonglai.luhui.admin.controller.iot;
import java.util.List;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.DistributionCurrencyModel;
import com.ruoyi.system.domain.IotProduct;
import com.ruoyi.system.service.IIotProductService;
import com.zhonglai.luhui.admin.dto.IotThingsModelAddApi;
import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelItemBase;
import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.specs.*;
import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
... ... @@ -38,6 +48,11 @@ public class IotThingsModelController extends BaseController
@Autowired
private IIotThingsModelService iotThingsModelService;
@Autowired
private TerminalDataThingsModeService terminalDataThingsModeService;
@Autowired
private IIotProductService iIotProductService;
/**
* 查询物模型模板列表
*/
... ... @@ -83,9 +98,46 @@ public class IotThingsModelController extends BaseController
@PreAuthorize("@ss.hasPermi('iot:IotThingsModel:add')")
@Log(title = "物模型模板", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody IotThingsModel iotThingsModel)
public AjaxResult add(@RequestBody IotThingsModelAddApi iotThingsModelAddApi)
{
IotThingsModel iotThingsModel = iotThingsModelAddApi.getIotThingsModel();
iotThingsModel.setCreate_by(getUsername());
ThingsModelItemBase thingsModelItemBase = null;
switch (iotThingsModel.getData_type())
{
case "integer":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), IntegerModelOutput.class);
break;
case "decimal":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), DecimalModelOutput.class);
break;
case "string":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), StringModelOutput.class);
break;
case "bool":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), BoolModelOutput.class);
break;
case "array":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), ArrayModelOutput.class);
break;
case "enum":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), EnumModelOutput.class);
break;
}
if(null == thingsModelItemBase)
{
return toAjax(iotThingsModelService.insertIotThingsModel(iotThingsModel));
return AjaxResult.error("请输入数模型");
}
iotThingsModel.setSpecs(JSONObject.toJSONString(thingsModelItemBase));
IotProduct iotProduct = iIotProductService.selectIotProductById(iotThingsModel.getProduct_id());
iotThingsModel.setMqtt_username(iotProduct.getMqtt_username());
int ri = iotThingsModelService.insertIotThingsModel(iotThingsModel);
terminalDataThingsModeService.saveIotThingsModel(JSON.parseObject(JSONObject.toJSONString(iotThingsModel),IotThingsModel.class));
return toAjax(ri);
}
/**
... ... @@ -95,9 +147,47 @@ public class IotThingsModelController extends BaseController
@PreAuthorize("@ss.hasPermi('iot:IotThingsModel:edit')")
@Log(title = "物模型模板", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody IotThingsModel iotThingsModel)
public AjaxResult edit(@RequestBody IotThingsModelAddApi iotThingsModelAddApi)
{
IotThingsModel iotThingsModel = iotThingsModelAddApi.getIotThingsModel();
iotThingsModel.setCreate_by(getUsername());
ThingsModelItemBase thingsModelItemBase = null;
switch (iotThingsModel.getData_type())
{
case "integer":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), IntegerModelOutput.class);
break;
case "decimal":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), DecimalModelOutput.class);
break;
case "string":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), StringModelOutput.class);
break;
case "bool":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), BoolModelOutput.class);
break;
case "array":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), ArrayModelOutput.class);
break;
case "enum":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), EnumModelOutput.class);
break;
}
if(null == thingsModelItemBase)
{
return toAjax(iotThingsModelService.updateIotThingsModel(iotThingsModel));
return AjaxResult.error("请输入数模型");
}
iotThingsModel.setSpecs(JSONObject.toJSONString(thingsModelItemBase));
int ri =iotThingsModelService.updateIotThingsModel(iotThingsModel);
IotThingsModel oldiotThingsModel = iotThingsModelService.selectIotThingsModelByModel_id(iotThingsModel.getModel_id());
IotProduct iotProduct = iIotProductService.selectIotProductById(oldiotThingsModel.getProduct_id());
iotThingsModel.setMqtt_username(iotProduct.getMqtt_username());
terminalDataThingsModeService.saveIotThingsModel(JSON.parseObject(JSONObject.toJSONString(iotThingsModel),IotThingsModel.class));
return toAjax(ri);
}
/**
... ... @@ -106,9 +196,49 @@ public class IotThingsModelController extends BaseController
@ApiOperation("删除物模型模板")
@PreAuthorize("@ss.hasPermi('iot:IotThingsModel:remove')")
@Log(title = "物模型模板", businessType = BusinessType.DELETE)
@Transactional
@DeleteMapping("/{model_ids}")
public AjaxResult remove(@PathVariable Integer[] model_ids)
{
return toAjax(iotThingsModelService.deleteIotThingsModelByModel_ids(model_ids));
Map<String,List<String>> map = new HashMap<>();
List<IotThingsModel> list = iotThingsModelService.selectIotThingsModelListByIds(model_ids);
if(null != list && list.size() !=0)
{
for(IotThingsModel iotThingsModel:list)
{
List<String> identifiers = map.get(iotThingsModel.getMqtt_username());
if(null == identifiers )
{
identifiers = new ArrayList<>();
map.put(iotThingsModel.getMqtt_username(),identifiers);
}
identifiers.add(iotThingsModel.getIdentifier());
}
}
int ri =iotThingsModelService.deleteIotThingsModelByModel_ids(model_ids);
if(null != map && map.size() !=0)
{
for(String key:map.keySet())
{
terminalDataThingsModeService.delIotThingsModel(key, map.get(key).toArray());
}
}
return toAjax(ri);
}
@ApiOperation("分配通用模型")
@PreAuthorize("@ss.hasPermi('iot:IotThingsModel:distributionTemplate')")
@Log(title = "物模型模板", businessType = BusinessType.INSERT)
@PostMapping("/distributionTemplate/{product_id}")
public AjaxResult distributionTemplate(@PathVariable Integer product_id,Integer[] tmplatemModel_ids)
{
DistributionCurrencyModel distributionCurrencyModel = new DistributionCurrencyModel();
IotProduct iotProduct = iIotProductService.selectIotProductById(product_id);
distributionCurrencyModel.setModel_ids(tmplatemModel_ids);
distributionCurrencyModel.setMqtt_username(iotProduct.getMqtt_username());
distributionCurrencyModel.setProduct_id(iotProduct.getId());
int ri = iotThingsModelService.distributionIotThingsModelTemplate(distributionCurrencyModel);
return toAjax(ri);
}
}
... ...
package com.zhonglai.luhui.admin.controller.iot;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.IotProduct;
import com.ruoyi.system.domain.IotThingsModel;
import com.ruoyi.system.service.IIotProductService;
import com.zhonglai.luhui.admin.dto.IotThingsModelAddApi;
import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelItemBase;
import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.specs.*;
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.IotThingsModelTemplate;
import com.ruoyi.system.service.IIotThingsModelTemplateService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
/**
* 物模型模板Controller
*
* @author 钟来
* @date 2022-10-24
*/
@Api(tags = "物模型模板公用模型")
@RestController
@RequestMapping("/iot/IotThingsModelTemplate")
public class IotThingsModelTemplateController extends BaseController
{
@Autowired
private IIotThingsModelTemplateService iotThingsModelTemplateService;
@Autowired
private IIotProductService iIotProductService;
/**
* 查询物模型模板列表
*/
@ApiOperation("查询物模型模板列表")
@PreAuthorize("@ss.hasPermi('iot:IotThingsModelTemplate:list')")
@GetMapping("/list")
public TableDataInfo list(IotThingsModelTemplate iotThingsModelTemplate)
{
startPage();
List<IotThingsModelTemplate> list = iotThingsModelTemplateService.selectIotThingsModelTemplateList(iotThingsModelTemplate);
return getDataTable(list);
}
/**
* 导出物模型模板列表
*/
@ApiOperation("导出物模型模板列表")
@PreAuthorize("@ss.hasPermi('iot:IotThingsModelTemplate:export')")
@Log(title = "物模型模板", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, IotThingsModelTemplate iotThingsModelTemplate)
{
List<IotThingsModelTemplate> list = iotThingsModelTemplateService.selectIotThingsModelTemplateList(iotThingsModelTemplate);
ExcelUtil<IotThingsModelTemplate> util = new ExcelUtil<IotThingsModelTemplate>(IotThingsModelTemplate.class);
util.exportExcel(response, list, "物模型模板数据");
}
/**
* 获取物模型模板详细信息
*/
@ApiOperation("获取物模型模板详细信息")
@PreAuthorize("@ss.hasPermi('iot:IotThingsModelTemplate:query')")
@GetMapping(value = "/{model_id}")
public AjaxResult getInfo(@PathVariable("model_id") Integer model_id)
{
return AjaxResult.success(iotThingsModelTemplateService.selectIotThingsModelTemplateByModel_id(model_id));
}
/**
* 新增物模型模板
*/
@ApiOperation("新增物模型模板")
@PreAuthorize("@ss.hasPermi('iot:IotThingsModelTemplate:add')")
@Log(title = "物模型模板", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody IotThingsModelAddApi iotThingsModelAddApi)
{
IotThingsModelTemplate iotThingsModel = JSONObject.parseObject(JSONObject.toJSONString(iotThingsModelAddApi.getIotThingsModel()),IotThingsModelTemplate.class);
iotThingsModel.setCreate_by(getUsername());
ThingsModelItemBase thingsModelItemBase = null;
switch (iotThingsModel.getData_type())
{
case "integer":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), IntegerModelOutput.class);
break;
case "decimal":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), DecimalModelOutput.class);
break;
case "string":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), StringModelOutput.class);
break;
case "bool":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), BoolModelOutput.class);
break;
case "array":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), ArrayModelOutput.class);
break;
case "enum":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), EnumModelOutput.class);
break;
}
if(null == thingsModelItemBase)
{
return AjaxResult.error("请输入数模型");
}
iotThingsModel.setSpecs(JSONObject.toJSONString(thingsModelItemBase));
iotThingsModel.setCreate_time(new Date());
int ri = iotThingsModelTemplateService.insertIotThingsModelTemplate(iotThingsModel);
return toAjax(ri);
}
/**
* 修改物模型模板
*/
@ApiOperation("修改物模型模板")
@PreAuthorize("@ss.hasPermi('iot:IotThingsModelTemplate:edit')")
@Log(title = "物模型模板", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody IotThingsModelAddApi iotThingsModelAddApi)
{
IotThingsModelTemplate iotThingsModel = JSONObject.parseObject(JSONObject.toJSONString(iotThingsModelAddApi.getIotThingsModel()),IotThingsModelTemplate.class);
iotThingsModel.setCreate_by(getUsername());
ThingsModelItemBase thingsModelItemBase = null;
switch (iotThingsModel.getData_type())
{
case "integer":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), IntegerModelOutput.class);
break;
case "decimal":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), DecimalModelOutput.class);
break;
case "string":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), StringModelOutput.class);
break;
case "bool":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), BoolModelOutput.class);
break;
case "array":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), ArrayModelOutput.class);
break;
case "enum":
thingsModelItemBase = JSONObject.parseObject(JSON.toJSONString(iotThingsModelAddApi.getThingsModelBase()), EnumModelOutput.class);
break;
}
if(null == thingsModelItemBase)
{
return AjaxResult.error("请输入数模型");
}
iotThingsModel.setSpecs(JSONObject.toJSONString(thingsModelItemBase));
int ri =iotThingsModelTemplateService.updateIotThingsModelTemplate(iotThingsModel);
return toAjax(ri);
}
/**
* 删除物模型模板
*/
@ApiOperation("删除物模型模板")
@PreAuthorize("@ss.hasPermi('iot:IotThingsModelTemplate:remove')")
@Log(title = "物模型模板", businessType = BusinessType.DELETE)
@DeleteMapping("/{model_ids}")
public AjaxResult remove(@PathVariable Integer[] model_ids)
{
return toAjax(iotThingsModelTemplateService.deleteIotThingsModelTemplateByModel_ids(model_ids));
}
}
... ...
package com.zhonglai.luhui.admin.dto;
import com.ruoyi.system.domain.IotThingsModel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Map;
@ApiModel("物模型添加对象")
public class IotThingsModelAddApi {
@ApiModelProperty("物模型信息")
private IotThingsModel iotThingsModel;
@ApiModelProperty("specs数据定义对象")
private Map<String,Object> thingsModelBase;
public IotThingsModel getIotThingsModel() {
return iotThingsModel;
}
public void setIotThingsModel(IotThingsModel iotThingsModel) {
this.iotThingsModel = iotThingsModel;
}
public Map<String,Object> getThingsModelBase() {
return thingsModelBase;
}
public void setThingsModelBase(Map<String,Object> thingsModelBase) {
this.thingsModelBase = thingsModelBase;
}
}
... ...
... ... @@ -6,7 +6,6 @@ spring:
druid:
# 主库数据源
master:
# url: jdbc:mysql://114.215.126.2:3306/jc-wenjuan?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
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
... ...
# 项目相关配置 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: 30 # 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/* 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();
}
}
... ...
<?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-domain</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
</dependency>
<!-- Swagger3依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
\ No newline at end of file
... ...
package com.zhonglai.luhui.mqtt.comm.dto.iot;
package com.ruoyi.system.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
import java.util.Map;
import java.io.Serializable;
/**
* 主机/网关对象 iot_device
... ... @@ -15,7 +14,7 @@ import java.util.Map;
* @date 2022-08-26
*/
@ApiModel("主机/网关")
public class IotDevice
public class IotDevice implements Serializable
{
private static final long serialVersionUID = 1L;
... ... @@ -45,7 +44,7 @@ public class IotDevice
/** 固件版本 */
@ApiModelProperty("固件版本")
private Float firmware_version;
private String firmware_version;
/** 图片地址 */
@ApiModelProperty("图片地址")
... ... @@ -84,7 +83,7 @@ public class IotDevice
private Integer rssi;
/** 设备状态(1-未激活,2-禁用,3-在线,4-离线) */
@ApiModelProperty("设备状态(1-未激活,2-禁用,3-在线,4-离线)")
@ApiModelProperty("设备状态(1-未激活,2-禁用,3-在线,4-离线,5-锁定)")
private Integer status;
/** 设备摘要,格式[{"name":"device"},{"chip":"esp8266"}] */
... ... @@ -103,23 +102,63 @@ public class IotDevice
@ApiModelProperty("更新时间")
private Integer update_time;
/** 用户id */
@ApiModelProperty("用户id")
private Integer user_id;
@ApiModelProperty("产品id")
private Integer product_id;
@ApiModelProperty("mqtt用户名/设备类型")
private String mqtt_username;
@ApiModelProperty("负载类型(String,Json,Bite16,Bite32)")
private String payload_type;
@ApiModelProperty("payload 协议模型")
private String business_model; //payload 协议模型
public String getBusiness_model() {
return business_model;
@ApiModelProperty("物模型配置")
private String things_model_config; //payload 协议模型
@ApiModelProperty("监听服务器的ip")
private String listen_service_ip;
@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;
}
public void setBusiness_model(String business_model) {
this.business_model = business_model;
public void setListen_service_ip(String listen_service_ip) {
this.listen_service_ip = listen_service_ip;
}
public String getThings_model_config() {
return things_model_config;
}
public void setThings_model_config(String things_model_config) {
this.things_model_config = things_model_config;
}
public String getPayload_type() {
return payload_type;
}
... ... @@ -182,12 +221,12 @@ public class IotDevice
{
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;
}
... ... @@ -317,40 +356,29 @@ public class IotDevice
{
return update_time;
}
public void setUser_id(Integer user_id)
{
this.user_id = user_id;
}
public Integer getUser_id()
{
return user_id;
}
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("active_time", getActive_time())
.append("client_id", getClient_id())
.append("completion_auth", getCompletion_auth())
.append("create_by", getCreate_by())
.append("create_time", getCreate_time())
.append("del_flag", getDel_flag())
.append("firmware_version", getFirmware_version())
.append("img_url", getImg_url())
.append("is_shadow", getIs_shadow())
.append("latitude", getLatitude())
.append("location_way", getLocation_way())
.append("longitude", getLongitude())
.append("name", getName())
.append("network_address", getNetwork_address())
.append("network_ip", getNetwork_ip())
.append("rssi", getRssi())
.append("status", getStatus())
.append("summary", getSummary())
.append("things_model_value", getThings_model_value())
.append("update_by", getUpdate_by())
.append("update_time", getUpdate_time())
.append("user_id", getUser_id())
.toString();
public Integer getProduct_id() {
return product_id;
}
public void setProduct_id(Integer product_id) {
this.product_id = product_id;
}
public String getMqtt_username() {
return mqtt_username;
}
public void setMqtt_username(String mqtt_username) {
this.mqtt_username = mqtt_username;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
... ...
package com.ruoyi.system.domain;
import com.ruoyi.system.domain.tool.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* topic权限控制对象 iot_permission
*
... ... @@ -14,7 +15,7 @@ import io.swagger.annotations.ApiModelProperty;
* @date 2022-08-26
*/
@ApiModel("topic权限控制")
public class IotPermission extends BaseEntity
public class IotPermission implements Serializable
{
private static final long serialVersionUID = 1L;
... ...
package com.zhonglai.luhui.mqtt.comm.dto.iot;
package com.ruoyi.system.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.ruoyi.system.domain.tool.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* 产品对象 iot_user
* 产品对象 iot_product
*
* @author 钟来
* @date 2022-08-26
*/
@ApiModel("产品")
public class IotUser
public class IotProduct implements Serializable
{
private static final long serialVersionUID = 1L;
... ... @@ -34,7 +37,7 @@ public class IotUser
/** 密码 */
@ApiModelProperty("密码")
private String password;
private String mqtt_password;
/** 角色id */
@ApiModelProperty("角色id")
... ... @@ -42,7 +45,7 @@ public class IotUser
/** 盐 */
@ApiModelProperty("盐")
private String salt;
private String mqtt_salt;
/** 是否使用(0否,1是) */
@ApiModelProperty("是否使用(0否,1是)")
... ... @@ -50,7 +53,11 @@ public class IotUser
/** 用户名 */
@ApiModelProperty("用户名")
private String username;
private String mqtt_username;
@ApiModelProperty("产品名称")
private String product_name;
public void setCreate_time(Integer create_time)
{
... ... @@ -88,15 +95,6 @@ public class IotUser
{
return open_encryption;
}
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return password;
}
public void setRole_id(Integer role_id)
{
this.role_id = role_id;
... ... @@ -106,15 +104,7 @@ public class IotUser
{
return role_id;
}
public void setSalt(String salt)
{
this.salt = salt;
}
public String getSalt()
{
return salt;
}
public void setUsed(Integer used)
{
this.used = used;
... ... @@ -124,27 +114,52 @@ public class IotUser
{
return used;
}
public void setUsername(String username)
{
this.username = username;
public String getMqtt_password() {
return mqtt_password;
}
public String getUsername()
{
return username;
public void setMqtt_password(String mqtt_password) {
this.mqtt_password = mqtt_password;
}
public String getMqtt_salt() {
return mqtt_salt;
}
public void setMqtt_salt(String mqtt_salt) {
this.mqtt_salt = mqtt_salt;
}
public String getMqtt_username() {
return mqtt_username;
}
public void setMqtt_username(String mqtt_username) {
this.mqtt_username = mqtt_username;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("create_time", getCreate_time())
.append("encryption_type", getEncryption_type())
.append("id", getId())
.append("open_encryption", getOpen_encryption())
.append("password", getPassword())
.append("mqtt_password", getMqtt_password())
.append("role_id", getRole_id())
.append("salt", getSalt())
.append("mqtt_salt", getMqtt_salt())
.append("used", getUsed())
.append("username", getUsername())
.append("mqtt_username", getMqtt_username())
.append("product_name", getProduct_name())
.toString();
}
}
... ...
package com.zhonglai.luhui.mqtt.comm.dto.iot;
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_role
* 产品指标翻译对象 iot_product_translate
*
* @author 钟来
* @date 2022-08-26
* @date 2022-11-04
*/
@ApiModel("公司")
public class IotRole
@ApiModel("产品指标翻译")
public class IotProductTranslate extends BaseEntity
{
private static final long serialVersionUID = 1L;
... ... @@ -20,21 +21,21 @@ public class IotRole
@ApiModelProperty("创建时间")
private Integer create_time;
/** 描述 */
@ApiModelProperty("描述")
private String describe;
/** 主键 */
@ApiModelProperty("主键")
private Integer id;
/** 名称 */
@ApiModelProperty("名称")
private String name;
/** 模型标识 */
@ApiModelProperty("模型标识")
private String model_identifier;
/** 产品id */
@ApiModelProperty("产品id")
private Integer product_id;
/** 是否使用(0否,1是) */
@ApiModelProperty("是否使用(0否,1是)")
private Integer used;
/** 翻译的模型标识(支持两层josn键值,用英文点分割) */
@ApiModelProperty("翻译的模型标识(支持两层josn键值,用英文点分割如:11:start)")
private String translate_identifier;
public void setCreate_time(Integer create_time)
{
... ... @@ -45,50 +46,51 @@ public class IotRole
{
return create_time;
}
public void setDescribe(String describe)
public void setId(Integer id)
{
this.describe = describe;
this.id = id;
}
public String getDescribe()
public Integer getId()
{
return describe;
return id;
}
public void setId(Integer id)
public void setModel_identifier(String model_identifier)
{
this.id = id;
this.model_identifier = model_identifier;
}
public Integer getId()
public String getModel_identifier()
{
return id;
return model_identifier;
}
public void setName(String name)
public void setProduct_id(Integer product_id)
{
this.name = name;
this.product_id = product_id;
}
public String getName()
public Integer getProduct_id()
{
return name;
return product_id;
}
public void setUsed(Integer used)
public void setTranslate_identifier(String translate_identifier)
{
this.used = used;
this.translate_identifier = translate_identifier;
}
public Integer getUsed()
public String getTranslate_identifier()
{
return used;
return translate_identifier;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("create_time", getCreate_time())
.append("describe", getDescribe())
.append("id", getId())
.append("name", getName())
.append("used", getUsed())
.append("model_identifier", getModel_identifier())
.append("product_id", getProduct_id())
.append("translate_identifier", getTranslate_identifier())
.toString();
}
}
... ...
package com.ruoyi.system.domain;
import com.ruoyi.system.domain.tool.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* 公司对象 iot_role
*
... ... @@ -14,7 +15,7 @@ import io.swagger.annotations.ApiModelProperty;
* @date 2022-08-26
*/
@ApiModel("公司")
public class IotRole extends BaseEntity
public class IotRole implements Serializable
{
private static final long serialVersionUID = 1L;
... ...
... ... @@ -2,11 +2,11 @@ package com.ruoyi.system.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* 终端对象 iot_terminal
*
... ... @@ -14,7 +14,7 @@ import io.swagger.annotations.ApiModelProperty;
* @date 2022-08-26
*/
@ApiModel("终端")
public class IotTerminal extends BaseEntity
public class IotTerminal implements Serializable
{
private static final long serialVersionUID = 1L;
... ... @@ -37,7 +37,48 @@ public class IotTerminal extends BaseEntity
/** 更新时间 */
@ApiModelProperty("更新时间")
private Integer update_time;
@ApiModelProperty("物模型配置")
private String things_model_config; //payload 协议模型
@ApiModelProperty("产品id")
private Integer product_id;
@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;
}
public void setProduct_id(Integer product_id) {
this.product_id = product_id;
}
public String getMqtt_username() {
return mqtt_username;
}
public void setMqtt_username(String mqtt_username) {
this.mqtt_username = mqtt_username;
}
public String getThings_model_config() {
return things_model_config;
}
public void setThings_model_config(String things_model_config) {
this.things_model_config = things_model_config;
}
public void setDevice_id(String device_id)
{
this.device_id = device_id;
... ... @@ -92,6 +133,8 @@ public class IotTerminal extends BaseEntity
.append("name", getName())
.append("things_model_value", getThings_model_value())
.append("update_time", getUpdate_time())
.append("product_id", getProduct_id())
.append("mqtt_username", getMqtt_username())
.toString();
}
}
... ...
package com.ruoyi.system.domain;
import com.ruoyi.system.domain.tool.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* 物模型模板对象 iot_things_model
*
... ... @@ -14,7 +15,7 @@ import io.swagger.annotations.ApiModelProperty;
* @date 2022-08-26
*/
@ApiModel("物模型模板")
public class IotThingsModel extends BaseEntity
public class IotThingsModel implements Serializable
{
private static final long serialVersionUID = 1L;
... ... @@ -74,9 +75,68 @@ public class IotThingsModel extends BaseEntity
@ApiModelProperty("更新时间")
private java.util.Date update_time;
/** 用户id */
@ApiModelProperty("用户id")
private Integer user_id;
@ApiModelProperty("mqtt用户名/设备类型")
private String mqtt_username;
@ApiModelProperty("产品id")
private Integer product_id;
@ApiModelProperty("是否配置属性(0否,1是)")
private Integer is_config;
@ApiModelProperty("展示类型")
private String view_type;
@ApiModelProperty("对应配置属性名称集合(英文逗号分割)")
private String config_names;
@ApiModelProperty("归属(0主键,1终端)")
private String ascription;
/** 数据定义 */
@ApiModelProperty("数据定义")
private String remark;
public String getAscription() {
return ascription;
}
public void setAscription(String ascription) {
this.ascription = ascription;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getView_type() {
return view_type;
}
public void setView_type(String view_type) {
this.view_type = view_type;
}
public String getConfig_names() {
return config_names;
}
public void setConfig_names(String config_names) {
this.config_names = config_names;
}
public Integer getIs_config() {
return is_config;
}
public void setIs_config(Integer is_config) {
this.is_config = is_config;
}
public void setCreate_by(String create_by)
{
... ... @@ -204,14 +264,21 @@ public class IotThingsModel extends BaseEntity
{
return update_time;
}
public void setUser_id(Integer user_id)
{
this.user_id = user_id;
public String getMqtt_username() {
return mqtt_username;
}
public Integer getUser_id()
{
return user_id;
public void setMqtt_username(String mqtt_username) {
this.mqtt_username = mqtt_username;
}
public Integer getProduct_id() {
return product_id;
}
public void setProduct_id(Integer product_id) {
this.product_id = product_id;
}
@Override
... ... @@ -227,12 +294,12 @@ public class IotThingsModel extends BaseEntity
.append("is_top", getIs_top())
.append("model_id", getModel_id())
.append("model_name", getModel_name())
.append("remark", getRemark())
.append("specs", getSpecs())
.append("type", getType())
.append("update_by", getUpdate_by())
.append("update_time", getUpdate_time())
.append("user_id", getUser_id())
.append("product_id", getProduct_id())
.append("mqtt_username", getMqtt_username())
.toString();
}
}
... ...
package com.zhonglai.luhui.mqtt.comm.dto.iot;
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_things_model
* 物模型模板对象 iot_things_model_template
*
* @author 钟来
* @date 2022-08-26
* @date 2022-10-24
*/
@ApiModel("物模型模板")
public class IotThingsModel
public class IotThingsModelTemplate extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 归属(0主键,1终端) */
@ApiModelProperty("归属(0主键,1终端)")
private Integer ascription;
/** 对应配置属性名称集合(英文逗号分割) */
@ApiModelProperty("对应配置属性名称集合(英文逗号分割)")
private String config_names;
/** 创建者 */
@ApiModelProperty("创建者")
private String create_by;
... ... @@ -36,6 +45,10 @@ public class IotThingsModel
@ApiModelProperty("标识符,用户下唯一")
private String identifier;
/** 是否配置属性(0否,1是) */
@ApiModelProperty("是否配置属性(0否,1是)")
private Integer is_config;
/** 是否实时监测(0-否,1-是) */
@ApiModelProperty("是否实时监测(0-否,1-是)")
private Integer is_monitor;
... ... @@ -56,6 +69,14 @@ public class IotThingsModel
@ApiModelProperty("物模型名称")
private String model_name;
/** mqtt用户名/设备类型 */
@ApiModelProperty("mqtt用户名/设备类型")
private String mqtt_username;
/** 产品id */
@ApiModelProperty("产品id")
private Integer product_id;
/** 数据定义 */
@ApiModelProperty("数据定义")
private String specs;
... ... @@ -72,22 +93,28 @@ public class IotThingsModel
@ApiModelProperty("更新时间")
private java.util.Date update_time;
/** 用户id */
@ApiModelProperty("用户id")
private Integer user_id;
/** 用户id */
@ApiModelProperty("用户名称")
private Integer user_name;
/** 页面展示类型 */
@ApiModelProperty("页面展示类型")
private String view_type;
public Integer getUser_name() {
return user_name;
public void setAscription(Integer ascription)
{
this.ascription = ascription;
}
public void setUser_name(Integer user_name) {
this.user_name = user_name;
public Integer getAscription()
{
return ascription;
}
public void setConfig_names(String config_names)
{
this.config_names = config_names;
}
public String getConfig_names()
{
return config_names;
}
public void setCreate_by(String create_by)
{
this.create_by = create_by;
... ... @@ -133,6 +160,15 @@ public class IotThingsModel
{
return identifier;
}
public void setIs_config(Integer is_config)
{
this.is_config = is_config;
}
public Integer getIs_config()
{
return is_config;
}
public void setIs_monitor(Integer is_monitor)
{
this.is_monitor = is_monitor;
... ... @@ -178,6 +214,24 @@ public class IotThingsModel
{
return model_name;
}
public void setMqtt_username(String mqtt_username)
{
this.mqtt_username = mqtt_username;
}
public String getMqtt_username()
{
return mqtt_username;
}
public void setProduct_id(Integer product_id)
{
this.product_id = product_id;
}
public Integer getProduct_id()
{
return product_id;
}
public void setSpecs(String specs)
{
this.specs = specs;
... ... @@ -214,33 +268,40 @@ public class IotThingsModel
{
return update_time;
}
public void setUser_id(Integer user_id)
public void setView_type(String view_type)
{
this.user_id = user_id;
this.view_type = view_type;
}
public Integer getUser_id()
public String getView_type()
{
return user_id;
return view_type;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("ascription", getAscription())
.append("config_names", getConfig_names())
.append("create_by", getCreate_by())
.append("create_time", getCreate_time())
.append("data_type", getData_type())
.append("del_flag", getDel_flag())
.append("identifier", getIdentifier())
.append("is_config", getIs_config())
.append("is_monitor", getIs_monitor())
.append("is_save_log", getIs_save_log())
.append("is_top", getIs_top())
.append("model_id", getModel_id())
.append("model_name", getModel_name())
.append("mqtt_username", getMqtt_username())
.append("product_id", getProduct_id())
.append("remark", getRemark())
.append("specs", getSpecs())
.append("type", getType())
.append("update_by", getUpdate_by())
.append("update_time", getUpdate_time())
.append("user_id", getUser_id())
.append("view_type", getView_type())
.toString();
}
}
... ...
package com.ruoyi.system.domain;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.system.domain.tool.BaseEntity;
import com.ruoyi.system.domain.tool.Excel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
... ... @@ -23,7 +22,7 @@ public class SysConfig extends BaseEntity
/** 参数主键 */
@ApiModelProperty("参数主键")
@Excel(name = "参数主键", cellType = ColumnType.NUMERIC)
@Excel(name = "参数主键", cellType = Excel.ColumnType.NUMERIC)
private Long configId;
/** 参数名称 */
... ...
package com.ruoyi.system.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.system.domain.tool.BaseEntity;
import com.ruoyi.system.domain.tool.Excel;
import java.util.Date;
... ... @@ -17,7 +16,7 @@ public class SysLogininfor extends BaseEntity
private static final long serialVersionUID = 1L;
/** ID */
@Excel(name = "序号", cellType = ColumnType.NUMERIC)
@Excel(name = "序号", cellType = Excel.ColumnType.NUMERIC)
private Long infoId;
/** 用户账号 */
... ...
package com.ruoyi.system.domain;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.xss.Xss;
import com.ruoyi.system.domain.tool.BaseEntity;
import com.ruoyi.system.domain.tool.Xss;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
... ...
package com.ruoyi.system.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.system.domain.tool.BaseEntity;
import com.ruoyi.system.domain.tool.Excel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
... ... @@ -21,7 +20,7 @@ public class SysOperLog extends BaseEntity
/** 日志主键 */
@ApiModelProperty("操作序号")
@Excel(name = "操作序号", cellType = ColumnType.NUMERIC)
@Excel(name = "操作序号", cellType = Excel.ColumnType.NUMERIC)
private Long operId;
/** 操作模块 */
... ...
package com.ruoyi.system.domain;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.system.domain.tool.BaseEntity;
import com.ruoyi.system.domain.tool.Excel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
... ... @@ -23,7 +22,7 @@ public class SysPost extends BaseEntity
/** 岗位序号 */
@ApiModelProperty("岗位序号")
@Excel(name = "岗位序号", cellType = ColumnType.NUMERIC)
@Excel(name = "岗位序号", cellType = Excel.ColumnType.NUMERIC)
private Long postId;
/** 岗位编码 */
... ...
package com.ruoyi.common.core.domain;
package com.ruoyi.system.domain.tool;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.data.annotation.Transient;
... ...
package com.ruoyi.common.annotation;
import com.ruoyi.common.utils.poi.ExcelHandlerAdapter;
package com.ruoyi.system.domain.tool;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
... ...
package com.ruoyi.common.utils.poi;
package com.ruoyi.system.domain.tool;
/**
* Excel数据格式处理适配器
... ...
package com.ruoyi.common.xss;
package com.ruoyi.system.domain.tool;
import javax.validation.Constraint;
import javax.validation.Payload;
... ...
package com.ruoyi.common.xss;
package com.ruoyi.system.domain.tool;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
... ...
package com.ruoyi.system.domain.vo;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.StringUtils;
/**
* 路由显示信息
... ... @@ -58,7 +59,7 @@ public class MetaVo
this.title = title;
this.icon = icon;
this.noCache = noCache;
if (StringUtils.ishttp(link))
if (StringUtils.startsWithAny(link, "http://", "https://"))
{
this.link = link;
}
... ...
... ... @@ -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": {
... ...
... ... @@ -12,11 +12,42 @@
<artifactId>lh-mqtt-service</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>
<!-- yml解析器 -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</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>
... ... @@ -58,11 +89,6 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.jodah</groupId>
<artifactId>expiringmap</artifactId>
</dependency>
... ... @@ -113,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>
... ... @@ -126,6 +161,12 @@
<artifactId>okhttp</artifactId>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>lh-domain</artifactId>
</dependency>
</dependencies>
<build>
... ... @@ -151,7 +192,7 @@
生成的manifest中classpath的前缀,因为要把第三方jar放到lib目录下,所以classpath的前缀是lib/
-->
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.zhonglai.waibao.juheliaotian.mqtt.service.MqttServiceApplication</mainClass>
<mainClass>com.zhonglai.luhui.mqtt.MqttApplication</mainClass>
</manifest>
</archive>
</configuration>
... ...
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;
... ... @@ -14,13 +15,23 @@ import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.PostConstruct;
@Configuration
public class RedisConfig {
@Value("${sys.redis.field:#{'luhui:mqttservice:device:'}")
@Value("${sys.redis.field}")
public String sysRedisField ; //域
public static String FIELD ; //域
public static String DEVICE = "device:"; //存放网关数据
public static String THINGS_MODEL = "things_model:"; //存放数据模型
public static String TERMINAL = "terminal:"; //存放终端数据
public static String LOCK = "lock:"; //存放设备锁
@PostConstruct
public void init()
{
RedisConfig.FIELD = sysRedisField;
}
@Bean
... ... @@ -44,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);
... ...
... ... @@ -18,10 +18,14 @@ public class SysParameter {
@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 static void init() {
public void init() {
String service_ip_url = "http://ly.userlogin.yu2le.com/ip";
JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(service_ip_url));
service_ip = jsonObject.getString("data");
... ... @@ -32,4 +36,5 @@ public class SysParameter {
{
topicconfig = tempTopicconfig;
}
}
... ...
... ... @@ -233,7 +233,13 @@ public class BaseDao {
{
Field field = fields[i];
try {
Method method = object.getClass().getMethod("get"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.getName(field.getName()));
Method method = null;
try {
method = object.getClass().getMethod("get"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.getName(field.getName()));
} catch (NoSuchMethodException e) {
continue;
}
Object value = method.invoke(object);
if(null != value)
{
... ... @@ -241,13 +247,10 @@ public class BaseDao {
{
sql += ",";
}
sql += "`"+changTableNameFromObject(field.getName())+"`"+"=?";
sql += "`"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`"+"=?";
j++;
valueList.add(value);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
... ... @@ -276,7 +279,7 @@ public class BaseDao {
Method method = object.getClass().getMethod("get"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.getName(wheres[i]));
Object value = method.invoke(object);
sql += " and ";
sql += changTableNameFromObject(wheres[i]) + "=?";
sql += com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(wheres[i]) + "=?";
valueList.add(value);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
... ... @@ -774,7 +777,6 @@ public class BaseDao {
update += "`"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`"+"=VALUES("+"`"+com.zhonglai.luhui.mqtt.comm.util.StringUtils.toUnderScoreCase(field.getName())+"`)";
}
} catch (NoSuchMethodException e) {
System.out.println("未找到"+field.getName()+"的get方法");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
... ...
... ... @@ -5,7 +5,6 @@ import com.zhonglai.luhui.mqtt.comm.factory.Topic;
import com.zhonglai.luhui.mqtt.dto.Message;
public interface ServerAgreementContent {
String getClienConnectionId();
byte[] getCommd();
String getReplyCommdTopic(Topic topic);
void setReplyMessage(Message message);
... ...
package com.zhonglai.luhui.mqtt.comm.dto;
import java.util.List;
public interface ServerDto {
ServerAgreementContent getServerAgreementContent();
boolean isReplyMessage();
List<DeviceSensorData> getDeviceSensorData();
List<LogDeviceOperation> getOperationLog();
}
... ...
package com.zhonglai.luhui.mqtt.comm.dto.iot;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* topic权限控制对象 iot_permission
*
* @author 钟来
* @date 2022-08-26
*/
@ApiModel("topic权限控制")
public class IotPermission
{
private static final long serialVersionUID = 1L;
/** 动作(PUBLISH,SUBSCRIBE,ALL) */
@ApiModelProperty("动作(PUBLISH,SUBSCRIBE,ALL)")
private String activity;
/** 创建时间 */
@ApiModelProperty("创建时间")
private Integer create_time;
/** 描述 */
@ApiModelProperty("描述")
private String describe;
/** 主键 */
@ApiModelProperty("主键")
private Integer id;
/** 质量(ZERO,ONE,TWO,ZERO_ONE,ZERO_TWO,ONE_TWO,ALL) */
@ApiModelProperty("质量(ZERO,ONE,TWO,ZERO_ONE,ZERO_TWO,ONE_TWO,ALL)")
private String qos;
/** 是否保留(RETAINED,NOT_RETAINED,ALL) */
@ApiModelProperty("是否保留(RETAINED,NOT_RETAINED,ALL)")
private String retain;
/** 角色id */
@ApiModelProperty("角色id")
private Integer role_id;
/** 共享组 */
@ApiModelProperty("共享组")
private String shared_group;
/** 共享订阅(SHARED,NOT_SHARED,ALL) */
@ApiModelProperty("共享订阅(SHARED,NOT_SHARED,ALL)")
private String shared_subscription;
/** topic(同一角色有切只有一个) */
@ApiModelProperty("topic(同一角色有切只有一个)")
private String topic;
public void setActivity(String activity)
{
this.activity = activity;
}
public String getActivity()
{
return activity;
}
public void setCreate_time(Integer create_time)
{
this.create_time = create_time;
}
public Integer getCreate_time()
{
return create_time;
}
public void setDescribe(String describe)
{
this.describe = describe;
}
public String getDescribe()
{
return describe;
}
public void setId(Integer id)
{
this.id = id;
}
public Integer getId()
{
return id;
}
public void setQos(String qos)
{
this.qos = qos;
}
public String getQos()
{
return qos;
}
public void setRetain(String retain)
{
this.retain = retain;
}
public String getRetain()
{
return retain;
}
public void setRole_id(Integer role_id)
{
this.role_id = role_id;
}
public Integer getRole_id()
{
return role_id;
}
public void setShared_group(String shared_group)
{
this.shared_group = shared_group;
}
public String getShared_group()
{
return shared_group;
}
public void setShared_subscription(String shared_subscription)
{
this.shared_subscription = shared_subscription;
}
public String getShared_subscription()
{
return shared_subscription;
}
public void setTopic(String topic)
{
this.topic = topic;
}
public String getTopic()
{
return topic;
}
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("activity", getActivity())
.append("create_time", getCreate_time())
.append("describe", getDescribe())
.append("id", getId())
.append("qos", getQos())
.append("retain", getRetain())
.append("role_id", getRole_id())
.append("shared_group", getShared_group())
.append("shared_subscription", getShared_subscription())
.append("topic", getTopic())
.toString();
}
}
package com.zhonglai.luhui.mqtt.comm.dto.iot;
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_terminal
*
* @author 钟来
* @date 2022-08-26
*/
@ApiModel("终端")
public class IotTerminal
{
private static final long serialVersionUID = 1L;
/** 网关id */
@ApiModelProperty("网关id")
private String device_id;
/** 主键id */
@ApiModelProperty("主键id")
private String id;
/** 终端名称 */
@ApiModelProperty("终端名称")
private String name;
/** 物模型值 */
@ApiModelProperty("物模型值")
private String things_model_value;
/** 更新时间 */
@ApiModelProperty("更新时间")
private Integer update_time;
public void setDevice_id(String device_id)
{
this.device_id = device_id;
}
public String getDevice_id()
{
return device_id;
}
public void setId(String id)
{
this.id = id;
}
public String getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setThings_model_value(String things_model_value)
{
this.things_model_value = things_model_value;
}
public String getThings_model_value()
{
return things_model_value;
}
public void setUpdate_time(Integer update_time)
{
this.update_time = update_time;
}
public Integer getUpdate_time()
{
return update_time;
}
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("device_id", getDevice_id())
.append("id", getId())
.append("name", getName())
.append("things_model_value", getThings_model_value())
.append("update_time", getUpdate_time())
.toString();
}
}
package com.zhonglai.luhui.mqtt.comm.dto.thingsmodels;
import com.zhonglai.luhui.mqtt.comm.dto.iot.IotThingsModel;
import com.ruoyi.system.domain.IotThingsModel;
/**
* 物模型工厂
... ... @@ -8,5 +9,8 @@ import com.zhonglai.luhui.mqtt.comm.dto.iot.IotThingsModel;
public interface ThingsModelBase<T> {
void conversionThingsModel(IotThingsModel thingsModel);
void addValue(T t);
// @JSONField(serialize=false)
String getView();
String getSaveView();
Object getCmdView(Object value);
}
... ...
package com.zhonglai.luhui.mqtt.comm.dto.thingsmodels;
import com.zhonglai.luhui.mqtt.comm.dto.iot.IotThingsModel;
import com.ruoyi.system.domain.IotThingsModel;
import lombok.Data;
/**
... ... @@ -26,7 +26,10 @@ public abstract class ThingsModelItemBase<T> implements ThingsModelBase<T>
private Integer is_save_log;
/** 模型类别(1-属性,2-功能,3-事件) */
private Integer mode_type;
/** 模型类别(1-属性,2-功能,3-事件) */
private String config_names;
/** 物模型id */
private Integer mode_id;
public void conversionThingsModel(IotThingsModel thingsModel)
{
id = thingsModel.getIdentifier();
... ... @@ -36,5 +39,8 @@ public abstract class ThingsModelItemBase<T> implements ThingsModelBase<T>
type = thingsModel.getData_type();
is_save_log = thingsModel.getIs_save_log();
mode_type = thingsModel.getType();
config_names = thingsModel.getConfig_names();
mode_id = thingsModel.getModel_id();
}
}
... ...
package com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.specs;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.annotation.JSONField;
import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelItemBase;
import lombok.Data;
... ... @@ -16,10 +17,25 @@ public class ArrayModelOutput extends ThingsModelItemBase<JSONArray>
@Override
public String getView() {
if(null != getValue())
{
return JSONArray.toJSONString(getValue());
}
return "";
return null;
}
@Override
public String getSaveView() {
if(null == getValue())
{
return null;
}
return JSONArray.toJSONString(getValue());
}
@Override
public Object getCmdView(Object object) {
return object;
}
}
... ...
... ... @@ -16,6 +16,10 @@ public class BoolModelOutput extends ThingsModelItemBase<Boolean>
@Override
public String getView() {
if(null == getValue())
{
return null;
}
if(getValue())
{
return trueText;
... ... @@ -24,4 +28,18 @@ public class BoolModelOutput extends ThingsModelItemBase<Boolean>
}
}
@Override
public String getSaveView() {
if(null == getValue())
{
return null;
}
return getValue().toString();
}
@Override
public Object getCmdView(Object object) {
return object;
}
}
... ...
... ... @@ -20,6 +20,24 @@ public class DecimalModelOutput extends ThingsModelItemBase<BigDecimal>
@Override
public String getView() {
return getView()+unit;
if(null == getValue())
{
return null;
}
return getValue().doubleValue()+(null==unit?"":unit);
}
@Override
public String getSaveView() {
if(null == getValue())
{
return null;
}
return getValue().toString();
}
@Override
public Object getCmdView(Object object) {
return object;
}
}
... ...
... ... @@ -7,24 +7,46 @@ import lombok.Data;
import java.util.List;
@Data
public class EnumModelOutput extends ThingsModelItemBase<String>
public class EnumModelOutput extends ThingsModelItemBase<Object>
{
private List<EnumItemOutput> enumList;
@Override
public void addValue(String object) {
public void addValue(Object object) {
setValue(object);
}
@Override
public String getView() {
if(null == getValue())
{
return null;
}
if(null == enumList || enumList.size()==0)
{
return null;
}
for(EnumItemOutput enumItemOutput:enumList)
{
if(enumItemOutput.getValue().equals(getValue()))
if(enumItemOutput.getValue().equals(getValue()+""))
{
return enumItemOutput.getText();
}
}
return getValue();
return getValue()+"";
}
@Override
public String getSaveView() {
if(null == getValue())
{
return null;
}
return getValue()+"";
}
@Override
public Object getCmdView(Object object) {
return object;
}
}
... ...
... ... @@ -4,14 +4,17 @@ import com.zhonglai.luhui.mqtt.comm.dto.thingsmodels.ThingsModelItemBase;
import lombok.Data;
import java.math.BigDecimal;
import java.math.RoundingMode;
@Data
public class IntegerModelOutput extends ThingsModelItemBase<Integer>
{
private BigDecimal min;
private BigDecimal max;
private BigDecimal step;
private String unit;
private BigDecimal min; //最大值
private BigDecimal max; //最小值
private BigDecimal step; //步长
private String unit; //单位
private Integer acy; //精度
@Override
public void addValue(Integer object) {
... ... @@ -20,6 +23,30 @@ public class IntegerModelOutput extends ThingsModelItemBase<Integer>
@Override
public String getView() {
return getView()+unit;
if(null == getValue())
{
return null;
}
return getSaveView()+(null==unit?"":unit);
}
@Override
public String getSaveView() {
if(null == getValue())
{
return null;
}
BigDecimal bigDecimal = new BigDecimal(getValue().toString());
return bigDecimal.divide(new BigDecimal(acy),acy.toString().length()-1, RoundingMode.HALF_UP).toString();
}
@Override
public Object getCmdView(Object object) {
if(null == object)
{
return null;
}
BigDecimal bigDecimal = new BigDecimal(object.toString());
return bigDecimal.multiply(new BigDecimal(acy)).intValue();
}
}
... ...
... ... @@ -13,11 +13,21 @@ public class StringModelOutput extends ThingsModelItemBase<Object>
@Override
public void addValue(Object object) {
setValue(null!=getValue()?getValue()+"":null);
setValue(null!=object?object+"":null);
}
@Override
public String getView() {
return null!=getValue()?getValue()+"":null;
}
@Override
public String getSaveView() {
return getView();
}
@Override
public Object getCmdView(Object object) {
return object;
}
}
... ...
... ... @@ -4,6 +4,7 @@ import com.zhonglai.luhui.mqtt.comm.config.RedisConfig;
import com.zhonglai.luhui.mqtt.comm.config.SysParameter;
import com.zhonglai.luhui.mqtt.comm.dto.MyException;
import com.zhonglai.luhui.mqtt.comm.service.MqttCallback;
import com.zhonglai.luhui.mqtt.comm.util.StringUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
... ... @@ -19,15 +20,40 @@ public class Topic {
private String username;
private String clientid;
private String topicType;
private String redicKey;
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("/");
for(int i=1;i<config.length;i++)
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 {
... ... @@ -40,17 +66,72 @@ public class Topic {
}
}
}
public String getRedicKey()
/**
* 生成缓存关键字
* @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))
{
if(null == redicKey)
clientid = "+";
}
str = str.replace("/{{clientid}}",clientid+division);
if(StringUtils.isEmpty(payloadtype))
{
return generateRedicKey();
payloadtype = "String";
}
return redicKey;
str = str.replace("/{{payloadtype}}",payloadtype+division);
if(StringUtils.isEmpty(topicType))
{
topicType = "PUT";
}
private String generateRedicKey()
str = str.replace("/{{topicType}}",topicType+division);
if(StringUtils.isNotEmpty(messageid))
{
return RedisConfig.FIELD+roleid+":"+username+":"+clientid;
str = str.replace("/{{messageid}}",messageid);
}
return str;
}
}
... ...
package com.zhonglai.luhui.mqtt.comm.service;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.IotDevice;
import com.ruoyi.system.domain.IotTerminal;
import com.zhonglai.luhui.mqtt.comm.config.SysParameter;
import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;
import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;
import com.zhonglai.luhui.mqtt.comm.dto.iot.IotDevice;
import com.zhonglai.luhui.mqtt.comm.dto.iot.IotTerminal;
import com.zhonglai.luhui.mqtt.comm.factory.Topic;
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.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.*;
/**
* 业务数据更新服务
*/
@Service
public class BusinessDataUpdateService {
private static final Logger logger = LoggerFactory.getLogger(BusinessDataUpdateService.class);
@Autowired
private DataModeAnalysisService dataModeAnalysisService ;
@Autowired
... ... @@ -26,15 +38,24 @@ public class BusinessDataUpdateService {
@Autowired
private DeviceService deviceService ;
@Value("${server.port}")
private long port;
@Value("${server.context-path}")
private String contextPath;
@Value("${sys.isText:false}")
private Boolean isText;
/**
* 更新数据
* @param type
* @param topic
* @param data
*/
public void updataDta(Type type,Topic topic, JSONObject data)
public void updataDta(Type type,Topic topic, JSONObject data,boolean isOperLog,List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list)
{
List<LogDeviceOperation> operateHisList = new ArrayList<>();
IotDevice olddevice = deviceService.getRedicDevice(topic.getClientid());
for(String key:data.keySet())
{
Object o = data.get(key);
... ... @@ -43,59 +64,71 @@ public class BusinessDataUpdateService {
JSONObject jsData = data.getJSONObject(key);
if("0".equals(key)) //主机
{
IotDevice iotDevice = translateDevice(type,topic,jsData,operateHisList);
IotDevice iotDevice = translateDevice(type,olddevice,jsData,isOperLog,operateHisList,list);
if(isText)
{
iotDevice.setListen_service_ip("127.0.0.1"+":"+port+contextPath);
}else{
iotDevice.setListen_service_ip(SysParameter.service_ip+":"+port+contextPath);
}
logger.info("更新网关数据{}",iotDevice);
if(null== iotDevice.getStatus() || 1 == iotDevice.getStatus() || 4==iotDevice.getStatus())
{
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,topic,jsData,operateHisList);
deviceService.updataTerminal(iotTerminal);
IotTerminal iotTerminal = translateTerminal(type,key,olddevice,jsData,isOperLog,operateHisList,list);
logger.info("更新终端数据{}",iotTerminal);
iotTerminal.setData_update_time(DateUtils.getNowTimeMilly());
deviceService.updataTerminal(iotTerminal,olddevice.getDevice_life());
}
}
}
if(null != operateHisList && operateHisList.size() !=0 )
{
deviceLogService.saveOperationLog(operateHisList);
}
}
/**
* 更新网关
* @param type
* @param topic
* @param olddevice
* @param jsData
* @param operateHisList
* @return
*/
private IotDevice translateDevice(Type type,Topic topic , JSONObject jsData, List<LogDeviceOperation> operateHisList)
private IotDevice translateDevice(Type type, IotDevice olddevice , JSONObject jsData,boolean isOperLog, List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list)
{
IotDevice olddevice = deviceService.getRedicDevice(topic.getClientid());
JSONObject summaryObjec = null;
if(jsData.containsKey("summary") && null != jsData.get("summary") && jsData.get("summary") instanceof JSONObject)
{
summaryObjec = jsData.getJSONObject("summary");
//记录summary内容变更日志
operateHisList.add(deviceLogService.newLogDeviceOperation(topic.getClientid(),summaryObjec.toString(),olddevice.getSummary(),"主机本地summary状态更新",jsData.toJSONString()));
operateHisList.add(deviceLogService.newLogDeviceOperation(olddevice.getClient_id(),summaryObjec.toString(),olddevice.getSummary(),"主机本地summary状态更新",jsData.toJSONString()));
jsData.remove("summary");
}
IotDevice device = JSONObject.parseObject(JSONObject.toJSONString(jsData),IotDevice.class);
device.setClient_id(topic.getClientid());
device.setUpdate_time(DateUtils.getNowTimeMilly());
device = (IotDevice) mergerData(olddevice,device);
if(null != summaryObjec)
{
device.setSummary(summaryObjec.toString());
}
JSONObject saveJson = dataModeAnalysisService.analysisThingsModelValue( topic.getClientid(),topic.getUsername(),jsData,true,"主机本地");
SaveDataDto saveDataDto = dataModeAnalysisService.analysisThingsModelValue( olddevice.getClient_id(),olddevice.getMqtt_username(),jsData,"主机本地",isOperLog,operateHisList,list);
//更新数据
if(null != olddevice && "ADD".equals(type.name()))
if(null != olddevice && ("ADD".equals(type.name())|| "READ".equals(type.name())))
{
String str = olddevice.getThings_model_value();
String newStr = deviceService.getNewAdddate(str,saveJson).toJSONString();
String newStr = deviceService.getNewAdddate(str,saveDataDto.getData()).toJSONString();
device.setThings_model_value(newStr);
}else{
device.setThings_model_value(saveJson.toJSONString());
device.setThings_model_value(saveDataDto.getData().toJSONString());
}
//配置只做增量
String str = (null!=olddevice?olddevice.getThings_model_config():null);
String newStr = deviceService.getNewAdddate(str,saveDataDto.getConfig()).toJSONString();
device.setThings_model_config(newStr);
return device;
}
... ... @@ -104,28 +137,46 @@ public class BusinessDataUpdateService {
* 更新终端
* @param type "ADD"增量更新,"ALL"全量更新
* @param key
* @param topic
* @param olddevice
* @param jsData
* @param operateHisList
* @return
*/
private IotTerminal translateTerminal(Type type,String key, Topic topic , JSONObject jsData, List<LogDeviceOperation> operateHisList)
private IotTerminal translateTerminal(Type type,String key, IotDevice olddevice , JSONObject jsData,boolean isOperLog, List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list)
{
String id = topic.getClientid()+"_"+key;
JSONObject saveJson = dataModeAnalysisService.analysisThingsModelValue( id,topic.getUsername(),jsData,true,"终端本地");
String id = olddevice.getClient_id()+"_"+key;
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());
//更新数据
IotTerminal oldterminal = deviceService.getRedicTerminal(id);
if(null != oldterminal && "ADD".equals(type.name()))
if(null == oldterminal)
{
oldterminal = new IotTerminal();
oldterminal.setDevice_id(olddevice.getClient_id());
oldterminal.setId(id);
oldterminal.setMqtt_username(olddevice.getMqtt_username());
oldterminal.setName(olddevice.getMqtt_username()+"终端"+key);
oldterminal.setProduct_id(olddevice.getProduct_id());
deviceService.updataTerminal(oldterminal,olddevice.getDevice_life());
}
if(null != oldterminal && ("ADD".equals(type.name())|| "READ".equals(type.name())))
{
String str = oldterminal.getThings_model_value();
terminal.setThings_model_value(deviceService.getNewAdddate(str,saveJson).toJSONString());
terminal.setThings_model_value(deviceService.getNewAdddate(str,saveDataDto.getData()).toJSONString());
}else{
terminal.setThings_model_value(saveJson.toJSONString());
terminal.setThings_model_value(saveDataDto.getData().toJSONString());
}
if(key.startsWith("1_") && null != saveDataDto.getConfig())
{
System.out.println(saveDataDto);
}
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;
}
... ... @@ -133,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);
}
}
... ...
package com.zhonglai.luhui.mqtt.comm.service;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import com.zhonglai.luhui.mqtt.comm.clien.ClienConnection;
import com.zhonglai.luhui.mqtt.comm.clien.impl.ClienConnectionImpl;
import com.zhonglai.luhui.mqtt.comm.dto.ServerDto;
... ... @@ -18,6 +19,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
... ... @@ -30,14 +32,14 @@ public class ClienNoticeService {
@Autowired
private TerminalService terminalService;
@Autowired
private TopicsService topicsService;
private ExpiringMap<String, ClienConnection> clienConnectionMap;
@Value("${mqtt.client.operationTime}")
private long operationTime; //客户端操作时间
@Value("#{${mqtt.top_return_map}}")
private Map<String,String> top_return_map; //topic返回的对应关系
@PostConstruct
public void init()
{
... ... @@ -48,46 +50,45 @@ public class ClienNoticeService {
// CREATED: 只在put和replace方法清零过期时间
// ACCESSED: 在CREATED策略基础上增加, 在还没过期时get方法清零过期时间。
// 清零过期时间也就是重置过期时间,重新计算过期时间.
clienConnectionMap = ExpiringMap.builder().maxSize(2000).expiration(operationTime, TimeUnit.SECONDS)
clienConnectionMap = ExpiringMap.builder().maxSize(20000).expiration(operationTime, TimeUnit.SECONDS)
.asyncExpirationListener((ExpirationListener<String, ClienConnection>) (s, clienConnection) -> clienConnection.close())
.expirationPolicy(ExpirationPolicy.CREATED).build();
}
public Message sendMessage(String imei, MqttMessage mqttMessage, String messageid) throws MqttException, InterruptedException {
public Message sendMessage(Topic topic, MqttMessage mqttMessage) throws MqttException, InterruptedException {
//设置通知渠道
ClienConnection clienConnection = new ClienConnectionImpl();
clienConnectionMap.put(topicsService.getClienConnectionMapKey(imei,messageid),clienConnection);
log.info("{} {} {} {}",topic.generateClienKey(),topic.getTopicType(),top_return_map,clienConnection);
clienConnectionMap.put(topic.generateClienKey().replace(topic.getTopicType(),top_return_map.get(topic.getTopicType())),clienConnection);
sendMessage(imei,messageid,mqttMessage);
sendMessage(topic.generateSendMessageTopic(),mqttMessage);
synchronized(clienConnection)
{
log.info("{}等待通知",imei);
log.info("{}等待通知",topic.getClientid());
clienConnection.wait(operationTime*1000+3000l);
}
log.info("{}收到通知{}",imei,clienConnection.getReplyMessage().getMessage());
log.info("{}收到通知{}",topic.getClientid(),clienConnection.getReplyMessage().getMessage());
Message message = clienConnection.getReplyMessage();
log.info("{}返回通知{}",imei,message);
log.info("{}返回通知{}",topic.getClientid(),message);
return message;
}
/**
* 发送消息
* @param imei
* @param mqttMessage
* @throws MqttException
* @throws InterruptedException
*/
public void sendMessage(String imei,String messageid, MqttMessage mqttMessage) throws MqttException, InterruptedException {
public void sendMessage(String topic,MqttMessage mqttMessage) throws MqttException, InterruptedException {
//发生指令,等待通知
String topic = topicsService.getTopicFromImei(imei,messageid);
System.out.println("发送的消息内容"+ ByteUtil.hexStringToSpace(ByteUtil.toHexString(mqttMessage.getPayload()).toUpperCase()));
System.out.println(topic+"发送的消息内容"+ ByteUtil.hexStringToSpace(ByteUtil.toHexString(mqttMessage.getPayload()).toUpperCase())+" 转化为字符串:"+new String(mqttMessage.getPayload()));
terminalService.publish(topic,mqttMessage);
}
public ClienConnection getClienConnection(String imei, String messageid)
public ClienConnection getClienConnection(Topic topic)
{
return clienConnectionMap.get(topicsService.getClienConnectionMapKey(imei,messageid));
return clienConnectionMap.get(topic.generateClienKey());
}
public void replySendMessage(Topic topic, ServerDto dto)
... ... @@ -96,7 +97,7 @@ public class ClienNoticeService {
//判断有没有需要回复的客户端,如果有就回复
if(dto.isReplyMessage())
{
ClienConnection clienConnection = getClienConnection(topic.getClientid(),dto.getServerAgreementContent().getClienConnectionId());
ClienConnection clienConnection = getClienConnection(topic);
if(null != clienConnection)
{
synchronized(clienConnection)
... ...
... ... @@ -2,23 +2,24 @@ package com.zhonglai.luhui.mqtt.comm.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhonglai.luhui.mqtt.comm.config.RedisConfig;
import com.ruoyi.system.domain.IotThingsModel;
import com.zhonglai.luhui.mqtt.comm.dao.BaseDao;
import com.zhonglai.luhui.mqtt.comm.dto.DeviceSensorData;
import com.zhonglai.luhui.mqtt.comm.dto.LogDeviceOperation;
import com.zhonglai.luhui.mqtt.comm.dto.iot.IotThingsModel;
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.util.DateUtils;
import com.zhonglai.luhui.mqtt.comm.util.StringUtils;
import com.zhonglai.luhui.mqtt.dto.SaveDataDto;
import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService;
import org.apache.commons.lang3.EnumUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 数据模型解析服务
... ... @@ -28,52 +29,48 @@ public class DataModeAnalysisService {
private static final Logger log = LoggerFactory.getLogger(DataModeAnalysisService.class);
private BaseDao baseDao = new BaseDao();
@Autowired
private RedisService redisService ;
@Autowired
private DeviceLogService dviceLogService;
@Autowired
private TerminalDataThingsModeService terminalDataThingsModeService;
/**
* 初始化物模型数据
*/
public void initDataThingsMode()
public void initDataThingsMode(String roleIds,String usernames)
{
List<IotThingsModel> list = baseDao.findBysql("select * from `mqtt_broker`.`iot_things_model` where del_flag=0", IotThingsModel.class);
if(null != list && list.size() != 0)
{
for(IotThingsModel thingsModel:list)
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))
{
redisService.hset(RedisConfig.FIELD+RedisConfig.THINGS_MODEL+thingsModel.getUser_name(),thingsModel.getIdentifier(),thingsModel);
}
sql += " AND b.`role_id` IN("+roleIds+")";
}
}
public JSONObject analysisThingsModelValue(String id, String userName , JSONObject jsData)
if(StringUtils.isNotEmpty(usernames))
{
return analysisThingsModelValue(id,userName,jsData,false,null);
sql += " AND b.`username` IN("+usernames+")";
}
List<IotThingsModel> list = baseDao.findBysql(sql, IotThingsModel.class);
terminalDataThingsModeService.saveIotThingsModelToUser(list);
}
/**
* 解析物模型数据
*/
public JSONObject analysisThingsModelValue(String id,String userName ,JSONObject jsData,boolean isSaveLog,String controlModel)
public SaveDataDto analysisThingsModelValue(String id,String userName ,JSONObject jsData,String controlModel,boolean isOperLog, List<LogDeviceOperation> operateHisList, List<DeviceSensorData> list)
{
if(null != jsData && jsData.size() != 0 )
{
Map<Object, Object> thingsModelMap = redisService.hmget(RedisConfig.FIELD+RedisConfig.THINGS_MODEL+userName);
JSONObject rObjec = new JSONObject();
JSONObject data = new JSONObject();
List<DeviceSensorData> list = new ArrayList<>();
List<LogDeviceOperation> oplist = new ArrayList<>();
JSONObject config = new JSONObject();
for(String key:jsData.keySet())
{
Object object = thingsModelMap.get(key);
IotThingsModel thingsModel = null;
if(object instanceof IotThingsModel)
IotThingsModel thingsModel = terminalDataThingsModeService.getIotThingsModel(userName,key);
if(null == thingsModel) //没有配置的 都按字符串处理
{
thingsModel = (IotThingsModel)object;
}else{ //没有配置的 都按字符串处理
thingsModel = new IotThingsModel();
thingsModel.setData_type(ThingsModelDataTypeEnum.STRING.name());
thingsModel.setIdentifier(key);
... ... @@ -81,22 +78,29 @@ public class DataModeAnalysisService {
thingsModel.setIs_top(0);
thingsModel.setIs_monitor(0);
thingsModel.setIs_save_log(0);
thingsModel.setIs_config(0);
JSONObject jsonObject = new JSONObject();
jsonObject.put("maxLength",255);
thingsModel.setSpecs(jsonObject.toString());
}
Class<ThingsModelBase> aClass = Enum.valueOf(ThingsModelDataTypeEnum.class,thingsModel.getData_type()).getaClass();
String data_type = thingsModel.getData_type().toUpperCase();
if(!EnumUtils.isValidEnum(ThingsModelDataTypeEnum.class,data_type))
{
data_type = ThingsModelDataTypeEnum.STRING.name();
}
Class<ThingsModelBase> aClass = Enum.valueOf(ThingsModelDataTypeEnum.class,data_type).getaClass();
ThingsModelBase thingsModelBase = JSON.parseObject(thingsModel.getSpecs(),aClass);
thingsModelBase.conversionThingsModel(thingsModel);
thingsModelBase.addValue(jsData.get(key));
ThingsModelItemBase thingsModelItemBase = (ThingsModelItemBase) thingsModelBase;
//记录数据日志
if(1==thingsModelItemBase.getIs_save_log())
if(1==thingsModelItemBase.getIs_save_log() && null != list)
{
DeviceSensorData sensorData = new DeviceSensorData();
sensorData.setDataType(key);
sensorData.setDataValue(jsData.getString(key));
sensorData.setDataValue(thingsModelBase.getSaveView());
sensorData.setCreatTime(DateUtils.getNowTimeMilly());
sensorData.setDeviceModel(userName);
sensorData.setDeviceInfoId(id);
... ... @@ -104,15 +108,30 @@ public class DataModeAnalysisService {
}
//记录操作日志
oplist.add(dviceLogService.newLogDeviceOperation(id,jsData.getString(key),null,controlModel+thingsModelItemBase.getName()+"为"+thingsModelBase.getView(),jsData.toString()));
rObjec.put(key,JSONObject.toJSONString(thingsModelBase));
if(isOperLog && null != operateHisList)
{
operateHisList.add(dviceLogService.newLogDeviceOperation(id,thingsModelBase.getSaveView(),null,controlModel+thingsModelItemBase.getName()+"为"+thingsModelBase.getView(),jsData.toString()));
}
//日志入库
dviceLogService.saveDeviceSensorDataLog(list);
dviceLogService.saveOperationLog(oplist);
return rObjec;
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);
return saveDataDto;
}
return null;
}
... ...
... ... @@ -17,7 +17,6 @@ public abstract class DataPersistenceService {
protected BaseDao baseDao = new BaseDao();
public abstract void persistence(Topic topic, ServerDto serverDto);
public abstract void addDeviceSensorData(Topic topic, ServerDto serverDto);
/**
* 记录操作日志
... ...