作者 钟来

模块整理

正在显示 93 个修改的文件 包含 2421 行增加466 行删除
@@ -19,10 +19,6 @@ @@ -19,10 +19,6 @@
19 19
20 <dependencies> 20 <dependencies>
21 <dependency> 21 <dependency>
22 - <groupId>com.zhonglai.luhui</groupId>  
23 - <artifactId>ruoyi-framework</artifactId>  
24 - </dependency>  
25 - <dependency>  
26 <groupId>org.aspectj</groupId> 22 <groupId>org.aspectj</groupId>
27 <artifactId>aspectjweaver</artifactId> 23 <artifactId>aspectjweaver</artifactId>
28 </dependency> 24 </dependency>
@@ -36,5 +32,38 @@ @@ -36,5 +32,38 @@
36 <artifactId>lh-jar-device-service</artifactId> 32 <artifactId>lh-jar-device-service</artifactId>
37 <scope>compile</scope> 33 <scope>compile</scope>
38 </dependency> 34 </dependency>
  35 +
  36 + <!-- mqtt -->
  37 + <dependency>
  38 + <groupId>org.eclipse.paho</groupId>
  39 + <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
  40 + </dependency>
  41 +
  42 + <dependency>
  43 + <groupId>net.jodah</groupId>
  44 + <artifactId>expiringmap</artifactId>
  45 + </dependency>
  46 +
  47 + <!-- 数据库 -->
  48 + <dependency>
  49 + <groupId>commons-dbcp</groupId>
  50 + <artifactId>commons-dbcp</artifactId>
  51 + <version>1.4</version>
  52 + </dependency>
  53 + <dependency>
  54 + <groupId>commons-dbutils</groupId>
  55 + <artifactId>commons-dbutils</artifactId>
  56 + <version>1.6</version>
  57 + </dependency>
  58 + <dependency>
  59 + <groupId>commons-pool</groupId>
  60 + <artifactId>commons-pool</artifactId>
  61 + <version>1.6</version>
  62 + </dependency>
  63 + <dependency>
  64 + <groupId>mysql</groupId>
  65 + <artifactId>mysql-connector-java</artifactId>
  66 + <version>8.0.17</version>
  67 + </dependency>
39 </dependencies> 68 </dependencies>
40 </project> 69 </project>
1 -package com.zhonglai.luhui.mqtt.comm.config; 1 +package com.zhonglai.luhui.device.analysis.comm.config;
2 2
3 import org.springframework.context.annotation.Bean; 3 import org.springframework.context.annotation.Bean;
4 import org.springframework.context.annotation.Configuration; 4 import org.springframework.context.annotation.Configuration;
1 -package com.zhonglai.luhui.mqtt.comm.config; 1 +package com.zhonglai.luhui.device.analysis.comm.config;
2 2
3 import com.alibaba.fastjson.JSON; 3 import com.alibaba.fastjson.JSON;
4 import com.alibaba.fastjson.serializer.SerializerFeature; 4 import com.alibaba.fastjson.serializer.SerializerFeature;
1 -package com.zhonglai.luhui.mqtt.comm.config; 1 +package com.zhonglai.luhui.device.analysis.comm.config;
2 2
3 import com.alibaba.fastjson.parser.ParserConfig; 3 import com.alibaba.fastjson.parser.ParserConfig;
4 import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 import com.fasterxml.jackson.annotation.JsonAutoDetect;
1 -package com.zhonglai.luhui.mqtt.comm.config; 1 +package com.zhonglai.luhui.device.analysis.comm.config;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 import com.zhonglai.luhui.device.analysis.comm.util.http.HttpUtils; 4 import com.zhonglai.luhui.device.analysis.comm.util.http.HttpUtils;
1 -package com.zhonglai.luhui.mqtt.comm.dao; 1 +package com.zhonglai.luhui.device.analysis.comm.dao;
2 2
3 import com.alibaba.fastjson.JSONArray; 3 import com.alibaba.fastjson.JSONArray;
4 import com.ruoyi.common.annotation.PublicSQLConfig; 4 import com.ruoyi.common.annotation.PublicSQLConfig;
@@ -4,7 +4,7 @@ @@ -4,7 +4,7 @@
4 * @author yushigui 4 * @author yushigui
5 * @date 2014-1-19 5 * @date 2014-1-19
6 */ 6 */
7 -package com.zhonglai.luhui.mqtt.comm.dao; 7 +package com.zhonglai.luhui.device.analysis.comm.dao;
8 8
9 import javax.sql.DataSource; 9 import javax.sql.DataSource;
10 10
@@ -4,7 +4,7 @@ @@ -4,7 +4,7 @@
4 * @author yushigui 4 * @author yushigui
5 * @date 2014-1-19 5 * @date 2014-1-19
6 */ 6 */
7 -package com.zhonglai.luhui.mqtt.comm.dao; 7 +package com.zhonglai.luhui.device.analysis.comm.dao;
8 8
9 import org.apache.commons.dbcp.BasicDataSourceFactory; 9 import org.apache.commons.dbcp.BasicDataSourceFactory;
10 10
1 -package com.zhonglai.luhui.mqtt.service.db; 1 +package com.zhonglai.luhui.device.analysis.comm.db;
2 2
3 import com.alibaba.fastjson.JSON; 3 import com.alibaba.fastjson.JSON;
4 import com.alibaba.fastjson.JSONArray; 4 import com.alibaba.fastjson.JSONArray;
5 import com.alibaba.fastjson.JSONObject; 5 import com.alibaba.fastjson.JSONObject;
  6 +import com.zhonglai.luhui.device.analysis.comm.db.mode.TerminalDataThingsModeService;
  7 +import com.zhonglai.luhui.device.analysis.comm.service.CacheServiceImpl;
  8 +import com.zhonglai.luhui.device.analysis.comm.service.DataPersistenceServiceImpl;
6 import com.zhonglai.luhui.device.domain.IotDevice; 9 import com.zhonglai.luhui.device.domain.IotDevice;
7 import com.zhonglai.luhui.device.domain.IotTerminal; 10 import com.zhonglai.luhui.device.domain.IotTerminal;
8 import com.zhonglai.luhui.device.domain.IotThingsModel; 11 import com.zhonglai.luhui.device.domain.IotThingsModel;
9 -import com.zhonglai.luhui.mqtt.comm.dao.BaseDao; 12 +import com.zhonglai.luhui.device.analysis.comm.dao.BaseDao;
10 import com.zhonglai.luhui.device.analysis.comm.dto.LogDeviceOperation; 13 import com.zhonglai.luhui.device.analysis.comm.dto.LogDeviceOperation;
11 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelBase; 14 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelBase;
12 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelDataTypeEnum; 15 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelDataTypeEnum;
13 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelItemBase; 16 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelItemBase;
14 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 17 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
15 -import com.zhonglai.luhui.mqtt.comm.service.BusinessDataUpdateService;  
16 -import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService;  
17 -import com.zhonglai.luhui.mqtt.comm.service.DeviceLogService;  
18 -import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService; 18 +import com.zhonglai.luhui.device.analysis.comm.service.BusinessDataUpdateService;
  19 +import com.zhonglai.luhui.device.analysis.comm.service.DeviceLogService;
  20 +import com.zhonglai.luhui.device.analysis.comm.service.redis.RedisService;
19 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils; 21 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils;
20 import com.zhonglai.luhui.device.analysis.dto.Message; 22 import com.zhonglai.luhui.device.analysis.dto.Message;
21 import com.zhonglai.luhui.device.analysis.dto.MessageCode; 23 import com.zhonglai.luhui.device.analysis.dto.MessageCode;
22 import com.zhonglai.luhui.device.analysis.dto.topic.AddPostDto; 24 import com.zhonglai.luhui.device.analysis.dto.topic.AddPostDto;
23 -import com.zhonglai.luhui.mqtt.service.CacheServiceImpl;  
24 -import com.zhonglai.luhui.mqtt.service.DataPersistenceServiceImpl;  
25 -import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService;  
26 import org.apache.commons.lang3.StringUtils; 25 import org.apache.commons.lang3.StringUtils;
27 import org.eclipse.paho.client.mqttv3.MqttException; 26 import org.eclipse.paho.client.mqttv3.MqttException;
28 import org.eclipse.paho.client.mqttv3.MqttMessage; 27 import org.eclipse.paho.client.mqttv3.MqttMessage;
@@ -37,11 +36,6 @@ import java.util.*; @@ -37,11 +36,6 @@ import java.util.*;
37 public class DeviceService { 36 public class DeviceService {
38 private static final Logger log = LoggerFactory.getLogger(DeviceService.class); 37 private static final Logger log = LoggerFactory.getLogger(DeviceService.class);
39 38
40 - @Autowired  
41 - private ClienNoticeService clienNoticeService;  
42 -  
43 - @Autowired  
44 - private TerminalDataThingsModeService terminalDataThingsModeService;  
45 39
46 @Autowired 40 @Autowired
47 private CacheServiceImpl cacheServiceImpl; 41 private CacheServiceImpl cacheServiceImpl;
@@ -53,11 +47,6 @@ public class DeviceService { @@ -53,11 +47,6 @@ public class DeviceService {
53 private DeviceLogService dviceLogService; 47 private DeviceLogService dviceLogService;
54 48
55 private BaseDao baseDao = new BaseDao(); 49 private BaseDao baseDao = new BaseDao();
56 - @Autowired  
57 - private DataPersistenceServiceImpl dataPersistenceService;  
58 -  
59 - @Autowired  
60 - private BusinessDataUpdateService businessDataUpdateService ;  
61 50
62 /** 51 /**
63 * 根据id获取终端 52 * 根据id获取终端
@@ -148,73 +137,8 @@ public class DeviceService { @@ -148,73 +137,8 @@ public class DeviceService {
148 cacheServiceImpl.deletRedisTerminal(terminalIds); 137 cacheServiceImpl.deletRedisTerminal(terminalIds);
149 } 138 }
150 139
151 - /**  
152 - * 控制发16进制指令  
153 - * @param clienid  
154 - * @param data  
155 - * @return  
156 - * @throws MqttException  
157 - * @throws InterruptedException  
158 - */  
159 - public Message controlHex(String clienid, String data) throws MqttException, InterruptedException {  
160 -  
161 - Topic topic = getTopicFromDb(clienid);  
162 - if(null == topic)  
163 - {  
164 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");  
165 - }  
166 - topic.setTopicType("PUT");  
167 - topic.setMessageid(DateUtils.getNowTimeMilly()+"");  
168 -  
169 - MqttMessage mqttMessage = new MqttMessage();  
170 - byte[] bs = hexStringToByte(data.trim().toUpperCase());  
171 - mqttMessage.setPayload(bs);  
172 -  
173 - Message message = clienNoticeService.sendMessage(topic,mqttMessage);  
174 - if(1==message.getCode())  
175 - {  
176 - List<LogDeviceOperation> list = new ArrayList<>();  
177 - list.add(dviceLogService.newLogDeviceOperation(clienid,null!=message.getData()?JSON.toJSONString(message.getData()):null,null,"远程操作控制设备","controlHex?"+data));  
178 - dviceLogService.saveOperationLog(list);  
179 - }  
180 - return message;  
181 - }  
182 -  
183 - /**  
184 - * 读  
185 - * @param clienid  
186 - * @param map  
187 - * @return  
188 - * @throws MqttException  
189 - * @throws InterruptedException  
190 - */  
191 - public Message read(String clienid,Map<String,Object> map) throws MqttException, InterruptedException {  
192 - log.info("api请求读取 {} 参数 {}",map);  
193 - if(null == map || map.size() ==0)  
194 - {  
195 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"参数验证失败");  
196 - }  
197 -  
198 - Topic topic = getTopicFromDb(clienid);  
199 - if(null == topic)  
200 - {  
201 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");  
202 - }  
203 - topic.setTopicType("READ");  
204 - topic.setMessageid(DateUtils.getNowTimeMilly()+"");  
205 - MqttMessage mqttMessage = new MqttMessage();  
206 - mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());  
207 - Message message = clienNoticeService.sendMessage(topic,mqttMessage);  
208 140
209 - if(1==message.getCode())  
210 - {  
211 - List<LogDeviceOperation> list = new ArrayList<>();  
212 - list.add(dviceLogService.newLogDeviceOperation(clienid,JSON.toJSONString(message.getData()),null,"远程操作读取配置参数","read?"+JSON.toJSONString(map).trim()));  
213 - dviceLogService.saveOperationLog(list);  
214 - }  
215 141
216 - return message;  
217 - }  
218 142
219 /** 143 /**
220 * 更新主机 144 * 更新主机
@@ -252,25 +176,7 @@ public class DeviceService { @@ -252,25 +176,7 @@ public class DeviceService {
252 return new Message(MessageCode.DEFAULT_SUCCESS_CODE); 176 return new Message(MessageCode.DEFAULT_SUCCESS_CODE);
253 } 177 }
254 178
255 - /**  
256 - * 强行断开链接  
257 - * @param clienid  
258 - * @return  
259 - * @throws MqttException  
260 - * @throws InterruptedException  
261 - */  
262 - public Message closeSession(String clienid) throws MqttException, InterruptedException {  
263 -  
264 - MqttMessage mqttMessage = new MqttMessage();  
265 - byte[] bs = hexStringToByte(clienid.trim().toUpperCase());  
266 - mqttMessage.setPayload(bs);  
267 179
268 - clienNoticeService.sendMessage("CLOSE",mqttMessage);  
269 - List<LogDeviceOperation> list = new ArrayList<>();  
270 - list.add(dviceLogService.newLogDeviceOperation(clienid,null,null,"远程操作强行断开链接","closeSession?"));  
271 - dviceLogService.saveOperationLog(list);  
272 - return new Message(MessageCode.DEFAULT_SUCCESS_CODE,"端口请求已发送");  
273 - }  
274 180
275 /** 181 /**
276 * 删除主机 182 * 删除主机
@@ -280,7 +186,6 @@ public class DeviceService { @@ -280,7 +186,6 @@ public class DeviceService {
280 * @throws InterruptedException 186 * @throws InterruptedException
281 */ 187 */
282 public Message delIotDevice(String client_id) throws MqttException, InterruptedException { 188 public Message delIotDevice(String client_id) throws MqttException, InterruptedException {
283 - closeSession(client_id); //强制下线  
284 cacheServiceImpl.deletRedisDevice(client_id); 189 cacheServiceImpl.deletRedisDevice(client_id);
285 baseDao.updateBySql("delete from iot_device where client_id='"+client_id+"'"); 190 baseDao.updateBySql("delete from iot_device where client_id='"+client_id+"'");
286 baseDao.updateBySql("delete from iot_terminal where device_id='"+client_id+"'"); 191 baseDao.updateBySql("delete from iot_terminal where device_id='"+client_id+"'");
@@ -301,7 +206,6 @@ public class DeviceService { @@ -301,7 +206,6 @@ public class DeviceService {
301 * @throws InterruptedException 206 * @throws InterruptedException
302 */ 207 */
303 public Message delIotTerminal(String client_id,String number) throws MqttException, InterruptedException { 208 public Message delIotTerminal(String client_id,String number) throws MqttException, InterruptedException {
304 - closeSession(client_id); //强制下线  
305 cacheServiceImpl.deletRedisTerminal(client_id+"_"+number); 209 cacheServiceImpl.deletRedisTerminal(client_id+"_"+number);
306 baseDao.updateBySql("delete from iot_terminal where id='"+client_id+"_"+number+"'"); 210 baseDao.updateBySql("delete from iot_terminal where id='"+client_id+"_"+number+"'");
307 baseDao.updateBySql("DELETE FROM `user_terminal_group_relation` WHERE iot_terminal_id = '"+client_id+"_"+number+"'"); 211 baseDao.updateBySql("DELETE FROM `user_terminal_group_relation` WHERE iot_terminal_id = '"+client_id+"_"+number+"'");
@@ -313,91 +217,6 @@ public class DeviceService { @@ -313,91 +217,6 @@ public class DeviceService {
313 } 217 }
314 218
315 /** 219 /**
316 - * 控制发json  
317 - * @param clienid  
318 - * @param map  
319 - * @return  
320 - * @throws MqttException  
321 - * @throws InterruptedException  
322 - */  
323 - public Message control(String clienid,Map<String,Object> map) throws MqttException, InterruptedException {  
324 -  
325 - if(null == map || map.size() ==0)  
326 - {  
327 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"参数验证失败");  
328 - }  
329 -  
330 - Topic topic = getTopicFromDb(clienid);  
331 - if(null == topic)  
332 - {  
333 - return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");  
334 - }  
335 - topic.setTopicType("PUT");  
336 - topic.setMessageid(DateUtils.getNowTimeMilly()+"");  
337 -  
338 - StringBuffer stringBuffer = new StringBuffer("");  
339 - List<LogDeviceOperation> logDeviceOperationList = new ArrayList<>();  
340 - for(String key:map.keySet())  
341 - {  
342 - Object sendMap = map.get(key);  
343 - JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(sendMap));  
344 - for(String skey:jsonObject.keySet())  
345 - {  
346 - IotThingsModel thingsModel = terminalDataThingsModeService.getIotThingsModel(topic.getUsername(),skey);  
347 - if(null == thingsModel) //没有配置的 都按字符串处理  
348 - {  
349 - thingsModel = new IotThingsModel();  
350 - thingsModel.setData_type(ThingsModelDataTypeEnum.STRING.name());  
351 - thingsModel.setIdentifier(key);  
352 - thingsModel.setModel_name(key);  
353 - thingsModel.setIs_top(0);  
354 - thingsModel.setIs_monitor(0);  
355 - thingsModel.setIs_save_log(0);  
356 - thingsModel.setIs_config(0);  
357 - JSONObject spes = new JSONObject();  
358 - spes.put("maxLength",255);  
359 - thingsModel.setSpecs(spes.toString());  
360 - }  
361 - String data_type = thingsModel.getData_type().toUpperCase();  
362 - Class<ThingsModelBase> aClass = Enum.valueOf(ThingsModelDataTypeEnum.class,data_type).getaClass();  
363 - ThingsModelBase thingsModelBase = JSON.parseObject(thingsModel.getSpecs(),aClass);  
364 - thingsModelBase.conversionThingsModel(thingsModel);  
365 - Object object = jsonObject.get(skey);  
366 -// Type clas = ((ParameterizedType)aClass.getGenericSuperclass()).getActualTypeArguments()[0];  
367 -// if(null != object && object.getClass()!=clas)  
368 -// {  
369 -// return new Message(MessageCode.DEFAULT_FAIL_CODE,skey+" 参数数据类型和模型数据类型("+clas+")不一致");  
370 -// }  
371 - ThingsModelItemBase thingsModelItemBase = (ThingsModelItemBase) thingsModelBase;  
372 - jsonObject.put(skey,thingsModelItemBase.getCmdView(object));  
373 - thingsModelBase.addValue(thingsModelItemBase.getCmdView(object));  
374 - String id = clienid+"_"+key;  
375 - logDeviceOperationList.add(dviceLogService.newLogDeviceOperation(id,thingsModelItemBase.getSaveView(),null,"远程控制"+thingsModelItemBase.getName()+"为"+thingsModelItemBase.getView(),null));  
376 - }  
377 -  
378 - map.put(key,jsonObject);  
379 -  
380 - }  
381 - MqttMessage mqttMessage = new MqttMessage();  
382 - mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());  
383 - Message message = clienNoticeService.sendMessage(topic,mqttMessage);  
384 - if(1==message.getCode())  
385 - {  
386 - topic.setClientid(clienid);  
387 - AddPostDto addPostDto = new AddPostDto();  
388 - addPostDto.setData(JSON.parseObject(JSON.toJSONString(map)));  
389 - addPostDto.setIotTerminalList(new ArrayList<>());  
390 - addPostDto.setDeviceSensorDataList(new ArrayList<>());  
391 - addPostDto.setLogDeviceOperationList(new ArrayList<>());  
392 - businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ADD,topic,addPostDto,"远程控制",true);  
393 - cacheServiceImpl.updateCache(topic,addPostDto);  
394 - addPostDto.setLogDeviceOperationList(logDeviceOperationList);  
395 - dataPersistenceService.persistence(topic,addPostDto);  
396 - }  
397 - return message;  
398 - }  
399 -  
400 - /**  
401 * 获取指定设备版本信息 220 * 获取指定设备版本信息
402 * @param app_type 221 * @param app_type
403 * @return 222 * @return
@@ -413,7 +232,7 @@ public class DeviceService { @@ -413,7 +232,7 @@ public class DeviceService {
413 * @param clienid 232 * @param clienid
414 * @return 233 * @return
415 */ 234 */
416 - private Topic getTopicFromDb(String clienid) 235 + public Topic getTopicFromDb(String clienid)
417 { 236 {
418 JSONArray jsonArray = baseDao.findBysql("SELECT b.`role_id` roleid,b.`mqtt_username` username,a.`client_id` clientid,a.`payload_type` payloadtype FROM `iot_device` a LEFT JOIN `iot_product` b ON a.`product_id`=b.`id` WHERE client_id='"+clienid+"'"); 237 JSONArray jsonArray = baseDao.findBysql("SELECT b.`role_id` roleid,b.`mqtt_username` username,a.`client_id` clientid,a.`payload_type` payloadtype FROM `iot_device` a LEFT JOIN `iot_product` b ON a.`product_id`=b.`id` WHERE client_id='"+clienid+"'");
419 if(null == jsonArray || jsonArray.size()==0 || null == jsonArray.getJSONObject(0).get("username")) 238 if(null == jsonArray || jsonArray.size()==0 || null == jsonArray.getJSONObject(0).get("username"))
@@ -510,7 +329,7 @@ public class DeviceService { @@ -510,7 +329,7 @@ public class DeviceService {
510 * @param hex 329 * @param hex
511 * @return 330 * @return
512 */ 331 */
513 - private byte[] hexStringToByte(String hex) { 332 + public byte[] hexStringToByte(String hex) {
514 int len = (hex.length() / 2); 333 int len = (hex.length() / 2);
515 byte[] result = new byte[len]; 334 byte[] result = new byte[len];
516 char[] achar = hex.toCharArray(); 335 char[] achar = hex.toCharArray();
1 -package com.zhonglai.luhui.mqtt.service.db.mode; 1 +package com.zhonglai.luhui.device.analysis.comm.db.mode;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 import com.zhonglai.luhui.device.domain.IotThingsModel; 4 import com.zhonglai.luhui.device.domain.IotThingsModel;
5 -import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService; 5 +import com.zhonglai.luhui.device.analysis.comm.service.redis.RedisService;
6 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.stereotype.Service; 7 import org.springframework.stereotype.Service;
8 8
1 -package com.zhonglai.luhui.mqtt.service.redis; 1 +package com.zhonglai.luhui.device.analysis.comm.redis;
2 2
3 import org.slf4j.Logger; 3 import org.slf4j.Logger;
4 import org.slf4j.LoggerFactory; 4 import org.slf4j.LoggerFactory;
1 -package com.zhonglai.luhui.mqtt.service.redis; 1 +package com.zhonglai.luhui.device.analysis.comm.redis;
2 2
3 import org.slf4j.Logger; 3 import org.slf4j.Logger;
4 import org.slf4j.LoggerFactory; 4 import org.slf4j.LoggerFactory;
1 -package com.zhonglai.luhui.mqtt.comm.service; 1 +package com.zhonglai.luhui.device.analysis.comm.service;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
  4 +import com.zhonglai.luhui.device.analysis.comm.config.SysParameter;
  5 +import com.zhonglai.luhui.device.analysis.comm.db.DeviceService;
4 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; 6 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
5 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils; 7 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils;
6 import com.zhonglai.luhui.device.analysis.dto.SaveDataDto; 8 import com.zhonglai.luhui.device.analysis.dto.SaveDataDto;
@@ -9,9 +11,6 @@ import com.zhonglai.luhui.device.analysis.dto.topic.AllPostDto; @@ -9,9 +11,6 @@ import com.zhonglai.luhui.device.analysis.dto.topic.AllPostDto;
9 import com.zhonglai.luhui.device.domain.IotDevice; 11 import com.zhonglai.luhui.device.domain.IotDevice;
10 import com.zhonglai.luhui.device.domain.IotTerminal; 12 import com.zhonglai.luhui.device.domain.IotTerminal;
11 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 13 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
12 -import com.zhonglai.luhui.mqtt.comm.config.SysParameter;  
13 -import com.zhonglai.luhui.mqtt.service.CacheServiceImpl;  
14 -import com.zhonglai.luhui.mqtt.service.db.DeviceService;  
15 import org.slf4j.Logger; 14 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory; 15 import org.slf4j.LoggerFactory;
17 import org.springframework.beans.BeanUtils; 16 import org.springframework.beans.BeanUtils;
1 -package com.zhonglai.luhui.mqtt.comm.service; 1 +package com.zhonglai.luhui.device.analysis.comm.service;
2 2
3 3
4 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; 4 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
1 -package com.zhonglai.luhui.mqtt.service; 1 +package com.zhonglai.luhui.device.analysis.comm.service;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 import com.zhonglai.luhui.device.domain.IotDevice; 4 import com.zhonglai.luhui.device.domain.IotDevice;
5 import com.zhonglai.luhui.device.domain.IotTerminal; 5 import com.zhonglai.luhui.device.domain.IotTerminal;
6 -import com.zhonglai.luhui.mqtt.comm.config.RedisConfig;  
7 -import com.zhonglai.luhui.mqtt.comm.dao.BaseDao; 6 +import com.zhonglai.luhui.device.analysis.comm.config.RedisConfig;
  7 +import com.zhonglai.luhui.device.analysis.comm.dao.BaseDao;
8 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; 8 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
9 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 9 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
10 -import com.zhonglai.luhui.mqtt.comm.service.CacheService;  
11 -import com.zhonglai.luhui.mqtt.comm.service.redis.RedisService; 10 +import com.zhonglai.luhui.device.analysis.comm.service.redis.RedisService;
12 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils; 11 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils;
13 -import com.zhonglai.luhui.mqtt.service.redis.RedisDeleteListener;  
14 -import com.zhonglai.luhui.mqtt.service.redis.RedisExpiredListener; 12 +import com.zhonglai.luhui.device.analysis.comm.redis.RedisDeleteListener;
  13 +import com.zhonglai.luhui.device.analysis.comm.redis.RedisExpiredListener;
15 import org.slf4j.Logger; 14 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory; 15 import org.slf4j.LoggerFactory;
17 import org.springframework.beans.factory.annotation.Autowired; 16 import org.springframework.beans.factory.annotation.Autowired;
1 -package com.zhonglai.luhui.mqtt.comm.service; 1 +package com.zhonglai.luhui.device.analysis.comm.service;
2 2
3 import com.alibaba.fastjson.JSON; 3 import com.alibaba.fastjson.JSON;
4 import com.alibaba.fastjson.JSONObject; 4 import com.alibaba.fastjson.JSONObject;
  5 +import com.zhonglai.luhui.device.analysis.comm.dao.BaseDao;
  6 +import com.zhonglai.luhui.device.analysis.comm.db.mode.TerminalDataThingsModeService;
5 import com.zhonglai.luhui.device.analysis.comm.dto.DeviceSensorData; 7 import com.zhonglai.luhui.device.analysis.comm.dto.DeviceSensorData;
6 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; 8 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
7 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelBase; 9 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelBase;
@@ -11,8 +13,6 @@ import com.zhonglai.luhui.device.analysis.comm.util.DateUtils; @@ -11,8 +13,6 @@ import com.zhonglai.luhui.device.analysis.comm.util.DateUtils;
11 import com.zhonglai.luhui.device.analysis.comm.util.StringUtils; 13 import com.zhonglai.luhui.device.analysis.comm.util.StringUtils;
12 import com.zhonglai.luhui.device.analysis.dto.SaveDataDto; 14 import com.zhonglai.luhui.device.analysis.dto.SaveDataDto;
13 import com.zhonglai.luhui.device.domain.IotThingsModel; 15 import com.zhonglai.luhui.device.domain.IotThingsModel;
14 -import com.zhonglai.luhui.mqtt.comm.dao.BaseDao;  
15 -import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService;  
16 import org.apache.commons.lang3.EnumUtils; 16 import org.apache.commons.lang3.EnumUtils;
17 import org.slf4j.Logger; 17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory; 18 import org.slf4j.LoggerFactory;
1 -package com.zhonglai.luhui.mqtt.comm.service; 1 +package com.zhonglai.luhui.device.analysis.comm.service;
2 2
  3 +import com.zhonglai.luhui.device.analysis.comm.dao.BaseDao;
3 import com.zhonglai.luhui.device.analysis.comm.dto.DeviceAlarmInfo; 4 import com.zhonglai.luhui.device.analysis.comm.dto.DeviceAlarmInfo;
4 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; 5 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
5 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils; 6 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils;
6 import com.zhonglai.luhui.device.analysis.comm.util.TableUtil; 7 import com.zhonglai.luhui.device.analysis.comm.util.TableUtil;
7 -import com.zhonglai.luhui.mqtt.comm.dao.BaseDao;  
8 -import com.zhonglai.luhui.mqtt.comm.dto.*;  
9 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 8 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
10 9
11 import java.util.ArrayList; 10 import java.util.ArrayList;
1 -package com.zhonglai.luhui.mqtt.service; 1 +package com.zhonglai.luhui.device.analysis.comm.service;
2 2
3 import com.zhonglai.luhui.device.domain.IotDevice; 3 import com.zhonglai.luhui.device.domain.IotDevice;
4 import com.zhonglai.luhui.device.domain.IotTerminal; 4 import com.zhonglai.luhui.device.domain.IotTerminal;
@@ -6,8 +6,6 @@ import com.zhonglai.luhui.device.analysis.comm.dto.DeviceSensorData; @@ -6,8 +6,6 @@ import com.zhonglai.luhui.device.analysis.comm.dto.DeviceSensorData;
6 import com.zhonglai.luhui.device.analysis.comm.dto.LogDeviceOperation; 6 import com.zhonglai.luhui.device.analysis.comm.dto.LogDeviceOperation;
7 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; 7 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
8 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 8 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
9 -import com.zhonglai.luhui.mqtt.comm.service.DataPersistenceService;  
10 -import com.zhonglai.luhui.mqtt.comm.service.DeviceLogService;  
11 import org.slf4j.Logger; 9 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory; 10 import org.slf4j.LoggerFactory;
13 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.beans.factory.annotation.Autowired;
1 -package com.zhonglai.luhui.mqtt.comm.service; 1 +package com.zhonglai.luhui.device.analysis.comm.service;
2 2
  3 +import com.zhonglai.luhui.device.analysis.comm.dao.BaseDao;
3 import com.zhonglai.luhui.device.analysis.comm.dto.DeviceSensorData; 4 import com.zhonglai.luhui.device.analysis.comm.dto.DeviceSensorData;
4 import com.zhonglai.luhui.device.analysis.comm.dto.LogDeviceOperation; 5 import com.zhonglai.luhui.device.analysis.comm.dto.LogDeviceOperation;
5 import com.zhonglai.luhui.device.analysis.comm.dto.TableGenerateSqlEnum; 6 import com.zhonglai.luhui.device.analysis.comm.dto.TableGenerateSqlEnum;
6 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils; 7 import com.zhonglai.luhui.device.analysis.comm.util.DateUtils;
7 -import com.zhonglai.luhui.mqtt.comm.dao.BaseDao;  
8 import org.springframework.stereotype.Service; 8 import org.springframework.stereotype.Service;
9 9
10 import java.util.List; 10 import java.util.List;
1 -package com.zhonglai.luhui.mqtt.comm.service; 1 +package com.zhonglai.luhui.device.analysis.comm.service;
2 2
3 -import com.zhonglai.luhui.mqtt.service.db.DeviceService;  
4 import org.springframework.beans.factory.annotation.Autowired; 3 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.data.redis.connection.Message; 4 import org.springframework.data.redis.connection.Message;
6 import org.springframework.data.redis.listener.KeyExpirationEventMessageListener; 5 import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
@@ -15,8 +14,6 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene @@ -15,8 +14,6 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
15 @Autowired 14 @Autowired
16 private DataPersistenceService dtaPersistenceService; 15 private DataPersistenceService dtaPersistenceService;
17 16
18 - @Autowired  
19 - private DeviceService deviceService ;  
20 17
21 public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) { 18 public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
22 super(listenerContainer); 19 super(listenerContainer);
1 -package com.zhonglai.luhui.mqtt.comm.service.redis; 1 +package com.zhonglai.luhui.device.analysis.comm.service.redis;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 import org.slf4j.Logger; 4 import org.slf4j.Logger;
@@ -8,6 +8,7 @@ import com.alibaba.fastjson.JSONObject; @@ -8,6 +8,7 @@ import com.alibaba.fastjson.JSONObject;
8 import com.ruoyi.common.core.domain.Message; 8 import com.ruoyi.common.core.domain.Message;
9 import com.ruoyi.common.exception.ServiceException; 9 import com.ruoyi.common.exception.ServiceException;
10 import com.ruoyi.common.utils.DateUtils; 10 import com.ruoyi.common.utils.DateUtils;
  11 +import com.ruoyi.common.utils.spring.SpringUtils;
11 import com.zhonglai.luhui.device.domain.IotProduct; 12 import com.zhonglai.luhui.device.domain.IotProduct;
12 import com.ruoyi.common.core.domain.ApiName; 13 import com.ruoyi.common.core.domain.ApiName;
13 import com.ruoyi.common.core.domain.DeviceCommandApi; 14 import com.ruoyi.common.core.domain.DeviceCommandApi;
@@ -33,8 +34,7 @@ public class IotDeviceServiceImpl implements IIotDeviceService @@ -33,8 +34,7 @@ public class IotDeviceServiceImpl implements IIotDeviceService
33 private IotDeviceMapper iotDeviceMapper; 34 private IotDeviceMapper iotDeviceMapper;
34 @Autowired 35 @Autowired
35 private IIotProductService iIotProductService; 36 private IIotProductService iIotProductService;
36 - @Autowired  
37 - protected RocketMqService rocketMqService; 37 +
38 /** 38 /**
39 * 查询null 39 * 查询null
40 * 40 *
@@ -99,7 +99,7 @@ public class IotDeviceServiceImpl implements IIotDeviceService @@ -99,7 +99,7 @@ public class IotDeviceServiceImpl implements IIotDeviceService
99 Map<String,Object> map = JSONObject.parseObject(JSONObject.toJSONString(iotDevice), HashMap.class); 99 Map<String,Object> map = JSONObject.parseObject(JSONObject.toJSONString(iotDevice), HashMap.class);
100 deviceCommandApiParameter.setMap(map); 100 deviceCommandApiParameter.setMap(map);
101 deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter); 101 deviceCommandApi.setDeviceCommandApiParameter(deviceCommandApiParameter);
102 - Message clJs = rocketMqService.send(deviceCommandApi); 102 + Message clJs = SpringUtils.getBean(RocketMqService.class).send(deviceCommandApi);
103 if(clJs.getCode()==1) 103 if(clJs.getCode()==1)
104 { 104 {
105 return 1; 105 return 1;
@@ -43,23 +43,23 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -43,23 +43,23 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
43 <result property="latitude" column="latitude" /> 43 <result property="latitude" column="latitude" />
44 <result property="location_way" column="location_way" /> 44 <result property="location_way" column="location_way" />
45 <result property="longitude" column="longitude" /> 45 <result property="longitude" column="longitude" />
46 - <result property="name" column="name" /> 46 + <result property="name" column="d_name" />
47 <result property="network_address" column="network_address" /> 47 <result property="network_address" column="network_address" />
48 <result property="network_ip" column="network_ip" /> 48 <result property="network_ip" column="network_ip" />
49 <result property="remark" column="remark" /> 49 <result property="remark" column="remark" />
50 <result property="rssi" column="rssi" /> 50 <result property="rssi" column="rssi" />
51 <result property="status" column="status" /> 51 <result property="status" column="status" />
52 <result property="summary" column="summary" /> 52 <result property="summary" column="summary" />
53 - <result property="things_model_value" column="things_model_value" /> 53 + <result property="things_model_value" column="d_things_model_value" />
54 <result property="update_by" column="update_by" /> 54 <result property="update_by" column="update_by" />
55 <result property="update_time" column="update_time" /> 55 <result property="update_time" column="update_time" />
56 <result property="product_id" column="product_id" /> 56 <result property="product_id" column="product_id" />
57 <result property="mqtt_username" column="mqtt_username" /> 57 <result property="mqtt_username" column="mqtt_username" />
58 <result property="payload_type" column="payload_type" /> 58 <result property="payload_type" column="payload_type" />
59 - <result property="things_model_config" column="things_model_config" /> 59 + <result property="things_model_config" column="d_things_model_config" />
60 <result property="listen_service_ip" column="listen_service_ip" /> 60 <result property="listen_service_ip" column="listen_service_ip" />
61 <result property="device_life" column="device_life" /> 61 <result property="device_life" column="device_life" />
62 - <result property="data_update_time" column="data_update_time" /> 62 + <result property="data_update_time" column="d_data_update_time" />
63 63
64 </resultMap> 64 </resultMap>
65 65
@@ -86,7 +86,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @@ -86,7 +86,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
86 </select> 86 </select>
87 87
88 <select id="selectIotTerminalListByUserId" parameterType="IotTerminal" resultMap="IotTerminalResult"> 88 <select id="selectIotTerminalListByUserId" parameterType="IotTerminal" resultMap="IotTerminalResult">
89 - SELECT a.*,b.*,c.* FROM `iot_terminal` a LEFT JOIN `user_terminal_group_relation` b ON a.`id`=b.`iot_terminal_id` LEFT JOIN `iot_device` c ON c.client_id=a.`device_id` 89 + SELECT a.*,b.*,c.*,c.`name` d_name,c.`things_model_value` d_things_model_value,c.`things_model_config` d_things_model_config,c.`data_update_time` d_data_update_time FROM `iot_terminal` a LEFT JOIN `user_terminal_group_relation` b ON a.`id`=b.`iot_terminal_id` LEFT JOIN `iot_device` c ON c.client_id=a.`device_id`
90 <where> 90 <where>
91 <if test="device_id !=null and device_id != ''"> 91 <if test="device_id !=null and device_id != ''">
92 and a.device_id = #{device_id} 92 and a.device_id = #{device_id}
@@ -20,7 +20,7 @@ import org.springframework.context.annotation.ComponentScan; @@ -20,7 +20,7 @@ import org.springframework.context.annotation.ComponentScan;
20 "com.zhonglai.luhui.rocketmq", 20 "com.zhonglai.luhui.rocketmq",
21 "com.zhonglai.luhui.firewall", 21 "com.zhonglai.luhui.firewall",
22 "com.zhonglai.luhui.admin", 22 "com.zhonglai.luhui.admin",
23 - "com.zhonglai.luhui.mqtt.comm.service.redis", 23 + "com.zhonglai.luhui.device.analysis.comm.service.redis",
24 "com.zhonglai.luhui.mqtt.service.db.mode" 24 "com.zhonglai.luhui.mqtt.service.db.mode"
25 }) 25 })
26 @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) 26 @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@@ -14,7 +14,7 @@ import com.zhonglai.luhui.device.domain.IotProduct; @@ -14,7 +14,7 @@ import com.zhonglai.luhui.device.domain.IotProduct;
14 import com.zhonglai.luhui.device.service.IIotProductService; 14 import com.zhonglai.luhui.device.service.IIotProductService;
15 import com.zhonglai.luhui.admin.dto.IotThingsModelAddApi; 15 import com.zhonglai.luhui.admin.dto.IotThingsModelAddApi;
16 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelItemBase; 16 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelItemBase;
17 -import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService; 17 +import com.zhonglai.luhui.device.analysis.comm.db.mode.TerminalDataThingsModeService;
18 import io.swagger.annotations.Api; 18 import io.swagger.annotations.Api;
19 import io.swagger.annotations.ApiOperation; 19 import io.swagger.annotations.ApiOperation;
20 import org.springframework.security.access.prepost.PreAuthorize; 20 import org.springframework.security.access.prepost.PreAuthorize;
  1 +package com.zhonglai.luhui.api.config;
  2 +
  3 +import com.ruoyi.common.utils.StringUtils;
  4 +import com.zhonglai.luhui.security.dto.BaseLoginUser;
  5 +import com.zhonglai.luhui.security.filter.JwtAuthenticationTokenFilter;
  6 +import com.zhonglai.luhui.security.service.TokenService;
  7 +import com.zhonglai.luhui.security.utils.SecurityUtils;
  8 +import org.springframework.beans.factory.annotation.Autowired;
  9 +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  10 +import org.springframework.stereotype.Component;
  11 +
  12 +import javax.servlet.http.HttpServletRequest;
  13 +
  14 +@Component
  15 +public class JwtAuthenticationTokenFilterImpl extends JwtAuthenticationTokenFilter {
  16 + @Autowired
  17 + private TokenService tokenService;
  18 +
  19 + @Override
  20 + public BaseLoginUser getBaseLoginUser(HttpServletRequest request) {
  21 + return tokenService.getLoginUser(request);
  22 + }
  23 +
  24 + @Override
  25 + public boolean verifyToken(BaseLoginUser baseLoginUser) {
  26 + if (StringUtils.isNotNull(baseLoginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
  27 + {
  28 + tokenService.verifyToken(baseLoginUser);
  29 + return true;
  30 + }
  31 + return false;
  32 + }
  33 +
  34 + @Override
  35 + public UsernamePasswordAuthenticationToken getUsernamePasswordAuthenticationToken(BaseLoginUser loginUser) {
  36 + return new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
  37 + }
  38 +}
  1 +package com.zhonglai.luhui.api.controller.data;
  2 +
  3 +import com.google.common.base.CaseFormat;
  4 +import com.google.gson.JsonElement;
  5 +import com.google.gson.JsonObject;
  6 +import com.ruoyi.common.utils.DateUtils;
  7 +import com.zhonglai.luhui.api.controller.data.mapper.DeviceSensorDataMapper;
  8 +import com.zhonglai.luhui.dao.service.PublicService;
  9 +import com.zhonglai.luhui.datasource.enums.DataSource;
  10 +import com.zhonglai.luhui.datasource.enums.DataSourceType;
  11 +import io.swagger.annotations.ApiOperation;
  12 +import org.apache.commons.lang3.StringUtils;
  13 +import org.springframework.beans.factory.annotation.Autowired;
  14 +import org.springframework.stereotype.Service;
  15 +import org.springframework.web.bind.annotation.RequestMapping;
  16 +import org.springframework.web.bind.annotation.RequestMethod;
  17 +
  18 +import javax.servlet.http.HttpServletResponse;
  19 +import java.io.IOException;
  20 +import java.lang.reflect.Field;
  21 +import java.util.*;
  22 +
  23 +@Service
  24 +public class DataService {
  25 +
  26 + @Autowired
  27 + public PublicService publicService;
  28 + @Autowired
  29 + public DeviceSensorDataMapper deviceSensorDataMapper;
  30 +
  31 + @DataSource(value = DataSourceType.SLAVE)
  32 + public Map<String,Object> getViewDataBeifen(Integer dateTime,String id,String data_type)
  33 + {
  34 +
  35 + int beforTime = getBeforeDawnTimeMilly(dateTime);
  36 + String sql = "SELECT '"+id+"' device_info_id,"+data_type+" data_type,`value` data_value,`time` creat_time FROM `"+id+"-"+data_type+"` WHERE `time`>="+beforTime+" and `time`<="+(beforTime+24*60*60) ;
  37 + if("0".equals(data_type))
  38 + {
  39 + sql+=" AND (`value`+0.0)<50 ";
  40 + }
  41 + if("1".equals(data_type))
  42 + {
  43 + sql+=" AND (`value`+0.0)<30 ";
  44 + }
  45 + sql+=" AND CAST(`value` AS DECIMAL(3,1)) > 0 ORDER BY `time` ASC;";
  46 + List<Map<String, Object>> dataList = publicService.getObjectListBySQL(sql);
  47 + return getViewData(dataList,dateTime);
  48 + }
  49 +
  50 + public Map<String,Object> getViewDataBase(Integer dateTime,String id,String data_type)
  51 + {
  52 + String tableName = TableGenerateSqlEnum.DeviceSensorData.getTableName(dateTime);
  53 + String sql = "SELECT device_info_id,data_type,data_value,creat_time FROM "+tableName+" WHERE device_info_id='"+id+"' AND data_type='"+data_type+"'" ;
  54 + if("0".equals(data_type))
  55 + {
  56 + sql+=" AND (data_value+0.0)<50 ";
  57 + }
  58 + if("1".equals(data_type))
  59 + {
  60 + sql+=" AND (data_value+0.0)<30 ";
  61 + }
  62 + sql+=" AND CAST(data_value AS DECIMAL(3,1)) > 0 ORDER BY creat_time ASC;";
  63 + List<Map<String, Object>> dataList = publicService.getObjectListBySQL(sql);
  64 + return getViewData(dataList,dateTime);
  65 + }
  66 +
  67 + public Map<String,Object> getViewData(List<Map<String, Object>> dataList,Integer dateTime)
  68 + {
  69 + //两点时间绝对值
  70 + int deulftime = 10*60;
  71 + int alltime = (1*24*60*60);
  72 + return getViewData(dataList, dateTime,alltime, deulftime);
  73 + }
  74 +
  75 + public Map<String,Object> getViewData(List<Map<String, Object>> dataList,Integer dateTime,int alltime,int deulftime)
  76 + {
  77 + int size = alltime/deulftime+1;
  78 + Object[] datas = new Object[size] ; //返回的参数
  79 +// int dateTime = 1470197532;
  80 + //要找的点x轴起点
  81 + int starttime = Integer.parseInt((DateUtils.dateTime(DateUtils.YYYY_MM_DD,DateUtils.dateTime(new Date(dateTime*1000l))).getTime()+"").substring(0, 10));
  82 +
  83 + Map<Integer,Map<String, Object>> tempMap = new HashMap<Integer,Map<String, Object>>();
  84 + for(Map<String, Object> dataMap:dataList)
  85 + {
  86 + if(null != dataMap.get("creat_time")) //屏蔽错误数据
  87 + {
  88 + tempMap.put(Integer.parseInt(dataMap.get("creat_time")+""), dataMap);
  89 + }
  90 + }
  91 + dataList = null;
  92 +
  93 + double totleVaule = 0.0;
  94 + int number = 0;
  95 + double maxVaule = 0.0;
  96 + double minVaule = 0.0;
  97 + for(int i=0;i<size;i++)
  98 + {
  99 + int tempTime = starttime + i*deulftime;
  100 +
  101 + Object[] obs = new Object[2];
  102 + datas[i] = obs;
  103 + obs[0] = tempTime * 1000l;
  104 +
  105 + for(int j=0;j<(deulftime/2);j++)
  106 + {
  107 + if(tempMap.containsKey(tempTime+j))
  108 + {
  109 + obs[1] = Double.parseDouble(tempMap.get(tempTime+j).get("data_value")+"");
  110 + obs[0] = (tempTime+j) * 1000l;
  111 +
  112 +
  113 + String type= tempMap.get(tempTime+j).get("data_type")+"";
  114 + if(type.equals("0") || type.equals("1"))
  115 + {
  116 + number++;
  117 + double data_value = Double.parseDouble(tempMap.get(tempTime+j).get("data_value")+"");
  118 + totleVaule += data_value;
  119 + if(number==1)
  120 + {
  121 + maxVaule = totleVaule;
  122 + minVaule = totleVaule;
  123 + }
  124 +
  125 + if(data_value>maxVaule)
  126 + {
  127 + maxVaule = data_value;
  128 + }
  129 + if(data_value<minVaule)
  130 + {
  131 + minVaule = data_value;
  132 + }
  133 + }
  134 + break;
  135 + }else if(tempMap.containsKey(tempTime-j)){
  136 +
  137 + obs[1] = Double.parseDouble(tempMap.get(tempTime-j).get("data_value")+"");
  138 + obs[0] = (tempTime+j) * 1000l;
  139 +
  140 +
  141 + String type= tempMap.get(tempTime-j).get("data_type")+"";
  142 + if(type.equals("0") || type.equals("1"))
  143 + {
  144 + number++;
  145 + double data_value = Double.parseDouble(tempMap.get(tempTime-j).get("data_value")+"");
  146 + totleVaule += data_value;
  147 + if(number==1)
  148 + {
  149 + maxVaule = totleVaule;
  150 + minVaule = totleVaule;
  151 + }
  152 + if(data_value>maxVaule)
  153 + {
  154 + maxVaule = data_value;
  155 + }
  156 + if(data_value<minVaule)
  157 + {
  158 + minVaule = data_value;
  159 + }
  160 + }
  161 + break;
  162 + }
  163 + }
  164 + }
  165 + Map<String,Object> map = new HashMap<String,Object>();
  166 + if(number != 0)
  167 + {
  168 + map.put("averageValue", totleVaule/number);
  169 + }
  170 + map.put("data",datas);
  171 + map.put("minVaule",minVaule);
  172 + map.put("maxVaule",maxVaule);
  173 +
  174 + return map;
  175 + }
  176 +
  177 + /**
  178 + * 获取连续数据
  179 + */
  180 + public List<Map<String,Object>> getContinuousSensorData(
  181 + Integer starTime, Integer endTime, Integer interval,
  182 + String deviceInfoId, String dataType) {
  183 + String sql = "CALL get_sensor_data(" + starTime + "," + endTime + ","
  184 + + interval + ",'" + deviceInfoId + "','" + dataType + "')";
  185 + return publicService.getObjectListBySQL(sql);
  186 + }
  187 +
  188 + /**
  189 + * 获取数据曲线
  190 + *
  191 + * @param starTime
  192 + * @param endTime
  193 + * @param interval
  194 + * @param dataType
  195 + * @return
  196 + */
  197 + public Map<String,Object> getDeviceData(Integer starTime,
  198 + Integer endTime, Integer interval, String deviceInfoId, String dataType) {
  199 + List<Map<String,Object>> rongyangMap = getContinuousSensorData( starTime, endTime, interval, deviceInfoId,dataType); // 溶氧
  200 +
  201 + int dataNumb = (endTime - starTime) / interval; // 显示点数
  202 +
  203 + Object[] rongyangs = new Object[dataNumb+1];
  204 +
  205 + Double max = null;
  206 + Double min = null;
  207 + Double pingjun = 0.0;
  208 +
  209 + if(null != rongyangMap && rongyangMap.size()>0)
  210 + {
  211 + Integer temptime = starTime;
  212 + Integer tempindex = Math.round((Float.parseFloat(rongyangMap.get(0).get("creat_time")+"")-Float.parseFloat(temptime+""))/interval);
  213 + temptime = Integer.parseInt(rongyangMap.get(0).get("creat_time")+"");
  214 + for (int i=0;i<rongyangMap.size();i++) {
  215 + Map<String, Object> map = rongyangMap.get(i);
  216 + tempindex = tempindex + Math.round((Float.parseFloat(map.get("creat_time")+"")-Float.parseFloat(temptime+""))/interval);
  217 + temptime=Integer.parseInt(map.get("creat_time")+"");
  218 + Double dataValue = Double.parseDouble(map.get("data_value")+"");
  219 + if(tempindex<dataNumb)
  220 + {
  221 + rongyangs[tempindex] = new Object[] {
  222 + map.get("create_time_view"), dataValue };
  223 + }
  224 +
  225 + pingjun += dataValue / rongyangMap.size();
  226 +
  227 + if (null == max) {
  228 + max = dataValue;
  229 + }
  230 + if (null == min) {
  231 + min = dataValue;
  232 + }
  233 + if (max < dataValue) {
  234 + max = dataValue;
  235 + }
  236 + if (min > dataValue) {
  237 + min = dataValue;
  238 + }
  239 + }
  240 + }
  241 +
  242 + Map<String,Object> map = new HashMap<String,Object>();
  243 + map.put("min", min);
  244 + map.put("pingjun", pingjun);
  245 + map.put("max", max);
  246 + map.put("datas", rongyangs);
  247 + return map;
  248 + }
  249 +
  250 +
  251 + /**
  252 + * 获取设备历史数据
  253 + * @param response 返回会话
  254 + * @param startTime 开始时间(时间戳)
  255 + * @param endTime 结束时间(时间戳)
  256 + * @param interval 取点颗粒(单位分钟)
  257 + * @param deviceInfoId 设备信息表id
  258 + * @param dataType 数据类型
  259 + * @return
  260 + * @throws IOException
  261 + */
  262 + public String getDeviceHistoryData(
  263 + HttpServletResponse response,int startTime,int endTime,int interval,String deviceInfoId,String dataType) throws IOException {
  264 +
  265 + if(startTime>endTime)
  266 + {
  267 + response.setStatus(500);
  268 + return "开始时间不能大于结束时间";
  269 + }
  270 +
  271 + if(interval<10 || interval%10 != 0)
  272 + {
  273 + response.setStatus(500);
  274 + return "取点颗粒必须是10的整数倍,并且不能小于10";
  275 + }
  276 +
  277 + int nowTime = getBeforeDawnTimeMilly(DateUtils.getNowTimeMilly()); //当天凌晨时间
  278 +
  279 + StringBuffer sb = new StringBuffer();
  280 + if(nowTime>startTime)
  281 + {
  282 + StringBuffer sb2after = getBeifeiDbDeviceHistoryData(deviceInfoId,dataType,startTime,endTime,interval*60); //天以前的数据
  283 + if(null != sb2after)
  284 + {
  285 + sb.append(sb2after);
  286 + }
  287 +
  288 + }
  289 + if(endTime > nowTime)
  290 + {
  291 + StringBuffer sbafter = getDeviceTimeData(deviceInfoId,dataType,new Date(endTime*1000l),interval*60);
  292 + if(null != sbafter)
  293 + {
  294 + sb.append(sbafter);
  295 + }
  296 + }
  297 +
  298 + return sb.toString();
  299 + }
  300 +
  301 + /**
  302 + * 获取备份数据库的历史数据
  303 + * @param deviceInfoId
  304 + * @param dataType
  305 + * @return
  306 + */
  307 + @DataSource(value = DataSourceType.SLAVE)
  308 + public StringBuffer getBeifeiDbDeviceHistoryData(String deviceInfoId,String dataType,int startTime,int endTime,int interval)
  309 + {
  310 + List<Map<String,Object>> list = publicService.getObjectListBySQL("SELECT count(*) ct FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='ly-device-data' and TABLE_NAME='"+deviceInfoId+"-"+dataType+"'");
  311 +
  312 + if(null != list && list.size() !=0 && null != list.get(0) && null != list.get(0).get("ct") && (list.get(0).get("ct")+"").equals("1"))
  313 + {
  314 + list = publicService.getObjectListBySQL("select * from `ly-device-data`.`"+deviceInfoId+"-"+dataType+"` where (`time` % "+interval+")=0 and `time`>="+startTime+" and `time`<="+endTime+"");
  315 +
  316 + if(null != list && list.size() !=0 )
  317 + {
  318 + StringBuffer sb = new StringBuffer();
  319 +
  320 + for(Map<String,Object> map:list)
  321 + {
  322 + sb.append(map.get("time"));
  323 + sb.append(",");
  324 + sb.append(map.get("value"));
  325 + sb.append("\r\n");
  326 + }
  327 + return sb;
  328 + }
  329 + }
  330 + return null;
  331 + }
  332 +
  333 + /**
  334 + * 获取数据指定天的数据
  335 + *
  336 + * @param deviceInfoId 设备id
  337 + * @param dataType 数据类型
  338 + * @param date 指定天数
  339 + * @return
  340 + */
  341 + @DataSource(value = DataSourceType.SLAVE)
  342 + public StringBuffer getDeviceTimeData(String deviceInfoId, String dataType, Date date, int interval) {
  343 +
  344 + String dataTypestr = dataType;
  345 +
  346 + List<DeviceSensorData> deviceSensorDataList = deviceSensorDataMapper.getDeviceSensorDataList(getDeviceTimeDataSql(deviceInfoId,dataTypestr,date));
  347 + //间隔时间补全
  348 + String day = DateUtils.parseDateToStr("yyyyMMdd",date);
  349 + StringBuffer stringBuffer10 = SensorData.deviceSensorDataListToIntervalCompletion(deviceSensorDataList, Integer.parseInt(DateUtils.dateTime( "yyyyMMdd",day).getTime() / 1000 + ""), interval, day);
  350 + return stringBuffer10;
  351 + }
  352 +
  353 + /**
  354 + * 获取数据指定天的数据查询语句
  355 + * @param deviceInfoId
  356 + * @param dataType
  357 + * @param date
  358 + * @return
  359 + */
  360 + public String getDeviceTimeDataSql(String deviceInfoId, String dataType, Date date)
  361 + {
  362 + String sql = "select * from "+TableGenerateSqlEnum.DeviceSensorData.getTableName(date) + " where device_info_id='"+deviceInfoId+"'"
  363 + +" and data_type='"+dataType+"'";
  364 + switch (dataType)
  365 + {
  366 + case "0":
  367 + sql += " and data_value>-50 and data_value<60";
  368 + break;
  369 + case "1":
  370 + sql += " and data_value>0 and data_value<35";
  371 + break;
  372 + case "4":
  373 + sql += " and data_value>-50 and data_value<60";
  374 + break;
  375 + case "5":
  376 + sql += " and data_value>600 and data_value<1100";
  377 + break;
  378 + }
  379 + return sql;
  380 + }
  381 +
  382 + /**
  383 + * 对象转查询结果
  384 + * @param cls
  385 + * @return
  386 + */
  387 + public String objectToSelect(Class cls)
  388 + {
  389 + StringBuffer stringBuffer = new StringBuffer();
  390 + Field[] fields = cls.getDeclaredFields();
  391 + for(Field field:fields)
  392 + {
  393 + if(stringBuffer.length()!=0)
  394 + {
  395 + stringBuffer.append(",");
  396 + }
  397 + stringBuffer.append(changTableNameFromClassName(field.getName())+" as "+field.getName());
  398 + }
  399 +
  400 + return stringBuffer.toString();
  401 + }
  402 +
  403 +
  404 +
  405 + public static int getBeforeDawnTimeMilly(int now) {
  406 + int daySecond = 86400;
  407 + return now - (now + 28800) % daySecond;
  408 + }
  409 +
  410 + public static String changTableNameFromClassName(String s) {
  411 + CaseFormat fromFormat = CaseFormat.LOWER_CAMEL;
  412 + CaseFormat toFormat = CaseFormat.LOWER_UNDERSCORE;
  413 + return fromFormat.to(toFormat, s);
  414 + }
  415 +}
  1 +package com.zhonglai.luhui.api.controller.data;
  2 +
  3 +import lombok.Data;
  4 +
  5 +@Data
  6 +public class DeviceSensorData {
  7 + private String deviceInfoId; //设备信息id
  8 + private String dataType; //数据类型
  9 + private String dataValue; //L数据值
  10 + private Integer creatTime; //创建时间
  11 + private String deviceModel; // VARCHAR(10) NOT NULL COMMENT '设备型号,(3,5,6)',
  12 +}
  1 +package com.zhonglai.luhui.api.controller.data;
  2 +
  3 +import com.ruoyi.common.utils.DateUtils;
  4 +
  5 +import java.util.List;
  6 +
  7 +/**
  8 + * @类名 SensorData
  9 + * @描述 TODO
  10 + * @创建者 钟来
  11 + * @时间 18-10-12 下午12:01
  12 + * @版本 1.0
  13 + **/
  14 +public class SensorData {
  15 +
  16 +
  17 + public static StringBuffer deviceSensorDataListToIntervalCompletion(List<DeviceSensorData> deviceSensorDataList,int lastTime,int interval,String day)
  18 + {
  19 + int abs = interval;
  20 + String lastData = null;
  21 + StringBuffer stringBuffer10 = new StringBuffer(); //间隔时间补全
  22 + for(DeviceSensorData deviceSensorData:deviceSensorDataList)
  23 + {
  24 +
  25 + //计算10分钟数据
  26 + int lc = lastTime - deviceSensorData.getCreatTime();
  27 + if(lc<0)
  28 + {
  29 + while (Math.abs(lc)>interval)
  30 + {
  31 + stringBuffer10.append(lastTime);
  32 + stringBuffer10.append(",");
  33 + stringBuffer10.append(lastData);
  34 + stringBuffer10.append("\r\n");
  35 +
  36 + lastTime = lastTime+interval;
  37 + abs = interval;
  38 + lastData = null;
  39 +
  40 + lc = lastTime - deviceSensorData.getCreatTime();
  41 + }
  42 +
  43 + if(Math.abs(lc)<=abs)
  44 + {
  45 + abs = Math.abs(lc);
  46 + lastData = deviceSensorData.getDataValue();
  47 + }
  48 +
  49 + }else if(lc==0){
  50 +
  51 + stringBuffer10.append(lastTime);
  52 + stringBuffer10.append(",");
  53 + stringBuffer10.append(deviceSensorData.getDataValue());
  54 + stringBuffer10.append("\r\n");
  55 +
  56 + lastTime = lastTime+interval;
  57 + abs = interval;
  58 + lastData = null;
  59 + }else{
  60 + if(Math.abs(lc)<=abs)
  61 + {
  62 + abs = Math.abs(lc);
  63 + lastData = deviceSensorData.getDataValue();
  64 + }
  65 + }
  66 +
  67 + }
  68 +
  69 + //设置最后一个
  70 + setStringBuffer(lastData,lastTime,stringBuffer10);
  71 +
  72 + //补全后面的
  73 + int nowTIme = Integer.parseInt(DateUtils.dateTime("yyyyMMdd",day).getTime()/1000 + "");
  74 + while ((lastTime-nowTIme)<86400)
  75 + {
  76 + lastTime = lastTime+interval;
  77 +
  78 + lastData = null;
  79 + stringBuffer10.append(lastTime);
  80 + stringBuffer10.append(",");
  81 + stringBuffer10.append(lastData);
  82 + stringBuffer10.append("\r\n");
  83 +
  84 + }
  85 +
  86 + return stringBuffer10;
  87 + }
  88 +
  89 +
  90 +
  91 + public static StringBuffer deviceSensorDataListToInterval(List<DeviceSensorData> deviceSensorDataList,int lastTime,int interval)
  92 + {
  93 + int abs = interval;
  94 + String lastData = null;
  95 + StringBuffer stringBuffer = new StringBuffer(); //间隔时间
  96 +
  97 + for(DeviceSensorData deviceSensorData:deviceSensorDataList)
  98 + {
  99 +
  100 + //计算10分钟数据
  101 + int lc = lastTime - deviceSensorData.getCreatTime();
  102 + if(lc<0)
  103 + {
  104 + while (Math.abs(lc)>interval)
  105 + {
  106 + setStringBuffer(lastData,lastTime,stringBuffer);
  107 +
  108 + lastTime = lastTime+interval;
  109 + abs = interval;
  110 + lastData = null;
  111 +
  112 + lc = lastTime - deviceSensorData.getCreatTime();
  113 + }
  114 +
  115 + if(Math.abs(lc)<=abs)
  116 + {
  117 + abs = Math.abs(lc);
  118 + lastData = deviceSensorData.getDataValue();
  119 + }
  120 +
  121 + }else if(lc==0){
  122 +
  123 + setStringBuffer(deviceSensorData.getDataValue(),lastTime,stringBuffer);
  124 +
  125 + lastTime = lastTime+interval;
  126 + abs = interval;
  127 + lastData = null;
  128 + }else{
  129 + if(Math.abs(lc)<=abs)
  130 + {
  131 + abs = Math.abs(lc);
  132 + lastData = deviceSensorData.getDataValue();
  133 + }
  134 + }
  135 +
  136 + }
  137 +
  138 + //设置最后一个
  139 + setStringBuffer(lastData,lastTime,stringBuffer);
  140 +
  141 + return stringBuffer;
  142 + }
  143 +
  144 + private static void setStringBuffer(String lastData,Integer lastTime,StringBuffer stringBuffer)
  145 + {
  146 + if(null != lastData)
  147 + {
  148 + stringBuffer.append(lastTime);
  149 + stringBuffer.append(",");
  150 + stringBuffer.append(lastData);
  151 + stringBuffer.append("\r\n");
  152 + }
  153 + }
  154 +}
  1 +package com.zhonglai.luhui.api.controller.data;
  2 +
  3 +import com.ruoyi.common.utils.DateUtils;
  4 +import com.zhonglai.luhui.api.controller.data.mapper.DeviceSensorDataMapper;
  5 +import io.swagger.annotations.*;
  6 +import org.springframework.beans.factory.annotation.Autowired;
  7 +import org.springframework.stereotype.Controller;
  8 +import org.springframework.web.bind.annotation.RequestMapping;
  9 +import org.springframework.web.bind.annotation.RequestMethod;
  10 +import org.springframework.web.bind.annotation.RequestParam;
  11 +import org.springframework.web.bind.annotation.RestController;
  12 +
  13 +import javax.servlet.http.HttpServletResponse;
  14 +import java.io.IOException;
  15 +import java.util.Date;
  16 +import java.util.List;
  17 +
  18 +@Api(tags = "数据管理")
  19 +@RestController
  20 +@RequestMapping("/data/sensorData")
  21 +public class SensorDataController {
  22 +
  23 + @Autowired
  24 + public DeviceSensorDataMapper deviceSensorDataMapper;
  25 + @Autowired
  26 + public DataService dataService;
  27 + @ApiOperation(value = "获取设备当天数据", notes = "当天数据曲线")
  28 + @ApiImplicitParams({
  29 + @ApiImplicitParam(name = "deviceInfoId", value = "设备信息表id"),
  30 + @ApiImplicitParam(name = "dataType", value = "数据类型"),
  31 + @ApiImplicitParam(name = "date", value = "时间yyyyMMdd"),
  32 + @ApiImplicitParam(name = "interval", value = "间隔时间")
  33 + })
  34 + @RequestMapping(value = "", method = RequestMethod.GET)
  35 + public String getDeviceTimeData(String deviceInfoId, String dataType, String date, int interval) {
  36 +
  37 + String dataTypestr = dataType;
  38 +
  39 + List<DeviceSensorData> deviceSensorDataList = deviceSensorDataMapper.getDeviceSensorDataList(getDeviceTimeDataSql(deviceInfoId,dataTypestr,DateUtils.dateTime("yyyyMMdd",date)));
  40 + //间隔时间补全
  41 + String day = date;
  42 + StringBuffer stringBuffer10 = SensorData.deviceSensorDataListToIntervalCompletion(deviceSensorDataList, Integer.parseInt(DateUtils.dateTime("yyyyMMdd",day).getTime() / 1000 + ""), interval, day);
  43 + return stringBuffer10.toString();
  44 + }
  45 +
  46 + @ApiOperation(value = "获取设备历史数据", notes = "获取设备历史数据")
  47 + @RequestMapping(value = "getDeviceHistoryData", method = RequestMethod.GET)
  48 + public String getDeviceHistoryData(
  49 + @ApiParam(name = "startTime", value = "开始时间(时间戳)", required = true) @RequestParam(name = "startTime") int startTime,
  50 + @ApiParam(name = "endTime", value = "结束时间(时间戳)", required = true) @RequestParam(name = "endTime") int endTime,
  51 + @ApiParam(name = "interval", value = "取点颗粒(单位分钟)", required = true) @RequestParam(name = "interval") int interval,
  52 + @ApiParam(name = "deviceInfoId", value = "设备信息表id", required = true) @RequestParam(name = "deviceInfoId") String deviceInfoId,
  53 + @ApiParam(name = "dataType", value = "数据类型", required = true) @RequestParam(name = "dataType") String dataType,HttpServletResponse response) throws IOException {
  54 +
  55 + return dataService.getDeviceHistoryData(response,startTime,endTime,interval,deviceInfoId,dataType);
  56 + }
  57 +
  58 + /**
  59 + * 获取数据指定天的数据查询语句
  60 + * @param deviceInfoId
  61 + * @param dataType
  62 + * @param date
  63 + * @return
  64 + */
  65 + private String getDeviceTimeDataSql(String deviceInfoId, String dataType, Date date)
  66 + {
  67 + String sql = "select * from "+TableGenerateSqlEnum.DeviceSensorData.getTableName(date) + " where device_info_id='"+deviceInfoId+"'"
  68 + +" and data_type='"+dataType+"'";
  69 + switch (dataType)
  70 + {
  71 + case "0":
  72 + sql += " and data_value>-50 and data_value<60";
  73 + break;
  74 + case "1":
  75 + sql += " and data_value>0 and data_value<35";
  76 + break;
  77 + case "4":
  78 + sql += " and data_value>-50 and data_value<60";
  79 + break;
  80 + case "5":
  81 + sql += " and data_value>600 and data_value<1100";
  82 + break;
  83 + }
  84 + return sql;
  85 + }
  86 +
  87 +}
  1 +package com.zhonglai.luhui.api.controller.data;
  2 +
  3 +import java.util.Date;
  4 +
  5 +public enum TableGenerateSqlEnum {
  6 +
  7 + //设备传感器数据
  8 + DeviceSensorData("设备传感器数据数据库","ly_sensor_data",
  9 + "device_sensor_data",
  10 + 3,
  11 + "CREATE TABLE IF NOT EXISTS `device_sensor_data` ("+
  12 + "`device_info_id` varchar(50) NOT NULL COMMENT '设备信息id',"+
  13 + "`data_type` varchar(50) NOT NULL COMMENT '数据类型',"+
  14 + "`data_value` varchar(50) NOT NULL COMMENT '数据值',"+
  15 + "`creat_time` int(11) NOT NULL COMMENT '创建时间',"+
  16 + "`device_model` varchar(10) DEFAULT NULL COMMENT '设备型号,(3,5,6,6_P)',"+
  17 + "KEY `device_info_id` (`device_info_id`,`data_type`,`creat_time`)"+
  18 + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"
  19 + ),
  20 + //管理员操作日志
  21 + LogSysUserOperation("管理员操作日志数据库","ly_sys_user_operation",
  22 + "log_sys_user_operation",
  23 + 2,
  24 + "CREATE TABLE IF NOT EXISTS `log_sys_user_operation` (" +
  25 + " `operation_name` varchar(50) NOT NULL COMMENT '操作名称'," +
  26 + " `operation_ip` varchar(50) DEFAULT NULL COMMENT '操作ip'," +
  27 + " `operation_url` varchar(200) DEFAULT NULL COMMENT '操作连接'," +
  28 + " `operation_value` text COMMENT '操作值'," +
  29 + " `user_id` int(11) DEFAULT NULL COMMENT '用户id'," +
  30 + " `user_login_name` varchar(50) DEFAULT NULL COMMENT '用户名称'," +
  31 + " `user_nickname` varchar(50) DEFAULT NULL COMMENT '用户昵称'," +
  32 + " `create_time` int(11) NOT NULL COMMENT '创建时间'," +
  33 + " `module` varchar(50) DEFAULT NULL COMMENT '操作模块'" +
  34 + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"
  35 + ),
  36 + //设备操作日志
  37 + LogDeviceOperation("设备操作日志数据库","ly_log_device_operation",
  38 + "log_device_operation",
  39 + 3,
  40 + "CREATE TABLE IF NOT EXISTS `log_device_operation` (" +
  41 + " `device_operation_id` int(11) NOT NULL AUTO_INCREMENT," +
  42 + " `device_info_id` varchar(50) NOT NULL COMMENT '设备id'," +
  43 + " `device_operation_time` int(11) NOT NULL COMMENT '设备操作时间'," +
  44 + " `operation_instruction` text COMMENT '设备操作指令'," +
  45 + " `operation_describe` varchar(50) DEFAULT NULL COMMENT '设备操作描述'," +
  46 + " `device_old_state` text COMMENT '设备操作前状态'," +
  47 + " `device_new_state` text COMMENT '设备操作后的状态'," +
  48 + " `device_operation_type` varchar(11) DEFAULT NULL COMMENT '设备操作类型'," +
  49 + " `sensor_or_controller` varchar(50) DEFAULT '00' COMMENT '传感器或控制器编号(控制器以00_开头)'," +
  50 + " `is_state_change` int(11) DEFAULT '0' COMMENT '是否有状态改变(0否,1是)'," +
  51 + " PRIMARY KEY (`device_operation_id`)" +
  52 + ") ENGINE=InnoDB AUTO_INCREMENT=3677 DEFAULT CHARSET=utf8"
  53 + ),
  54 + //用户登录日志
  55 + UserLoginLog("用户登录日志数据库","ly_user_login",
  56 + "user_login_log",
  57 + 2,
  58 + "CREATE TABLE IF NOT EXISTS `user_login_log` (" +
  59 + " `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id'," +
  60 + " `user_id` int(11) NOT NULL COMMENT '用户id'," +
  61 + " `user_login_name` varchar(50) NOT NULL COMMENT '用户登录名'," +
  62 + " `user_nickname` varchar(50) NOT NULL COMMENT '用户姓名'," +
  63 + " `user_type` int(11) NOT NULL DEFAULT '0' COMMENT '用户类型,默认0-普通用户,1-管理员,2客服'," +
  64 + " `login_province_id` varchar(50) DEFAULT NULL COMMENT '登录省份id'," +
  65 + " `login_city_id` varchar(50) DEFAULT NULL COMMENT '登录城市id'," +
  66 + " `login_province_name` varchar(50) DEFAULT NULL COMMENT '登录省份名'," +
  67 + " `login_city_name` varchar(50) DEFAULT NULL COMMENT '登录城市名'," +
  68 + " `login_address` varchar(50) DEFAULT NULL COMMENT '登陆地址'," +
  69 + " `login_ip` varchar(50) DEFAULT NULL COMMENT '登录ip'," +
  70 + " `create_time` int(11) NOT NULL COMMENT '登陆时间'," +
  71 + " PRIMARY KEY (`id`)" +
  72 + ") ENGINE=InnoDB AUTO_INCREMENT=916 DEFAULT CHARSET=utf8"
  73 + ),
  74 + //管理员登录日志
  75 + SysUserLoginLog("管理员登录日志数据库","ly_sys_user_login",
  76 + "sys_user_login_log",
  77 + 1,
  78 + "CREATE TABLE IF NOT EXISTS `sys_user_login_log` (" +
  79 + " `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id'," +
  80 + " `user_login_name` varchar(50) NOT NULL COMMENT '用户登录名'," +
  81 + " `user_phone` varchar(50) NOT NULL COMMENT '用户电话'," +
  82 + " `login_province_id` varchar(50) DEFAULT NULL COMMENT '登录省份id'," +
  83 + " `login_city_id` varchar(50) DEFAULT NULL COMMENT '登录城市id'," +
  84 + " `login_province_name` varchar(50) DEFAULT NULL COMMENT '登录省份名'," +
  85 + " `login_city_name` varchar(50) DEFAULT NULL COMMENT '登录城市名'," +
  86 + " `login_address` varchar(50) DEFAULT NULL COMMENT '登陆地址'," +
  87 + " `login_ip` varchar(50) DEFAULT NULL COMMENT '登录ip'," +
  88 + " `create_time` int(11) NOT NULL COMMENT '登陆时间'," +
  89 + " PRIMARY KEY (`id`)" +
  90 + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"
  91 + ),
  92 + //用户操作日志
  93 + LogUserOperation("用户操作日志数据库","ly_user_operation",
  94 + "log_user_operation",
  95 + 3,
  96 + "CREATE TABLE IF NOT EXISTS `log_user_operation` (" +
  97 + " `operation_name` varchar(50) NOT NULL COMMENT '操作名称'," +
  98 + " `operation_ip` varchar(50) DEFAULT NULL COMMENT '操作ip'," +
  99 + " `operation_url` varchar(200) DEFAULT NULL COMMENT '操作连接'," +
  100 + " `operation_value` text COMMENT '操作值'," +
  101 + " `user_id` int(11) DEFAULT NULL COMMENT '用户id'," +
  102 + " `user_login_name` varchar(50) DEFAULT NULL COMMENT '用户名称'," +
  103 + " `user_nickname` varchar(50) DEFAULT NULL COMMENT '用户昵称'," +
  104 + " `create_time` int(11) NOT NULL COMMENT '创建时间'," +
  105 + " `module` varchar(50) DEFAULT NULL COMMENT '操作模块'," +
  106 + " `my_user_id` varchar(45) DEFAULT NULL COMMENT '我的用户id'," +
  107 + " `my_user_login_name` varchar(45) DEFAULT NULL COMMENT '我的用户名称'," +
  108 + " `my_user_nickname` varchar(45) DEFAULT NULL COMMENT '我的用户昵称'" +
  109 + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"
  110 + ),
  111 + //用户积分信息记录
  112 + UserIntegral("用户积分信息记录数据库","ly_user_integral",
  113 + "user_integral",
  114 + 2,
  115 + "CREATE TABLE IF NOT EXISTS `user_integral` (" +
  116 + " `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id'," +
  117 + " `user_id` int(11) DEFAULT NULL COMMENT '用户id'," +
  118 + " `integral_before` int(11) DEFAULT NULL COMMENT '操作前积分数'," +
  119 + " `integral_end` int(11) DEFAULT NULL COMMENT '操作后积分数'," +
  120 + " `integral_number` int(11) DEFAULT NULL COMMENT '积分数量'," +
  121 + " `integral_type` int(11) DEFAULT NULL COMMENT '积分类型'," +
  122 + " `integral_type_name` varchar(50) DEFAULT NULL COMMENT '积分信息'," +
  123 + " `create_time` int(11) DEFAULT NULL COMMENT '创建时间'," +
  124 + " `remark` varchar(50) DEFAULT NULL COMMENT '备注'," +
  125 + " PRIMARY KEY (`id`)" +
  126 + ") ENGINE=InnoDB AUTO_INCREMENT=4559 DEFAULT CHARSET=utf8"
  127 + ),
  128 + //告警信息
  129 + DeviceAlarmInfo("告警信息数据库","ly_device_alarm_info",
  130 + "device_alarm_info",
  131 + 3,
  132 + "CREATE TABLE IF NOT EXISTS `device_alarm_info` (" +
  133 + " `alarm_info_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id'," +
  134 + " `device_info_id` varchar(50) NOT NULL COMMENT '设备id'," +
  135 + " `alarm_code` varchar(50) NOT NULL COMMENT '告警代码'," +
  136 + " `alarm_time` int(11) DEFAULT NULL COMMENT '告警时间'," +
  137 + " `is_send_number` int(11) DEFAULT '0' COMMENT '发送次数'," +
  138 + " `alarm_state` int(11) DEFAULT '0' COMMENT '告警状态(1发生告警,0结束告警)'," +
  139 + " PRIMARY KEY (`alarm_info_id`)" +
  140 + ") ENGINE=InnoDB AUTO_INCREMENT=399144 DEFAULT CHARSET=utf8"
  141 + ),
  142 + //用户分享
  143 + UserShare("用户分享数据库","ly_user_share",
  144 + "user_share",
  145 + 2,
  146 + "CREATE TABLE IF NOT EXISTS `user_share` (" +
  147 + " `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id'," +
  148 + " `user_id` int(11) NOT NULL COMMENT '用户id'," +
  149 + " `user_login_name` varchar(50) NOT NULL COMMENT '用户登录名称'," +
  150 + " `share_content` text COMMENT '分享内容'," +
  151 + " `share_time` int(11) NOT NULL COMMENT '分享时间'," +
  152 + " `share_type` int(11) NOT NULL COMMENT '分享类型(注:1-首页分享,2-曲线分享,3-病害报表分享,4-多天曲线分享)'," +
  153 + " `random_number` int(11) DEFAULT NULL COMMENT '随机数'," +
  154 + " PRIMARY KEY (`id`)" +
  155 + ") ENGINE=InnoDB AUTO_INCREMENT=1301 DEFAULT CHARSET=utf8"
  156 + ),
  157 + //用户等级记录
  158 + UserLevel("用户等级记录","ly_user_level",
  159 + "log_user_level",
  160 + 2,
  161 + "CREATE TABLE IF NOT EXISTS `log_user_level` (" +
  162 + " `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id'," +
  163 + " `user_id` int(11) NOT NULL COMMENT '用户id'," +
  164 + " `user_login_name` varchar(50) NOT NULL COMMENT '用户登录名称'," +
  165 + " `operation` varchar(50) NOT NULL COMMENT '操作描述'," +
  166 + " `create_time` int(11) NOT NULL COMMENT '创建时间'," +
  167 + " `level` int(11) NOT NULL COMMENT '积分(可以为负数)'," +
  168 + " `use_type` int(11) NOT NULL COMMENT '使用类型'," +
  169 + " `order_id` int(11) NOT NULL COMMENT '关联支付表id'," +
  170 +
  171 + " PRIMARY KEY (`id`)" +
  172 + ") ENGINE=InnoDB AUTO_INCREMENT=1301 DEFAULT CHARSET=utf8"
  173 + ),
  174 + //用户货币记录
  175 + UserCurrency("用户货币记录","ly_user_currency",
  176 + "log_user_currency",
  177 + 2,
  178 + "CREATE TABLE IF NOT EXISTS `log_user_currency` (" +
  179 + " `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id'," +
  180 + " `user_id` int(11) NOT NULL COMMENT '用户id'," +
  181 + " `user_login_name` varchar(50) NOT NULL COMMENT '用户登录名称'," +
  182 + " `operation` varchar(50) NOT NULL COMMENT '操作描述'," +
  183 + " `create_time` int(11) NOT NULL COMMENT '创建时间'," +
  184 + " `currency` int(11) NOT NULL COMMENT '货币数(可以为负数)'," +
  185 + " `use_type` int(11) NOT NULL COMMENT '使用类型'," +
  186 + " `order_id` int(11) NOT NULL COMMENT '关联支付表id'," +
  187 + " PRIMARY KEY (`id`)" +
  188 + ") ENGINE=InnoDB AUTO_INCREMENT=1301 DEFAULT CHARSET=utf8"
  189 + ),
  190 + Device301Sensitivity("301传感器灵敏度数据","ly_device301_sensitivity","device301_sensitivity",
  191 + 2,
  192 + "CREATE TABLE IF NOT EXISTS `device301_sensitivity` (" +
  193 + " `device_info_id` varchar(50) NOT NULL COMMENT '设备信息表id'," +
  194 + " `pump_current` varchar(10) DEFAULT NULL COMMENT '水泵电流'," +
  195 + " `leakage_current` varchar(10) DEFAULT NULL COMMENT '泄露电流'," +
  196 + " `magnification` varchar(10) DEFAULT NULL COMMENT '放大倍数'," +
  197 + " `sensor_sensitivity` varchar(10) DEFAULT NULL COMMENT '传感器灵敏度'," +
  198 + " `sensor_accuracy` varchar(10) DEFAULT NULL COMMENT '传感器准确度'," +
  199 + " `create_time` int(11) NOT NULL COMMENT '添加时间'" +
  200 + " ) ENGINE=InnoDB DEFAULT CHARSET=utf8"),
  201 + LogSyswebErr("系统运行错误日志","ly_sysweb_err","log_sysweb_err",2,
  202 + "CREATE TABLE IF NOT EXISTS `log_sysweb_err` (" +
  203 + " `create_time` int(11) DEFAULT NULL COMMENT '创建时间'," +
  204 + " `url` varchar(200) DEFAULT NULL COMMENT '请求链接'," +
  205 + " `parameter_value` text COMMENT '参数'," +
  206 + " `err_message` text COMMENT '错误信息'" +
  207 + ") ENGINE=InnoDB DEFAULT CHARSET=utf8")
  208 + ;
  209 +
  210 + public String alias; //别名
  211 + public String dateBaseName; //数据库名称
  212 + public String tableName; //表名
  213 + public String generateSql; //创建sql
  214 + public int accuracy; //表类型(1年表,2月表,3日表)
  215 +
  216 + TableGenerateSqlEnum(String alias, String dateBaseName, String tableName, int accuracy, String generateSql)
  217 + {
  218 + this.alias = alias;
  219 + this.dateBaseName = dateBaseName;
  220 + this.tableName = tableName;
  221 + this.accuracy = accuracy;
  222 + this.generateSql = generateSql;
  223 + }
  224 +
  225 + public String getTableName(Date date)
  226 + {
  227 + return TableUtil.getTableName(date, dateBaseName, tableName,accuracy);
  228 + }
  229 +
  230 + public String getNowTableName()
  231 + {
  232 + return TableUtil.getNowTableName( dateBaseName, tableName,accuracy);
  233 + }
  234 + public String getTableName(String date)
  235 + {
  236 + return TableUtil.getTableName( date,dateBaseName, tableName,accuracy);
  237 + }
  238 +
  239 + public String getTableName(Integer date)
  240 + {
  241 + return getTableName(new Date(date*1000l));
  242 + }
  243 +}
  1 +package com.zhonglai.luhui.api.controller.data;
  2 +
  3 +import com.ruoyi.common.utils.DateUtils;
  4 +
  5 +import java.util.Date;
  6 +
  7 +public class TableUtil {
  8 + public TableUtil() {
  9 + }
  10 +
  11 + public static String getNowTableName(String dateBase, String tableName, int accuracy) {
  12 + return getTableName(getTimeToString(), dateBase, tableName, accuracy);
  13 + }
  14 +
  15 + public static String getTableName(Date date, String dateBase, String tableName, int accuracy) {
  16 + return getTableName(getTimeToString(date), dateBase, tableName, accuracy);
  17 + }
  18 +
  19 + public static String getTableName(String date, String dateBase, String tableName, int accuracy) {
  20 + String[] datas = date.split("-");
  21 + dateBase = dateBase + "_" + datas[0];
  22 + if (0 == accuracy) {
  23 + tableName = tableName + "";
  24 + } else if (1 == accuracy) {
  25 + tableName = tableName + "_" + datas[0];
  26 + } else if (2 == accuracy) {
  27 + tableName = tableName + "_" + datas[0] + datas[1];
  28 + } else if (3 == accuracy) {
  29 + tableName = tableName + "_" + datas[0] + datas[1] + datas[2];
  30 + } else {
  31 + tableName = tableName + "_" + datas[0] + datas[1] + datas[2];
  32 + }
  33 +
  34 + return dateBase + "." + tableName;
  35 + }
  36 +
  37 + public static String getTimeToString(long dateValue) {
  38 + return DateUtils.parseDateToStr( "yyyy-MM-dd",new Date(dateValue));
  39 + }
  40 +
  41 + public static String getTimeToString(int dateValue) {
  42 + return DateUtils.parseDateToStr("yyyy-MM-dd",new Date((long)dateValue * 1000L));
  43 + }
  44 +
  45 + public static String getTimeToString(Date dateValue) {
  46 + return DateUtils.parseDateToStr( "yyyy-MM-dd",dateValue);
  47 + }
  48 +
  49 + public static String getTimeToString() {
  50 + return DateUtils.parseDateToStr("yyyy-MM-dd",new Date());
  51 + }
  52 +}
  1 +package com.zhonglai.luhui.api.controller.data.mapper;
  2 +
  3 +import com.zhonglai.luhui.api.controller.data.DeviceSensorData;
  4 +import com.zhonglai.luhui.dao.dto.PublicSQL;
  5 +import org.apache.ibatis.annotations.Param;
  6 +import org.apache.ibatis.annotations.SelectProvider;
  7 +import org.springframework.stereotype.Component;
  8 +import tk.mybatis.mapper.common.BaseMapper;
  9 +
  10 +import java.util.List;
  11 +
  12 +@Component(value = "DeviceSensorDataMapper")
  13 +public interface DeviceSensorDataMapper extends BaseMapper<DeviceSensorData> {
  14 + @SelectProvider(type = PublicSQL.class, method = "getObjectListBySQL")
  15 + List<DeviceSensorData> getDeviceSensorDataList(@Param("sql") String sql);
  16 +
  17 +}
@@ -12,10 +12,10 @@ spring: @@ -12,10 +12,10 @@ spring:
12 # 从库数据源 12 # 从库数据源
13 slave: 13 slave:
14 # 从数据源开关/默认关闭 14 # 从数据源开关/默认关闭
15 - enabled: false  
16 - url:  
17 - username:  
18 - password: 15 + enabled: true
  16 + url: jdbc:mysql://rm-wz9a3l0g7cjysv8054o.mysql.rds.aliyuncs.com:3306/ly-device-data?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
  17 + username: luhui
  18 + password: Luhui586
19 # 初始连接数 19 # 初始连接数
20 initialSize: 5 20 initialSize: 5
21 # 最小连接池数量 21 # 最小连接池数量
@@ -14,7 +14,7 @@ PUBLIC "-//mybatis.org//DTD Config 3.0//EN" @@ -14,7 +14,7 @@ PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
14 <!-- 指定 MyBatis 所用日志的具体实现 --> 14 <!-- 指定 MyBatis 所用日志的具体实现 -->
15 <setting name="logImpl" value="SLF4J" /> 15 <setting name="logImpl" value="SLF4J" />
16 <!-- 使用驼峰命名法转换字段 --> 16 <!-- 使用驼峰命名法转换字段 -->
17 - <!-- <setting name="mapUnderscoreToCamelCase" value="true"/> --> 17 + <setting name="mapUnderscoreToCamelCase" value="true"/>
18 </settings> 18 </settings>
19 19
20 </configuration> 20 </configuration>
@@ -25,21 +25,9 @@ @@ -25,21 +25,9 @@
25 </dependency> 25 </dependency>
26 <dependency> 26 <dependency>
27 <groupId>com.zhonglai.luhui</groupId> 27 <groupId>com.zhonglai.luhui</groupId>
28 - <artifactId>lh-jar-sys-service</artifactId>  
29 - </dependency>  
30 - <dependency>  
31 - <groupId>com.zhonglai.luhui</groupId>  
32 - <artifactId>lh-common-swagger</artifactId>  
33 - </dependency>  
34 - <dependency>  
35 - <groupId>com.zhonglai.luhui</groupId>  
36 <artifactId>lh-common-datasource</artifactId> 28 <artifactId>lh-common-datasource</artifactId>
37 </dependency> 29 </dependency>
38 <dependency> 30 <dependency>
39 - <groupId>com.zhonglai.luhui</groupId>  
40 - <artifactId>lh-public-dao</artifactId>  
41 - </dependency>  
42 - <dependency>  
43 <groupId>org.aspectj</groupId> 31 <groupId>org.aspectj</groupId>
44 <artifactId>aspectjweaver</artifactId> 32 <artifactId>aspectjweaver</artifactId>
45 </dependency> 33 </dependency>
@@ -48,18 +36,13 @@ @@ -48,18 +36,13 @@
48 <artifactId>aspectjrt</artifactId> 36 <artifactId>aspectjrt</artifactId>
49 </dependency> 37 </dependency>
50 <dependency> 38 <dependency>
51 - <groupId>org.springframework.boot</groupId>  
52 - <artifactId>spring-boot-starter-data-jpa</artifactId> 39 + <groupId>com.zhonglai.luhui</groupId>
  40 + <artifactId>lh-jar-device-analysis</artifactId>
53 </dependency> 41 </dependency>
54 <dependency> 42 <dependency>
55 - <groupId>org.yaml</groupId>  
56 - <artifactId>snakeyaml</artifactId> 43 + <groupId>com.zhonglai.luhui</groupId>
  44 + <artifactId>lh-jar-device-service</artifactId>
57 </dependency> 45 </dependency>
58 -  
59 - <!-- <dependency>-->  
60 -<!-- <groupId>com.zhonglai.luhui</groupId>-->  
61 -<!-- <artifactId>lh-jar-device-analysis</artifactId>-->  
62 -<!-- </dependency>-->  
63 </dependencies> 46 </dependencies>
64 47
65 <build> 48 <build>
@@ -85,7 +68,7 @@ @@ -85,7 +68,7 @@
85 生成的manifest中classpath的前缀,因为要把第三方jar放到lib目录下,所以classpath的前缀是lib/ 68 生成的manifest中classpath的前缀,因为要把第三方jar放到lib目录下,所以classpath的前缀是lib/
86 --> 69 -->
87 <classpathPrefix>lib/</classpathPrefix> 70 <classpathPrefix>lib/</classpathPrefix>
88 - <mainClass>com.zhonglai.luhui.http.service.Main</mainClass> 71 + <mainClass>com.zhonglai.luhui.http.service.LhHttpServiceApplication</mainClass>
89 </manifest> 72 </manifest>
90 </archive> 73 </archive>
91 </configuration> 74 </configuration>
@@ -98,7 +81,7 @@ @@ -98,7 +81,7 @@
98 <version>2.4</version> 81 <version>2.4</version>
99 <configuration> 82 <configuration>
100 <descriptors> 83 <descriptors>
101 - <descriptor>src/main/resources/package.xml</descriptor> 84 + <descriptor>${project.parent.parent.basedir}/configs/package.xml</descriptor>
102 </descriptors> 85 </descriptors>
103 </configuration> 86 </configuration>
104 <executions> 87 <executions>
1 package com.zhonglai.luhui.http.service; 1 package com.zhonglai.luhui.http.service;
2 2
3 -import org.slf4j.Logger;  
4 -import org.slf4j.LoggerFactory; 3 +import com.ruoyi.framework.config.ResourcesConfig;
  4 +import com.zhonglai.luhui.device.service.DeviceControlService;
5 import org.springframework.boot.SpringApplication; 5 import org.springframework.boot.SpringApplication;
6 import org.springframework.boot.autoconfigure.SpringBootApplication; 6 import org.springframework.boot.autoconfigure.SpringBootApplication;
7 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 7 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
8 import org.springframework.context.annotation.ComponentScan; 8 import org.springframework.context.annotation.ComponentScan;
  9 +import org.springframework.context.annotation.FilterType;
9 10
10 @ComponentScan(basePackages = { 11 @ComponentScan(basePackages = {
11 "com.ruoyi.common", 12 "com.ruoyi.common",
12 "com.ruoyi.framework", 13 "com.ruoyi.framework",
13 "com.zhonglai.luhui.datasource", 14 "com.zhonglai.luhui.datasource",
14 "com.zhonglai.luhui.dao", 15 "com.zhonglai.luhui.dao",
  16 + "com.zhonglai.luhui.device",
  17 + "com.zhonglai.luhui.redis",
  18 + "com.zhonglai.luhui.rocketmq",
15 "com.zhonglai.luhui.http.service", 19 "com.zhonglai.luhui.http.service",
16 } 20 }
17 ) 21 )
18 -@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class})  
19 -public class Main {  
20 - private static final Logger logger = LoggerFactory.getLogger(Main.class); 22 +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
  23 +public class LhHttpServiceApplication {
21 public static void main(String[] args) { 24 public static void main(String[] args) {
22 - SpringApplication.run(Main.class,args);  
23 - logger.info("启动服务"); 25 + SpringApplication.run(LhHttpServiceApplication.class,args);
  26 + System.out.println("启动成功");
24 } 27 }
25 } 28 }
@@ -8,6 +8,7 @@ import org.springframework.context.annotation.Configuration; @@ -8,6 +8,7 @@ import org.springframework.context.annotation.Configuration;
8 import springfox.documentation.builders.ApiInfoBuilder; 8 import springfox.documentation.builders.ApiInfoBuilder;
9 import springfox.documentation.builders.PathSelectors; 9 import springfox.documentation.builders.PathSelectors;
10 import springfox.documentation.builders.RequestHandlerSelectors; 10 import springfox.documentation.builders.RequestHandlerSelectors;
  11 +import springfox.documentation.service.ApiInfo;
11 import springfox.documentation.service.Contact; 12 import springfox.documentation.service.Contact;
12 import springfox.documentation.spi.DocumentationType; 13 import springfox.documentation.spi.DocumentationType;
13 import springfox.documentation.spring.web.plugins.Docket; 14 import springfox.documentation.spring.web.plugins.Docket;
@@ -23,19 +24,29 @@ public class SwaggerConfig { @@ -23,19 +24,29 @@ public class SwaggerConfig {
23 @Bean 24 @Bean
24 public Docket createRestApi() { 25 public Docket createRestApi() {
25 return new Docket(DocumentationType.SWAGGER_2) 26 return new Docket(DocumentationType.SWAGGER_2)
26 - .groupName("设备http服务器")  
27 - .apiInfo(  
28 - new ApiInfoBuilder().title("标题:设备http服务器")  
29 - .description("设备http服务器")  
30 - .contact(new Contact(ruoyiConfig.getName(), null, null))  
31 - .version("版本号:" + ruoyiConfig.getVersion())  
32 - .build()  
33 - ) 27 + .apiInfo(apiInfo())
34 .select() 28 .select()
35 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) 29 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
36 .paths(PathSelectors.any()) 30 .paths(PathSelectors.any())
37 .build(); 31 .build();
38 } 32 }
39 33
  34 + /**
  35 + * 添加摘要信息
  36 + */
  37 + private ApiInfo apiInfo()
  38 + {
  39 + // 用ApiInfoBuilder进行定制
  40 + return new ApiInfoBuilder()
  41 + // 设置标题
  42 + .title("标题:登陆服务")
  43 + // 描述
  44 + .description("描述:各种角色的登陆接口")
  45 + // 作者信息
  46 + .contact(new Contact(ruoyiConfig.getName(), null, null))
  47 + // 版本
  48 + .version("版本号:" + ruoyiConfig.getVersion())
  49 + .build();
  50 + }
40 51
41 } 52 }
1 package com.zhonglai.luhui.http.service.controller; 1 package com.zhonglai.luhui.http.service.controller;
2 2
3 import com.ruoyi.common.core.domain.AjaxResult; 3 import com.ruoyi.common.core.domain.AjaxResult;
  4 +import com.ruoyi.common.exception.ServiceException;
4 import com.ruoyi.common.utils.StringUtils; 5 import com.ruoyi.common.utils.StringUtils;
  6 +import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
  7 +import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto;
  8 +import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDtoClassNew;
  9 +import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement;
  10 +import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreementFactory;
  11 +import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
  12 +import com.zhonglai.luhui.device.analysis.comm.service.CacheService;
  13 +import com.zhonglai.luhui.device.analysis.comm.service.DataPersistenceService;
  14 +import com.zhonglai.luhui.device.domain.IotDevice;
  15 +import com.zhonglai.luhui.device.service.IIotDeviceService;
  16 +import com.zhonglai.luhui.http.service.util.HttpServletRequestUtil;
5 import io.swagger.annotations.Api; 17 import io.swagger.annotations.Api;
6 import io.swagger.annotations.ApiOperation; 18 import io.swagger.annotations.ApiOperation;
  19 +import org.slf4j.Logger;
  20 +import org.slf4j.LoggerFactory;
  21 +import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.web.bind.annotation.ModelAttribute; 22 import org.springframework.web.bind.annotation.ModelAttribute;
8 import org.springframework.web.bind.annotation.PathVariable; 23 import org.springframework.web.bind.annotation.PathVariable;
9 import org.springframework.web.bind.annotation.RequestMapping; 24 import org.springframework.web.bind.annotation.RequestMapping;
@@ -15,10 +30,24 @@ import javax.servlet.http.HttpServletResponse; @@ -15,10 +30,24 @@ import javax.servlet.http.HttpServletResponse;
15 @Api(tags = "设备操作") 30 @Api(tags = "设备操作")
16 @RestController 31 @RestController
17 @RequestMapping("/device") 32 @RequestMapping("/device")
18 -public class DeviceService { 33 +public class DeviceServiceController {
  34 +
  35 + private static final Logger log = LoggerFactory.getLogger(DeviceServiceController.class);
19 36
20 private static String authKey = "key"; 37 private static String authKey = "key";
21 38
  39 + @Autowired
  40 + private IIotDeviceService deviceService ;
  41 +
  42 + @Autowired
  43 + private BusinessAgreementFactory businessAgreementFactory;
  44 +
  45 + @Autowired
  46 + private CacheService cacheService; //数据缓存
  47 +
  48 + @Autowired
  49 + private DataPersistenceService dataPersistenceService; //数据持久化
  50 +
22 /** 51 /**
23 * 添加校验 52 * 添加校验
24 * @return 53 * @return
@@ -30,19 +59,54 @@ public class DeviceService { @@ -30,19 +59,54 @@ public class DeviceService {
30 if(StringUtils.isNoneEmpty(key)) 59 if(StringUtils.isNoneEmpty(key))
31 { 60 {
32 response.setStatus(403); 61 response.setStatus(403);
  62 + throw new ServiceException("验证失败");
33 } 63 }
  64 +
34 } 65 }
35 66
36 @ApiOperation("更新指定设备的全部数据") 67 @ApiOperation("更新指定设备的全部数据")
37 - @RequestMapping(value = "putAllData/{deviceid}")  
38 - public AjaxResult putAllData(@PathVariable String deviceid) 68 + @RequestMapping(value = "putAllData/{deviceid}/{messageid}")
  69 + public AjaxResult putDeviceAllData(@PathVariable String deviceid,@PathVariable String messageid,HttpServletRequest request) throws Exception {
  70 + String str = HttpServletRequestUtil.getAllParametersAsJSON(request);
  71 +
  72 + if(StringUtils.isEmpty(str))
39 { 73 {
  74 + return AjaxResult.error("数据为空");
  75 + }
  76 +
  77 + String imei = deviceid.split("_")[0];
  78 + IotDevice iotDevice = deviceService.selectIotDeviceByClient_id(imei);
  79 + Topic topic = new Topic();
  80 + topic.setRoleid(iotDevice.getProduct_id()+"");
  81 + topic.setUsername(iotDevice.getMqtt_username());
  82 + topic.setClientid(iotDevice.getClient_id());
  83 + topic.setTopicType("PUT");
  84 + topic.setMessageid(messageid);
  85 + topic.setPayloadtype("json");
  86 +
  87 + //转化为协议对象
  88 + BusinessDto businessDto = BusinessDtoClassNew.newBean(topic.getPayloadtype(),str.getBytes()).analyticalModel(iotDevice.getThings_model_value());
  89 +
  90 + BusinessAgreement businessAgreement = businessAgreementFactory.createBusinessAgreement(topic);
  91 + //解析为业务对象
  92 + ServerDto dto = businessAgreement.analysis(topic,businessAgreement.toData(businessDto));
  93 + if(null == dto)
  94 + {
  95 + return AjaxResult.error("没有业务解析方法");
  96 + }
  97 + log.info("{} 解析到的dto【{}】",dto);
  98 +
  99 + //缓存数据
  100 + cacheService.updateCache(topic,dto);
  101 +
  102 + //数据持久化
  103 + dataPersistenceService.persistence(topic,dto);
40 return AjaxResult.success(); 104 return AjaxResult.success();
41 } 105 }
42 106
43 @ApiOperation("更新指定设备的部分数据") 107 @ApiOperation("更新指定设备的部分数据")
44 @RequestMapping(value = "putPartialData/{deviceid}") 108 @RequestMapping(value = "putPartialData/{deviceid}")
45 - public AjaxResult putPartialData(@PathVariable String deviceid) 109 + public AjaxResult putDevicePartialData(@PathVariable String deviceid)
46 { 110 {
47 return AjaxResult.success(); 111 return AjaxResult.success();
48 } 112 }
  1 +package com.zhonglai.luhui.http.service.util;
  2 +
  3 +import com.fasterxml.jackson.databind.ObjectMapper;
  4 +import javax.servlet.http.HttpServletRequest;
  5 +import java.io.IOException;
  6 +import java.util.HashMap;
  7 +import java.util.Map;
  8 +
  9 +public class HttpServletRequestUtil {
  10 + public static String getAllParametersAsJSON(HttpServletRequest request) {
  11 + Map<String, String[]> parameters = request.getParameterMap();
  12 + Map<String, Object> allParameters = new HashMap<>();
  13 +
  14 + // 将URL参数添加到参数Map中
  15 + for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
  16 + String key = entry.getKey();
  17 + String[] values = entry.getValue();
  18 + if (values.length == 1) {
  19 + allParameters.put(key, values[0]);
  20 + } else {
  21 + allParameters.put(key, values);
  22 + }
  23 + }
  24 +
  25 + // 将请求体参数添加到参数Map中
  26 + try {
  27 + ObjectMapper objectMapper = new ObjectMapper();
  28 + Map<String, Object> requestBodyParameters = objectMapper.readValue(request.getInputStream(), Map.class);
  29 + allParameters.putAll(requestBodyParameters);
  30 + } catch (IOException e) {
  31 + e.printStackTrace();
  32 + }
  33 +
  34 + // 将参数Map转化为JSON格式的字符串
  35 + ObjectMapper objectMapper = new ObjectMapper();
  36 + String json = "";
  37 +
  38 + try {
  39 + json = objectMapper.writeValueAsString(allParameters);
  40 + } catch (IOException e) {
  41 + e.printStackTrace();
  42 + }
  43 +
  44 + return json;
  45 + }
  46 +}
1 -# 开发环境配置 server: # 服务器的HTTP端口,默认为8080 port: 8065 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 # Swagger配置 swagger: # 是否开启swagger enabled: true # 请求前缀 pathMapping: /dev-api # 防止XSS攻击 xss: # 过滤开关 enabled: true # 排除链接(多个用逗号分隔) excludes: /system/notice # 匹配链接 urlPatterns: /system/*,/monitor/*,/tool/*  
  1 +# 项目相关配置 jhlt: # 名称 name: zhonglai # 版本 version: 3.8.2 # 版权年份 copyrightYear: 2022 # 实例演示开关 demoEnabled: true # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath) profile: D:/ruoyi/uploadPath # 获取ip地址开关 addressEnabled: false # 验证码类型 math 数组计算 char 字符验证 captchaType: math # 开发环境配置 server: # 服务器的HTTP端口,默认为8080 port: 8061 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 ##redic配置 redis: database: 1 # Redis服务器地址 写你的ip host: 47.112.163.61 # Redis服务器连接端口 port: 9527 # Redis服务器连接密码(默认为空) password: Luhui586 # 连接池最大连接数(使用负值表示没有限制 类似于mysql的连接池 jedis: pool: max-active: 200 # 连接池最大阻塞等待时间(使用负值表示没有限制) 表示连接池的链接拿完了 现在去申请需要等待的时间 max-wait: -1 # 连接池中的最大空闲连接 max-idle: 10 # 连接池中的最小空闲连接 min-idle: 0 # 连接超时时间(毫秒) 去链接redis服务端 timeout: 6000 # MyBatis配置 mybatis: # 搜索指定包别名 typeAliasesPackage: com.ruoyi.**.domain,com.zhonglai.luhui.**.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: /** redis: field: "lh:mqttservice:" isText: false # NameServer地址 rocketmq: name-server: 47.115.144.179:9876 # 默认的消息组 producer: group: deviceCommand send-message-timeout: 30000 send-topic: lh-http-service-deviceCommand-test send-tags: 1
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<configuration>
  3 + <!-- 日志存放路径 -->
  4 + <property name="log.path" value="logs" />
  5 + <!-- 日志输出格式 -->
  6 + <property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
  7 +
  8 + <!-- 控制台输出 -->
  9 + <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
  10 + <encoder>
  11 + <pattern>${log.pattern}</pattern>
  12 + </encoder>
  13 + </appender>
  14 +
  15 + <!-- 系统日志输出 -->
  16 + <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
  17 + <file>${log.path}/sys-info.log</file>
  18 + <!-- 循环政策:基于时间创建日志文件 -->
  19 + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  20 + <!-- 日志文件名格式 -->
  21 + <fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
  22 + <!-- 日志最大的历史 60天 -->
  23 + <maxHistory>60</maxHistory>
  24 + </rollingPolicy>
  25 + <encoder>
  26 + <pattern>${log.pattern}</pattern>
  27 + </encoder>
  28 + <filter class="ch.qos.logback.classic.filter.LevelFilter">
  29 + <!-- 过滤的级别 -->
  30 + <level>INFO</level>
  31 + <!-- 匹配时的操作:接收(记录) -->
  32 + <onMatch>ACCEPT</onMatch>
  33 + <!-- 不匹配时的操作:拒绝(不记录) -->
  34 + <onMismatch>DENY</onMismatch>
  35 + </filter>
  36 + </appender>
  37 +
  38 + <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
  39 + <file>${log.path}/sys-error.log</file>
  40 + <!-- 循环政策:基于时间创建日志文件 -->
  41 + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  42 + <!-- 日志文件名格式 -->
  43 + <fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
  44 + <!-- 日志最大的历史 60天 -->
  45 + <maxHistory>60</maxHistory>
  46 + </rollingPolicy>
  47 + <encoder>
  48 + <pattern>${log.pattern}</pattern>
  49 + </encoder>
  50 + <filter class="ch.qos.logback.classic.filter.LevelFilter">
  51 + <!-- 过滤的级别 -->
  52 + <level>ERROR</level>
  53 + <!-- 匹配时的操作:接收(记录) -->
  54 + <onMatch>ACCEPT</onMatch>
  55 + <!-- 不匹配时的操作:拒绝(不记录) -->
  56 + <onMismatch>DENY</onMismatch>
  57 + </filter>
  58 + </appender>
  59 +
  60 + <!-- 用户访问日志输出 -->
  61 + <appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender">
  62 + <file>${log.path}/sys-user.log</file>
  63 + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  64 + <!-- 按天回滚 daily -->
  65 + <fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern>
  66 + <!-- 日志最大的历史 60天 -->
  67 + <maxHistory>60</maxHistory>
  68 + </rollingPolicy>
  69 + <encoder>
  70 + <pattern>${log.pattern}</pattern>
  71 + </encoder>
  72 + </appender>
  73 +
  74 + <!-- 系统模块日志级别控制 -->
  75 + <logger name="com.ruoyi" level="info" />
  76 + <!-- Spring日志级别控制 -->
  77 + <logger name="org.springframework" level="warn" />
  78 +
  79 + <root level="info">
  80 + <appender-ref ref="console" />
  81 + </root>
  82 +
  83 + <!--系统操作日志-->
  84 + <root level="info">
  85 + <appender-ref ref="file_info" />
  86 + <appender-ref ref="file_error" />
  87 + </root>
  88 +
  89 + <!--系统用户操作日志-->
  90 + <logger name="sys-user" level="info">
  91 + <appender-ref ref="sys-user"/>
  92 + </logger>
  93 +</configuration>
@@ -73,7 +73,7 @@ @@ -73,7 +73,7 @@
73 生成的manifest中classpath的前缀,因为要把第三方jar放到lib目录下,所以classpath的前缀是lib/ 73 生成的manifest中classpath的前缀,因为要把第三方jar放到lib目录下,所以classpath的前缀是lib/
74 --> 74 -->
75 <classpathPrefix>lib/</classpathPrefix> 75 <classpathPrefix>lib/</classpathPrefix>
76 - <mainClass>com.zhonglai.luhui.login.LhLoginApplication</mainClass> 76 + <mainClass>com.zhonglai.luhui.http.service.LhHttpServiceApplication</mainClass>
77 </manifest> 77 </manifest>
78 </archive> 78 </archive>
79 </configuration> 79 </configuration>
@@ -4,9 +4,9 @@ import com.ruoyi.common.constant.Constants; @@ -4,9 +4,9 @@ import com.ruoyi.common.constant.Constants;
4 import com.ruoyi.common.core.domain.AjaxResult; 4 import com.ruoyi.common.core.domain.AjaxResult;
5 import com.ruoyi.common.utils.StringUtils; 5 import com.ruoyi.common.utils.StringUtils;
6 import com.zhonglai.luhui.action.BaseController; 6 import com.zhonglai.luhui.action.BaseController;
  7 +import com.zhonglai.luhui.login.service.LoginService;
7 import com.zhonglai.luhui.login.model.LoginBody; 8 import com.zhonglai.luhui.login.model.LoginBody;
8 import com.zhonglai.luhui.login.model.RegisterBody; 9 import com.zhonglai.luhui.login.model.RegisterBody;
9 -import com.zhonglai.luhui.login.service.LoginService;  
10 import com.zhonglai.luhui.login.service.SysRegisterService; 10 import com.zhonglai.luhui.login.service.SysRegisterService;
11 import com.zhonglai.luhui.sys.service.ISysConfigService; 11 import com.zhonglai.luhui.sys.service.ISysConfigService;
12 import io.swagger.annotations.Api; 12 import io.swagger.annotations.Api;
@@ -4,6 +4,7 @@ import com.ruoyi.common.constant.Constants; @@ -4,6 +4,7 @@ import com.ruoyi.common.constant.Constants;
4 import com.ruoyi.common.tool.SysLogininforType; 4 import com.ruoyi.common.tool.SysLogininforType;
5 import com.ruoyi.common.utils.MessageUtils; 5 import com.ruoyi.common.utils.MessageUtils;
6 import com.ruoyi.common.utils.spring.SpringUtils; 6 import com.ruoyi.common.utils.spring.SpringUtils;
  7 +import com.zhonglai.luhui.login.service.LoginService;
7 import com.zhonglai.luhui.security.dto.LoginToken; 8 import com.zhonglai.luhui.security.dto.LoginToken;
8 import com.zhonglai.luhui.security.dto.OpenAiLoginUser; 9 import com.zhonglai.luhui.security.dto.OpenAiLoginUser;
9 import com.zhonglai.luhui.security.dto.OpenAiUserInfo; 10 import com.zhonglai.luhui.security.dto.OpenAiUserInfo;
@@ -82,39 +82,6 @@ @@ -82,39 +82,6 @@
82 <version>${swagger-ui.version}</version> 82 <version>${swagger-ui.version}</version>
83 </dependency> 83 </dependency>
84 84
85 - <!-- mqtt -->  
86 - <dependency>  
87 - <groupId>org.eclipse.paho</groupId>  
88 - <artifactId>org.eclipse.paho.client.mqttv3</artifactId>  
89 - </dependency>  
90 -  
91 - <dependency>  
92 - <groupId>net.jodah</groupId>  
93 - <artifactId>expiringmap</artifactId>  
94 - </dependency>  
95 -  
96 -  
97 - <!-- 数据库 -->  
98 - <dependency>  
99 - <groupId>commons-dbcp</groupId>  
100 - <artifactId>commons-dbcp</artifactId>  
101 - <version>1.4</version>  
102 - </dependency>  
103 - <dependency>  
104 - <groupId>commons-dbutils</groupId>  
105 - <artifactId>commons-dbutils</artifactId>  
106 - <version>1.6</version>  
107 - </dependency>  
108 - <dependency>  
109 - <groupId>commons-pool</groupId>  
110 - <artifactId>commons-pool</artifactId>  
111 - <version>1.6</version>  
112 - </dependency>  
113 - <dependency>  
114 - <groupId>mysql</groupId>  
115 - <artifactId>mysql-connector-java</artifactId>  
116 - <version>8.0.17</version>  
117 - </dependency>  
118 85
119 <!-- 支持data --> 86 <!-- 支持data -->
120 <dependency> 87 <dependency>
@@ -3,6 +3,7 @@ package com.zhonglai.luhui.mqtt; @@ -3,6 +3,7 @@ package com.zhonglai.luhui.mqtt;
3 import org.slf4j.Logger; 3 import org.slf4j.Logger;
4 import org.slf4j.LoggerFactory; 4 import org.slf4j.LoggerFactory;
5 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
  6 +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
6 import org.springframework.boot.builder.SpringApplicationBuilder; 7 import org.springframework.boot.builder.SpringApplicationBuilder;
7 import org.springframework.context.annotation.ComponentScan; 8 import org.springframework.context.annotation.ComponentScan;
8 9
@@ -16,7 +17,7 @@ import org.springframework.context.annotation.ComponentScan; @@ -16,7 +17,7 @@ import org.springframework.context.annotation.ComponentScan;
16 "com.zhonglai.luhui.mqtt.service", 17 "com.zhonglai.luhui.mqtt.service",
17 "com.zhonglai.luhui.mqtt.controller", 18 "com.zhonglai.luhui.mqtt.controller",
18 }) 19 })
19 -@SpringBootApplication 20 +@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
20 public class MqttApplication { 21 public class MqttApplication {
21 private static Logger log = LoggerFactory.getLogger(MqttApplication.class); 22 private static Logger log = LoggerFactory.getLogger(MqttApplication.class);
22 23
1 package com.zhonglai.luhui.mqtt.comm.rocketMq; 1 package com.zhonglai.luhui.mqtt.comm.rocketMq;
2 2
3 import com.alibaba.fastjson.JSON; 3 import com.alibaba.fastjson.JSON;
4 -import com.zhonglai.luhui.mqtt.comm.dto.DeviceCommandApi; 4 +import com.zhonglai.luhui.device.analysis.comm.db.DeviceService;
  5 +import com.zhonglai.luhui.mqtt.comm.service.DeviceCommandApi;
5 import com.zhonglai.luhui.device.analysis.dto.Message; 6 import com.zhonglai.luhui.device.analysis.dto.Message;
6 import com.zhonglai.luhui.device.analysis.dto.MessageCode; 7 import com.zhonglai.luhui.device.analysis.dto.MessageCode;
7 -import com.zhonglai.luhui.mqtt.service.db.DeviceService; 8 +import com.zhonglai.luhui.mqtt.comm.service.MqttDeviceService;
8 import org.apache.rocketmq.common.message.MessageExt; 9 import org.apache.rocketmq.common.message.MessageExt;
9 import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; 10 import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
10 import org.apache.rocketmq.spring.annotation.SelectorType; 11 import org.apache.rocketmq.spring.annotation.SelectorType;
@@ -21,7 +22,7 @@ public class RocketMqService implements RocketMQReplyListener<MessageExt, Messag @@ -21,7 +22,7 @@ public class RocketMqService implements RocketMQReplyListener<MessageExt, Messag
21 private static final Logger log = LoggerFactory.getLogger(RocketMqService.class); 22 private static final Logger log = LoggerFactory.getLogger(RocketMqService.class);
22 23
23 @Autowired 24 @Autowired
24 - private DeviceService deviceService ; 25 + private MqttDeviceService deviceService ;
25 26
26 @Override 27 @Override
27 public Message onMessage(MessageExt messageExt) { 28 public Message onMessage(MessageExt messageExt) {
1 -package com.zhonglai.luhui.mqtt.comm.dto; 1 +package com.zhonglai.luhui.mqtt.comm.service;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 import com.zhonglai.luhui.device.analysis.dto.ApiName; 4 import com.zhonglai.luhui.device.analysis.dto.ApiName;
@@ -7,7 +7,6 @@ import com.zhonglai.luhui.device.analysis.dto.Message; @@ -7,7 +7,6 @@ import com.zhonglai.luhui.device.analysis.dto.Message;
7 import com.zhonglai.luhui.device.analysis.dto.MessageCode; 7 import com.zhonglai.luhui.device.analysis.dto.MessageCode;
8 import com.zhonglai.luhui.device.domain.IotDevice; 8 import com.zhonglai.luhui.device.domain.IotDevice;
9 import com.zhonglai.luhui.device.domain.IotTerminal; 9 import com.zhonglai.luhui.device.domain.IotTerminal;
10 -import com.zhonglai.luhui.mqtt.service.db.DeviceService;  
11 import org.eclipse.paho.client.mqttv3.MqttException; 10 import org.eclipse.paho.client.mqttv3.MqttException;
12 11
13 /** 12 /**
@@ -17,7 +16,7 @@ public class DeviceCommandApi { @@ -17,7 +16,7 @@ public class DeviceCommandApi {
17 private ApiName apiName; //指令接口名称 16 private ApiName apiName; //指令接口名称
18 private DeviceCommandApiParameter deviceCommandApiParameter; //参数 17 private DeviceCommandApiParameter deviceCommandApiParameter; //参数
19 18
20 - public Message invokeApi(DeviceService deviceService) throws MqttException, InterruptedException { 19 + public Message invokeApi(MqttDeviceService deviceService) throws InterruptedException, MqttException {
21 switch (apiName) 20 switch (apiName)
22 { 21 {
23 case read: 22 case read:
@@ -29,8 +28,10 @@ public class DeviceCommandApi { @@ -29,8 +28,10 @@ public class DeviceCommandApi {
29 case closeSession: 28 case closeSession:
30 return deviceService.closeSession(deviceCommandApiParameter.getClient_id()); 29 return deviceService.closeSession(deviceCommandApiParameter.getClient_id());
31 case delIotDevice: 30 case delIotDevice:
  31 + deviceService.closeSession(deviceCommandApiParameter.getClient_id()); //强制下线
32 return deviceService.delIotDevice(deviceCommandApiParameter.getClient_id()); 32 return deviceService.delIotDevice(deviceCommandApiParameter.getClient_id());
33 case delIotTerminal: 33 case delIotTerminal:
  34 + deviceService.closeSession(deviceCommandApiParameter.getClient_id()); //强制下线
34 return deviceService.delIotTerminal(deviceCommandApiParameter.getClient_id(),deviceCommandApiParameter.getNumber()); 35 return deviceService.delIotTerminal(deviceCommandApiParameter.getClient_id(),deviceCommandApiParameter.getNumber());
35 case getFirmwareVersion: 36 case getFirmwareVersion:
36 return deviceService.getFirmwareVersion(deviceCommandApiParameter.getData()); 37 return deviceService.getFirmwareVersion(deviceCommandApiParameter.getData());
@@ -3,13 +3,15 @@ package com.zhonglai.luhui.mqtt.comm.service; @@ -3,13 +3,15 @@ package com.zhonglai.luhui.mqtt.comm.service;
3 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; 3 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
4 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto; 4 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto;
5 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDtoClassNew; 5 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDtoClassNew;
  6 +import com.zhonglai.luhui.device.analysis.comm.service.CacheService;
  7 +import com.zhonglai.luhui.device.analysis.comm.service.DataPersistenceService;
6 import com.zhonglai.luhui.device.analysis.comm.util.ByteUtil; 8 import com.zhonglai.luhui.device.analysis.comm.util.ByteUtil;
7 import com.zhonglai.luhui.device.domain.IotDevice; 9 import com.zhonglai.luhui.device.domain.IotDevice;
8 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement; 10 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement;
9 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreementFactory; 11 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreementFactory;
10 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 12 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
11 import com.zhonglai.luhui.mqtt.comm.util.TopicUtil; 13 import com.zhonglai.luhui.mqtt.comm.util.TopicUtil;
12 -import com.zhonglai.luhui.mqtt.service.db.DeviceService; 14 +import com.zhonglai.luhui.device.analysis.comm.db.DeviceService;
13 import lombok.SneakyThrows; 15 import lombok.SneakyThrows;
14 import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; 16 import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
15 import org.eclipse.paho.client.mqttv3.MqttCallbackExtended; 17 import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
  1 +package com.zhonglai.luhui.mqtt.comm.service;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.alibaba.fastjson.JSONObject;
  5 +import com.zhonglai.luhui.device.analysis.comm.db.DeviceService;
  6 +import com.zhonglai.luhui.device.analysis.comm.db.mode.TerminalDataThingsModeService;
  7 +import com.zhonglai.luhui.device.analysis.comm.dto.LogDeviceOperation;
  8 +import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelBase;
  9 +import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelDataTypeEnum;
  10 +import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelItemBase;
  11 +import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
  12 +import com.zhonglai.luhui.device.analysis.comm.service.*;
  13 +import com.zhonglai.luhui.device.analysis.comm.util.DateUtils;
  14 +import com.zhonglai.luhui.device.analysis.dto.Message;
  15 +import com.zhonglai.luhui.device.analysis.dto.MessageCode;
  16 +import com.zhonglai.luhui.device.analysis.dto.topic.AddPostDto;
  17 +import com.zhonglai.luhui.device.domain.IotThingsModel;
  18 +import com.zhonglai.luhui.mqtt.service.ClienNoticeService;
  19 +import org.eclipse.paho.client.mqttv3.MqttException;
  20 +import org.eclipse.paho.client.mqttv3.MqttMessage;
  21 +import org.slf4j.Logger;
  22 +import org.slf4j.LoggerFactory;
  23 +import org.springframework.beans.factory.annotation.Autowired;
  24 +import org.springframework.stereotype.Service;
  25 +
  26 +import java.util.ArrayList;
  27 +import java.util.List;
  28 +import java.util.Map;
  29 +
  30 +@Service
  31 +public class MqttDeviceService extends DeviceService{
  32 + private static final Logger log = LoggerFactory.getLogger(MqttDeviceService.class);
  33 + @Autowired
  34 + private ClienNoticeService clienNoticeService;
  35 +
  36 + @Autowired
  37 + private DeviceLogService dviceLogService;
  38 +
  39 + @Autowired
  40 + private CacheServiceImpl cacheServiceImpl;
  41 +
  42 + @Autowired
  43 + private DataPersistenceServiceImpl dataPersistenceService;
  44 +
  45 + @Autowired
  46 + private BusinessDataUpdateService businessDataUpdateService ;
  47 +
  48 + @Autowired
  49 + private TerminalDataThingsModeService terminalDataThingsModeService;
  50 +
  51 +
  52 + /**
  53 + * 控制发16进制指令
  54 + * @param clienid
  55 + * @param data
  56 + * @return
  57 + * @throws MqttException
  58 + * @throws InterruptedException
  59 + */
  60 + public Message controlHex(String clienid, String data) throws MqttException, InterruptedException {
  61 +
  62 + Topic topic = getTopicFromDb(clienid);
  63 + if(null == topic)
  64 + {
  65 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");
  66 + }
  67 + topic.setTopicType("PUT");
  68 + topic.setMessageid(DateUtils.getNowTimeMilly()+"");
  69 +
  70 + MqttMessage mqttMessage = new MqttMessage();
  71 + byte[] bs = hexStringToByte(data.trim().toUpperCase());
  72 + mqttMessage.setPayload(bs);
  73 +
  74 + Message message = clienNoticeService.sendMessage(topic,mqttMessage);
  75 + if(1==message.getCode())
  76 + {
  77 + List<LogDeviceOperation> list = new ArrayList<>();
  78 + list.add(dviceLogService.newLogDeviceOperation(clienid,null!=message.getData()? JSON.toJSONString(message.getData()):null,null,"远程操作控制设备","controlHex?"+data));
  79 + dviceLogService.saveOperationLog(list);
  80 + }
  81 + return message;
  82 + }
  83 +
  84 + /**
  85 + * 控制发json
  86 + * @param clienid
  87 + * @param map
  88 + * @return
  89 + * @throws MqttException
  90 + * @throws InterruptedException
  91 + */
  92 + public Message control(String clienid, Map<String,Object> map) throws MqttException, InterruptedException {
  93 +
  94 + if(null == map || map.size() ==0)
  95 + {
  96 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"参数验证失败");
  97 + }
  98 +
  99 + Topic topic = getTopicFromDb(clienid);
  100 + if(null == topic)
  101 + {
  102 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");
  103 + }
  104 + topic.setTopicType("PUT");
  105 + topic.setMessageid(DateUtils.getNowTimeMilly()+"");
  106 +
  107 + StringBuffer stringBuffer = new StringBuffer("");
  108 + List<LogDeviceOperation> logDeviceOperationList = new ArrayList<>();
  109 + for(String key:map.keySet())
  110 + {
  111 + Object sendMap = map.get(key);
  112 + JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(sendMap));
  113 + for(String skey:jsonObject.keySet())
  114 + {
  115 + IotThingsModel thingsModel = terminalDataThingsModeService.getIotThingsModel(topic.getUsername(),skey);
  116 + if(null == thingsModel) //没有配置的 都按字符串处理
  117 + {
  118 + thingsModel = new IotThingsModel();
  119 + thingsModel.setData_type(ThingsModelDataTypeEnum.STRING.name());
  120 + thingsModel.setIdentifier(key);
  121 + thingsModel.setModel_name(key);
  122 + thingsModel.setIs_top(0);
  123 + thingsModel.setIs_monitor(0);
  124 + thingsModel.setIs_save_log(0);
  125 + thingsModel.setIs_config(0);
  126 + JSONObject spes = new JSONObject();
  127 + spes.put("maxLength",255);
  128 + thingsModel.setSpecs(spes.toString());
  129 + }
  130 + String data_type = thingsModel.getData_type().toUpperCase();
  131 + Class<ThingsModelBase> aClass = Enum.valueOf(ThingsModelDataTypeEnum.class,data_type).getaClass();
  132 + ThingsModelBase thingsModelBase = JSON.parseObject(thingsModel.getSpecs(),aClass);
  133 + thingsModelBase.conversionThingsModel(thingsModel);
  134 + Object object = jsonObject.get(skey);
  135 +// Type clas = ((ParameterizedType)aClass.getGenericSuperclass()).getActualTypeArguments()[0];
  136 +// if(null != object && object.getClass()!=clas)
  137 +// {
  138 +// return new Message(MessageCode.DEFAULT_FAIL_CODE,skey+" 参数数据类型和模型数据类型("+clas+")不一致");
  139 +// }
  140 + ThingsModelItemBase thingsModelItemBase = (ThingsModelItemBase) thingsModelBase;
  141 + jsonObject.put(skey,thingsModelItemBase.getCmdView(object));
  142 + thingsModelBase.addValue(thingsModelItemBase.getCmdView(object));
  143 + String id = clienid+"_"+key;
  144 + logDeviceOperationList.add(dviceLogService.newLogDeviceOperation(id,thingsModelItemBase.getSaveView(),null,"远程控制"+thingsModelItemBase.getName()+"为"+thingsModelItemBase.getView(),null));
  145 + }
  146 +
  147 + map.put(key,jsonObject);
  148 +
  149 + }
  150 + MqttMessage mqttMessage = new MqttMessage();
  151 + mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());
  152 + Message message = clienNoticeService.sendMessage(topic,mqttMessage);
  153 + if(1==message.getCode())
  154 + {
  155 + topic.setClientid(clienid);
  156 + AddPostDto addPostDto = new AddPostDto();
  157 + addPostDto.setData(JSON.parseObject(JSON.toJSONString(map)));
  158 + addPostDto.setIotTerminalList(new ArrayList<>());
  159 + addPostDto.setDeviceSensorDataList(new ArrayList<>());
  160 + addPostDto.setLogDeviceOperationList(new ArrayList<>());
  161 + businessDataUpdateService.updataDta(BusinessDataUpdateService.Type.ADD,topic,addPostDto,"远程控制",true);
  162 + cacheServiceImpl.updateCache(topic,addPostDto);
  163 + addPostDto.setLogDeviceOperationList(logDeviceOperationList);
  164 + dataPersistenceService.persistence(topic,addPostDto);
  165 + }
  166 + return message;
  167 + }
  168 +
  169 + /**
  170 + * 读
  171 + * @param clienid
  172 + * @param map
  173 + * @return
  174 + * @throws MqttException
  175 + * @throws InterruptedException
  176 + */
  177 + public Message read(String clienid,Map<String,Object> map) throws MqttException, InterruptedException {
  178 + log.info("api请求读取 {} 参数 {}",map);
  179 + if(null == map || map.size() ==0)
  180 + {
  181 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"参数验证失败");
  182 + }
  183 +
  184 + Topic topic = getTopicFromDb(clienid);
  185 + if(null == topic)
  186 + {
  187 + return new Message(MessageCode.DEFAULT_FAIL_CODE,"mqtt_username查询失败");
  188 + }
  189 + topic.setTopicType("READ");
  190 + topic.setMessageid(DateUtils.getNowTimeMilly()+"");
  191 + MqttMessage mqttMessage = new MqttMessage();
  192 + mqttMessage.setPayload(JSON.toJSONString(map).trim().getBytes());
  193 + Message message = clienNoticeService.sendMessage(topic,mqttMessage);
  194 +
  195 + if(1==message.getCode())
  196 + {
  197 + List<LogDeviceOperation> list = new ArrayList<>();
  198 + list.add(dviceLogService.newLogDeviceOperation(clienid,JSON.toJSONString(message.getData()),null,"远程操作读取配置参数","read?"+JSON.toJSONString(map).trim()));
  199 + dviceLogService.saveOperationLog(list);
  200 + }
  201 +
  202 + return message;
  203 + }
  204 +
  205 +
  206 + /**
  207 + * 强行断开链接
  208 + * @param clienid
  209 + * @return
  210 + * @throws MqttException
  211 + * @throws InterruptedException
  212 + */
  213 + public Message closeSession(String clienid) throws MqttException, InterruptedException {
  214 +
  215 + MqttMessage mqttMessage = new MqttMessage();
  216 + byte[] bs = hexStringToByte(clienid.trim().toUpperCase());
  217 + mqttMessage.setPayload(bs);
  218 +
  219 + clienNoticeService.sendMessage("CLOSE",mqttMessage);
  220 + List<LogDeviceOperation> list = new ArrayList<>();
  221 + list.add(dviceLogService.newLogDeviceOperation(clienid,null,null,"远程操作强行断开链接","closeSession?"));
  222 + dviceLogService.saveOperationLog(list);
  223 + return new Message(MessageCode.DEFAULT_SUCCESS_CODE,"端口请求已发送");
  224 + }
  225 +}
1 package com.zhonglai.luhui.mqtt.comm.service; 1 package com.zhonglai.luhui.mqtt.comm.service;
2 2
3 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 3 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
4 -import com.zhonglai.luhui.mqtt.comm.config.SysParameter; 4 +import com.zhonglai.luhui.device.analysis.comm.config.SysParameter;
  5 +import com.zhonglai.luhui.device.analysis.comm.service.DataModeAnalysisService;
5 import com.zhonglai.luhui.mqtt.comm.util.TopicUtil; 6 import com.zhonglai.luhui.mqtt.comm.util.TopicUtil;
6 import org.apache.commons.lang3.StringUtils; 7 import org.apache.commons.lang3.StringUtils;
7 import org.eclipse.paho.client.mqttv3.MqttClient; 8 import org.eclipse.paho.client.mqttv3.MqttClient;
@@ -3,7 +3,7 @@ package com.zhonglai.luhui.mqtt.comm.util; @@ -3,7 +3,7 @@ package com.zhonglai.luhui.mqtt.comm.util;
3 import com.zhonglai.luhui.device.analysis.comm.dto.MyException; 3 import com.zhonglai.luhui.device.analysis.comm.dto.MyException;
4 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 4 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
5 import com.zhonglai.luhui.device.analysis.comm.util.StringUtils; 5 import com.zhonglai.luhui.device.analysis.comm.util.StringUtils;
6 -import com.zhonglai.luhui.mqtt.comm.config.SysParameter; 6 +import com.zhonglai.luhui.device.analysis.comm.config.SysParameter;
7 import org.slf4j.Logger; 7 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory; 8 import org.slf4j.LoggerFactory;
9 9
@@ -5,8 +5,9 @@ import com.zhonglai.luhui.device.domain.IotTerminal; @@ -5,8 +5,9 @@ import com.zhonglai.luhui.device.domain.IotTerminal;
5 import com.zhonglai.luhui.device.domain.IotThingsModel; 5 import com.zhonglai.luhui.device.domain.IotThingsModel;
6 import com.zhonglai.luhui.device.analysis.dto.Message; 6 import com.zhonglai.luhui.device.analysis.dto.Message;
7 import com.zhonglai.luhui.device.analysis.dto.MessageCode; 7 import com.zhonglai.luhui.device.analysis.dto.MessageCode;
8 -import com.zhonglai.luhui.mqtt.service.db.DeviceService;  
9 -import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService; 8 +import com.zhonglai.luhui.device.analysis.comm.db.DeviceService;
  9 +import com.zhonglai.luhui.device.analysis.comm.db.mode.TerminalDataThingsModeService;
  10 +import com.zhonglai.luhui.mqtt.comm.service.MqttDeviceService;
10 import io.swagger.annotations.Api; 11 import io.swagger.annotations.Api;
11 import io.swagger.annotations.ApiOperation; 12 import io.swagger.annotations.ApiOperation;
12 import org.eclipse.paho.client.mqttv3.MqttException; 13 import org.eclipse.paho.client.mqttv3.MqttException;
@@ -23,31 +24,36 @@ public class DeviceController { @@ -23,31 +24,36 @@ public class DeviceController {
23 24
24 @Autowired 25 @Autowired
25 private DeviceService deviceService ; 26 private DeviceService deviceService ;
  27 +
  28 + @Autowired
  29 + private MqttDeviceService mqttDeviceService ;
  30 +
26 @Autowired 31 @Autowired
27 private TerminalDataThingsModeService terminalDataThingsModeService; 32 private TerminalDataThingsModeService terminalDataThingsModeService;
28 33
29 @ApiOperation("控制发16进制指令") 34 @ApiOperation("控制发16进制指令")
30 @RequestMapping(value = "controlHex/{clienid}",method = RequestMethod.POST) 35 @RequestMapping(value = "controlHex/{clienid}",method = RequestMethod.POST)
31 public Message controlHex(@PathVariable String clienid, String data) throws MqttException, InterruptedException { 36 public Message controlHex(@PathVariable String clienid, String data) throws MqttException, InterruptedException {
32 - return deviceService.controlHex(clienid,data); 37 + return mqttDeviceService.controlHex(clienid,data);
33 } 38 }
34 39
35 @ApiOperation("读") 40 @ApiOperation("读")
36 @RequestMapping(value = "read/{clienid}",method = RequestMethod.POST) 41 @RequestMapping(value = "read/{clienid}",method = RequestMethod.POST)
37 public Message read(@PathVariable String clienid,@RequestBody Map<String,Object> map) throws MqttException, InterruptedException { 42 public Message read(@PathVariable String clienid,@RequestBody Map<String,Object> map) throws MqttException, InterruptedException {
38 - return deviceService.read(clienid,map); 43 + return mqttDeviceService.read(clienid,map);
39 } 44 }
40 45
41 @ApiOperation("强行断开链接") 46 @ApiOperation("强行断开链接")
42 @RequestMapping(value = "closeSession/{clienid}",method = RequestMethod.POST) 47 @RequestMapping(value = "closeSession/{clienid}",method = RequestMethod.POST)
43 public Message closeSession(@PathVariable String clienid) throws MqttException, InterruptedException { 48 public Message closeSession(@PathVariable String clienid) throws MqttException, InterruptedException {
44 - return deviceService.closeSession(clienid); 49 + return mqttDeviceService.closeSession(clienid);
45 } 50 }
46 51
47 @ApiOperation("删除主机") 52 @ApiOperation("删除主机")
48 @Transactional 53 @Transactional
49 @RequestMapping(value = "delIotDevice/{client_id}",method = RequestMethod.POST) 54 @RequestMapping(value = "delIotDevice/{client_id}",method = RequestMethod.POST)
50 public Message delIotDevice(@PathVariable String client_id) throws MqttException, InterruptedException { 55 public Message delIotDevice(@PathVariable String client_id) throws MqttException, InterruptedException {
  56 + mqttDeviceService.closeSession(client_id); //强制下线
51 return deviceService.delIotDevice(client_id); 57 return deviceService.delIotDevice(client_id);
52 } 58 }
53 59
@@ -55,13 +61,14 @@ public class DeviceController { @@ -55,13 +61,14 @@ public class DeviceController {
55 @Transactional 61 @Transactional
56 @RequestMapping(value = "delIotTerminal/{client_id}/{number}",method = RequestMethod.POST) 62 @RequestMapping(value = "delIotTerminal/{client_id}/{number}",method = RequestMethod.POST)
57 public Message delIotTerminal(@PathVariable String client_id,@PathVariable String number) throws MqttException, InterruptedException { 63 public Message delIotTerminal(@PathVariable String client_id,@PathVariable String number) throws MqttException, InterruptedException {
  64 + mqttDeviceService.closeSession(client_id); //强制下线
58 return deviceService.delIotTerminal(client_id,number); 65 return deviceService.delIotTerminal(client_id,number);
59 } 66 }
60 67
61 @ApiOperation("控制发json") 68 @ApiOperation("控制发json")
62 @RequestMapping(value = "control/{clienid}",method = RequestMethod.POST) 69 @RequestMapping(value = "control/{clienid}",method = RequestMethod.POST)
63 public Message control(@PathVariable String clienid,@RequestBody Map<String,Object> map) throws MqttException, InterruptedException { 70 public Message control(@PathVariable String clienid,@RequestBody Map<String,Object> map) throws MqttException, InterruptedException {
64 - return deviceService.control(clienid,map); 71 + return mqttDeviceService.control(clienid,map);
65 } 72 }
66 73
67 @ApiOperation("获取指定设备版本信息") 74 @ApiOperation("获取指定设备版本信息")
1 -package com.zhonglai.luhui.mqtt.comm.service; 1 +package com.zhonglai.luhui.mqtt.service;
2 2
3 import com.zhonglai.luhui.device.analysis.comm.clien.ClienConnection; 3 import com.zhonglai.luhui.device.analysis.comm.clien.ClienConnection;
4 import com.zhonglai.luhui.device.analysis.comm.clien.impl.ClienConnectionImpl; 4 import com.zhonglai.luhui.device.analysis.comm.clien.impl.ClienConnectionImpl;
@@ -7,6 +7,7 @@ import com.zhonglai.luhui.device.analysis.comm.dto.TerminalClientRePlyDto; @@ -7,6 +7,7 @@ import com.zhonglai.luhui.device.analysis.comm.dto.TerminalClientRePlyDto;
7 import com.zhonglai.luhui.device.analysis.comm.util.ByteUtil; 7 import com.zhonglai.luhui.device.analysis.comm.util.ByteUtil;
8 import com.zhonglai.luhui.device.analysis.dto.Message; 8 import com.zhonglai.luhui.device.analysis.dto.Message;
9 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 9 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
  10 +import com.zhonglai.luhui.mqtt.comm.service.TerminalService;
10 import com.zhonglai.luhui.mqtt.comm.util.TopicUtil; 11 import com.zhonglai.luhui.mqtt.comm.util.TopicUtil;
11 import net.jodah.expiringmap.ExpirationListener; 12 import net.jodah.expiringmap.ExpirationListener;
12 import net.jodah.expiringmap.ExpirationPolicy; 13 import net.jodah.expiringmap.ExpirationPolicy;
@@ -5,7 +5,7 @@ import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; @@ -5,7 +5,7 @@ import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
5 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto; 5 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto;
6 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement; 6 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement;
7 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 7 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
8 -import com.zhonglai.luhui.mqtt.comm.service.BusinessDataUpdateService; 8 +import com.zhonglai.luhui.device.analysis.comm.service.BusinessDataUpdateService;
9 import com.zhonglai.luhui.device.analysis.dto.topic.AddPostDto; 9 import com.zhonglai.luhui.device.analysis.dto.topic.AddPostDto;
10 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.stereotype.Service; 11 import org.springframework.stereotype.Service;
@@ -5,7 +5,7 @@ import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; @@ -5,7 +5,7 @@ import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
5 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto; 5 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto;
6 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement; 6 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement;
7 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 7 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
8 -import com.zhonglai.luhui.mqtt.comm.service.BusinessDataUpdateService; 8 +import com.zhonglai.luhui.device.analysis.comm.service.BusinessDataUpdateService;
9 import com.zhonglai.luhui.device.analysis.dto.topic.AllPostDto; 9 import com.zhonglai.luhui.device.analysis.dto.topic.AllPostDto;
10 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.stereotype.Service; 11 import org.springframework.stereotype.Service;
@@ -3,13 +3,13 @@ package com.zhonglai.luhui.mqtt.service.topic; @@ -3,13 +3,13 @@ package com.zhonglai.luhui.mqtt.service.topic;
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 import com.zhonglai.luhui.device.domain.IotDevice; 4 import com.zhonglai.luhui.device.domain.IotDevice;
5 import com.zhonglai.luhui.device.domain.IotTerminal; 5 import com.zhonglai.luhui.device.domain.IotTerminal;
6 -import com.zhonglai.luhui.mqtt.comm.dao.BaseDao; 6 +import com.zhonglai.luhui.device.analysis.comm.dao.BaseDao;
7 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; 7 import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
8 import com.zhonglai.luhui.device.analysis.comm.dto.TerminalClientRePlyDto; 8 import com.zhonglai.luhui.device.analysis.comm.dto.TerminalClientRePlyDto;
9 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto; 9 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto;
10 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement; 10 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement;
11 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 11 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
12 -import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService; 12 +import com.zhonglai.luhui.mqtt.service.ClienNoticeService;
13 import com.zhonglai.luhui.device.analysis.comm.util.StringUtils; 13 import com.zhonglai.luhui.device.analysis.comm.util.StringUtils;
14 import com.zhonglai.luhui.device.analysis.dto.topic.GetDto; 14 import com.zhonglai.luhui.device.analysis.dto.topic.GetDto;
15 import com.zhonglai.luhui.mqtt.comm.util.TopicUtil; 15 import com.zhonglai.luhui.mqtt.comm.util.TopicUtil;
@@ -6,8 +6,8 @@ import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto; @@ -6,8 +6,8 @@ import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto;
6 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement; 6 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement;
7 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 7 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
8 import com.zhonglai.luhui.device.analysis.dto.topic.OnlineDto; 8 import com.zhonglai.luhui.device.analysis.dto.topic.OnlineDto;
9 -import com.zhonglai.luhui.mqtt.service.CacheServiceImpl;  
10 -import com.zhonglai.luhui.mqtt.service.db.DeviceService; 9 +import com.zhonglai.luhui.device.analysis.comm.service.CacheServiceImpl;
  10 +import com.zhonglai.luhui.device.analysis.comm.db.DeviceService;
11 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.stereotype.Service; 12 import org.springframework.stereotype.Service;
13 13
@@ -5,7 +5,7 @@ import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto; @@ -5,7 +5,7 @@ import com.zhonglai.luhui.device.analysis.comm.dto.ServerDto;
5 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto; 5 import com.zhonglai.luhui.device.analysis.comm.dto.business.BusinessDto;
6 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement; 6 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement;
7 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 7 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
8 -import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService; 8 +import com.zhonglai.luhui.mqtt.service.ClienNoticeService;
9 import com.zhonglai.luhui.device.analysis.dto.MessageCode; 9 import com.zhonglai.luhui.device.analysis.dto.MessageCode;
10 import com.zhonglai.luhui.device.analysis.dto.topic.PutReqDto; 10 import com.zhonglai.luhui.device.analysis.dto.topic.PutReqDto;
11 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.beans.factory.annotation.Autowired;
@@ -9,10 +9,10 @@ import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelBase; @@ -9,10 +9,10 @@ import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelBase;
9 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelDataTypeEnum; 9 import com.zhonglai.luhui.device.analysis.comm.dto.thingsmodels.ThingsModelDataTypeEnum;
10 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement; 10 import com.zhonglai.luhui.device.analysis.comm.factory.BusinessAgreement;
11 import com.zhonglai.luhui.device.analysis.comm.factory.Topic; 11 import com.zhonglai.luhui.device.analysis.comm.factory.Topic;
12 -import com.zhonglai.luhui.mqtt.comm.service.ClienNoticeService; 12 +import com.zhonglai.luhui.mqtt.service.ClienNoticeService;
13 import com.zhonglai.luhui.device.analysis.dto.MessageCode; 13 import com.zhonglai.luhui.device.analysis.dto.MessageCode;
14 import com.zhonglai.luhui.device.analysis.dto.topic.ReadReqDto; 14 import com.zhonglai.luhui.device.analysis.dto.topic.ReadReqDto;
15 -import com.zhonglai.luhui.mqtt.service.db.mode.TerminalDataThingsModeService; 15 +import com.zhonglai.luhui.device.analysis.comm.db.mode.TerminalDataThingsModeService;
16 import org.apache.commons.lang3.EnumUtils; 16 import org.apache.commons.lang3.EnumUtils;
17 import org.springframework.beans.factory.annotation.Autowired; 17 import org.springframework.beans.factory.annotation.Autowired;
18 import org.springframework.stereotype.Service; 18 import org.springframework.stereotype.Service;
@@ -13,7 +13,6 @@ import com.ruoyi.common.utils.StringUtils; @@ -13,7 +13,6 @@ import com.ruoyi.common.utils.StringUtils;
13 import com.zhonglai.luhui.action.BaseController; 13 import com.zhonglai.luhui.action.BaseController;
14 import com.zhonglai.luhui.dao.service.PublicService; 14 import com.zhonglai.luhui.dao.service.PublicService;
15 import com.zhonglai.luhui.login.service.LocalLoginService; 15 import com.zhonglai.luhui.login.service.LocalLoginService;
16 -import com.zhonglai.luhui.login.service.LoginService;  
17 import com.zhonglai.luhui.security.dto.OpenAiUserInfo; 16 import com.zhonglai.luhui.security.dto.OpenAiUserInfo;
18 import io.swagger.annotations.Api; 17 import io.swagger.annotations.Api;
19 import io.swagger.annotations.ApiImplicitParam; 18 import io.swagger.annotations.ApiImplicitParam;
  1 +#!/bin/bash
  2 +
  3 +APP_PATH="/path/to/your/application"
  4 +APP_JAR="yourapp.jar"
  5 +SERVICE_NAME="yourapp"
  6 +
  7 +# 创建systemd服务文件
  8 +echo "[Unit]
  9 +Description=Your Java Application
  10 +After=network.target
  11 +
  12 +[Service]
  13 +User=root
  14 +WorkingDirectory=$APP_PATH
  15 +ExecStart=/usr/bin/java -jar $APP_JAR
  16 +SuccessExitStatus=143
  17 +TimeoutStopSec=10
  18 +Restart=on-failure
  19 +
  20 +[Install]
  21 +WantedBy=multi-user.target
  22 +" > /etc/systemd/system/$SERVICE_NAME.service
  23 +
  24 +# 重新加载systemd,使新的服务生效
  25 +systemctl daemon-reload
  26 +
  27 +# 开启服务
  28 +systemctl start $SERVICE_NAME
  29 +
  30 +# 设置服务开机自启
  31 +systemctl enable $SERVICE_NAME
  32 +
  33 +echo "Service $SERVICE_NAME installed."
  1 +package com.zhonglai.luhui.smart.feeder.config.manager;
  2 +
  3 +import com.ruoyi.common.utils.Threads;
  4 +import com.ruoyi.common.utils.spring.SpringUtils;
  5 +
  6 +import java.util.TimerTask;
  7 +import java.util.concurrent.ScheduledExecutorService;
  8 +import java.util.concurrent.TimeUnit;
  9 +
  10 +/**
  11 + * 异步任务管理器
  12 + *
  13 + * @author ruoyi
  14 + */
  15 +public class AsyncManager
  16 +{
  17 +
  18 + /**
  19 + * 异步操作任务调度线程池
  20 + */
  21 + private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
  22 +
  23 + /**
  24 + * 单例模式
  25 + */
  26 + private AsyncManager(){}
  27 +
  28 + private static AsyncManager me = new AsyncManager();
  29 +
  30 + public static AsyncManager me()
  31 + {
  32 + return me;
  33 + }
  34 +
  35 + /**
  36 + * 停止任务线程池
  37 + */
  38 + public void shutdown()
  39 + {
  40 + Threads.shutdownAndAwaitTermination(executor);
  41 + }
  42 +}
  1 +//package com.zhonglai.luhui.smart.feeder.config.manager;
  2 +//
  3 +//import com.zhonglai.luhui.smart.feeder.service.EhCacheService;
  4 +//import org.slf4j.Logger;
  5 +//import org.slf4j.LoggerFactory;
  6 +//import org.springframework.beans.factory.annotation.Autowired;
  7 +//import org.springframework.stereotype.Component;
  8 +//
  9 +//import javax.annotation.PreDestroy;
  10 +//
  11 +///**
  12 +// * 确保应用退出时能关闭后台线程
  13 +// *
  14 +// * @author ruoyi
  15 +// */
  16 +//@Component
  17 +//public class ShutdownManager
  18 +//{
  19 +// private static final Logger logger = LoggerFactory.getLogger(ShutdownManager.class);
  20 +//
  21 +// @Autowired
  22 +// private EhCacheService ehCacheService;
  23 +//
  24 +// @PreDestroy
  25 +// public void destroy()
  26 +// {
  27 +// shutdownAsyncManager();
  28 +// ehCacheService.shutdown();
  29 +// }
  30 +//
  31 +// /**
  32 +// * 停止异步执行任务
  33 +// */
  34 +// private void shutdownAsyncManager()
  35 +// {
  36 +// try
  37 +// {
  38 +// logger.info("====关闭后台任务任务线程池111====");
  39 +// AsyncManager.me().shutdown();
  40 +// }
  41 +// catch (Exception e)
  42 +// {
  43 +// logger.error(e.getMessage(), e);
  44 +// }
  45 +// }
  46 +//}
@@ -2,9 +2,9 @@ package com.zhonglai.luhui.smart.feeder.controller; @@ -2,9 +2,9 @@ package com.zhonglai.luhui.smart.feeder.controller;
2 2
3 import com.ruoyi.common.core.domain.AjaxResult; 3 import com.ruoyi.common.core.domain.AjaxResult;
4 import com.zhonglai.luhui.smart.feeder.config.WebSocketClien; 4 import com.zhonglai.luhui.smart.feeder.config.WebSocketClien;
5 -import com.zhonglai.luhui.smart.feeder.dto.SysConfig; 5 +import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
6 import com.zhonglai.luhui.smart.feeder.dto.VeiwType; 6 import com.zhonglai.luhui.smart.feeder.dto.VeiwType;
7 -import com.zhonglai.luhui.smart.feeder.service.CameraService; 7 +import com.zhonglai.luhui.smart.feeder.service.ConfigurationParameterService;
8 import com.zhonglai.luhui.smart.feeder.service.DeviceService; 8 import com.zhonglai.luhui.smart.feeder.service.DeviceService;
9 import com.zhonglai.luhui.smart.feeder.service.FishGroupImageRecognitionService; 9 import com.zhonglai.luhui.smart.feeder.service.FishGroupImageRecognitionService;
10 import io.swagger.annotations.Api; 10 import io.swagger.annotations.Api;
@@ -23,20 +23,15 @@ import java.io.IOException; @@ -23,20 +23,15 @@ import java.io.IOException;
23 @RestController 23 @RestController
24 @RequestMapping("/camera") 24 @RequestMapping("/camera")
25 public class CameraController { 25 public class CameraController {
26 - @Autowired  
27 - private CameraService cameraService;  
28 26
29 @Autowired 27 @Autowired
30 private DeviceService deviceService; 28 private DeviceService deviceService;
31 29
32 - @Autowired  
33 - private FishGroupImageRecognitionService fishGroupImageRecognitionService;  
34 -  
35 @ApiOperation("打开鱼群识别") 30 @ApiOperation("打开鱼群识别")
36 @GetMapping("/open") 31 @GetMapping("/open")
37 public AjaxResult open() 32 public AjaxResult open()
38 { 33 {
39 - fishGroupImageRecognitionService.start(VeiwType.html); 34 +// fishGroupImageRecognitionService.start(VeiwType.html);
40 return AjaxResult.success(); 35 return AjaxResult.success();
41 } 36 }
42 37
@@ -44,7 +39,7 @@ public class CameraController { @@ -44,7 +39,7 @@ public class CameraController {
44 @GetMapping("/close") 39 @GetMapping("/close")
45 public AjaxResult close() 40 public AjaxResult close()
46 { 41 {
47 - fishGroupImageRecognitionService.stop(); 42 +// fishGroupImageRecognitionService.stop();
48 return AjaxResult.success(); 43 return AjaxResult.success();
49 } 44 }
50 45
@@ -56,13 +51,6 @@ public class CameraController { @@ -56,13 +51,6 @@ public class CameraController {
56 return AjaxResult.success(); 51 return AjaxResult.success();
57 } 52 }
58 53
59 - @ApiOperation("设置摄像头usb口编号")  
60 - @GetMapping("/setNumber/{number}")  
61 - public AjaxResult setNumber(@PathVariable Integer number)  
62 - {  
63 - SysConfig.captureNumber = number;  
64 - return AjaxResult.success();  
65 - }  
66 @ApiOperation("打开串口") 54 @ApiOperation("打开串口")
67 @ApiImplicitParams({ 55 @ApiImplicitParams({
68 @ApiImplicitParam(value = "串口名称",name = "portName"), 56 @ApiImplicitParam(value = "串口名称",name = "portName"),
@@ -80,7 +68,6 @@ public class CameraController { @@ -80,7 +68,6 @@ public class CameraController {
80 @ApiOperation("串口发送指令") 68 @ApiOperation("串口发送指令")
81 @GetMapping("/sendSerialData") 69 @GetMapping("/sendSerialData")
82 public AjaxResult sendSerialData(String hexStr) throws IOException { 70 public AjaxResult sendSerialData(String hexStr) throws IOException {
83 - ;  
84 return AjaxResult.success().put("data",deviceService.sendData(hexStr)); 71 return AjaxResult.success().put("data",deviceService.sendData(hexStr));
85 } 72 }
86 73
@@ -89,4 +76,5 @@ public class CameraController { @@ -89,4 +76,5 @@ public class CameraController {
89 public AjaxResult getAllSerial() { 76 public AjaxResult getAllSerial() {
90 return AjaxResult.success().put("data",deviceService.getAllSerial()); 77 return AjaxResult.success().put("data",deviceService.getAllSerial());
91 } 78 }
  79 +
92 } 80 }
1 package com.zhonglai.luhui.smart.feeder.controller; 1 package com.zhonglai.luhui.smart.feeder.controller;
2 2
  3 +import com.ruoyi.common.core.domain.AjaxResult;
  4 +import com.zhonglai.luhui.smart.feeder.dto.ConfigDto;
  5 +import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
  6 +import com.zhonglai.luhui.smart.feeder.dto.VeiwType;
  7 +import com.zhonglai.luhui.smart.feeder.service.ConfigurationParameterService;
  8 +import com.zhonglai.luhui.smart.feeder.service.FishGroupImageRecognitionService;
3 import io.swagger.annotations.Api; 9 import io.swagger.annotations.Api;
4 -import org.springframework.web.bind.annotation.RequestMapping;  
5 -import org.springframework.web.bind.annotation.RestController; 10 +import io.swagger.annotations.ApiOperation;
  11 +import org.ehcache.Cache;
  12 +import org.springframework.beans.factory.annotation.Autowired;
  13 +import org.springframework.web.bind.annotation.*;
  14 +
  15 +import java.util.Iterator;
6 16
7 @Api(tags = "配置") 17 @Api(tags = "配置")
8 @RestController 18 @RestController
9 @RequestMapping("/config") 19 @RequestMapping("/config")
10 public class ConfigController { 20 public class ConfigController {
  21 + @Autowired
  22 + private ConfigurationParameterService configurationParameterService;
  23 + @ApiOperation("获取配置所有参数")
  24 + @GetMapping("/all")
  25 + public AjaxResult all()
  26 + {
  27 + AjaxResult ajaxResult = AjaxResult.success();
  28 + Cache<String, Object> cache = configurationParameterService.getAll();
  29 + Iterator<Cache.Entry<String, Object>> iterator = cache.iterator();
  30 + while (iterator.hasNext()) {
  31 + Cache.Entry<String, Object> entry = iterator.next();
  32 + String key = entry.getKey();
  33 + Object value = entry.getValue();
  34 + // Process the key and value as needed.
  35 + ajaxResult.put(key,value);
  36 + }
  37 + return ajaxResult;
  38 + }
11 39
  40 + @ApiOperation("参数配置")
  41 + @PostMapping("/set")
  42 + public AjaxResult set(@RequestBody ConfigDto configDto)
  43 + {
  44 + configurationParameterService.setConfig(configDto.getConfigurationParameter(),configDto.getValue());
  45 + return AjaxResult.success();
  46 + }
12 } 47 }
  1 +package com.zhonglai.luhui.smart.feeder.dto;
  2 +
  3 +import java.io.Serializable;
  4 +
  5 +public class CacheConfigurationObject extends Object implements Serializable {
  6 + public CacheConfigurationObject()
  7 + {
  8 +
  9 + }
  10 +}
  1 +package com.zhonglai.luhui.smart.feeder.dto;
  2 +
  3 +import lombok.Data;
  4 +
  5 +@Data
  6 +public class ConfigDto {
  7 + private ConfigurationParameter configurationParameter;
  8 + private Object value;
  9 +}
1 package com.zhonglai.luhui.smart.feeder.dto; 1 package com.zhonglai.luhui.smart.feeder.dto;
2 2
3 -public class ConfigurationParameter {  
4 - public Integer captureNumber; //摄像头编号  
5 - public Integer reflectionThreshold; //反光阈值  
6 - public Integer kernelSize; //去噪调整内核大小,用来消除小的物体或噪声  
7 - public Double maxValue; //最大反光阈值  
8 3
  4 +import java.util.ArrayList;
  5 +import java.util.HashMap;
9 6
  7 +public enum ConfigurationParameter {
  8 + ifVeiw(false),//是否显示
  9 + captureNumber(0),//摄像头编号
  10 + reflectionThreshold(100),//反光阈值
  11 + kernelSize(3),//去噪调整内核大小,用来消除小的物体或噪声
  12 + maxValue(255.0), //最大反光阈值
  13 + gear_command (new HashMap<Integer,String>()), //档位对应的指令
  14 + absValue_command (new ArrayList<FishCurveControlCondition>()), //斜率范围对应的档位
  15 + VeiwDto_isFrame(false), //是否显示原图
  16 + VeiwDto_isBinaryImage(false), //是否显示临时图
  17 + VeiwDto_isSize(false), //是否显示面积
  18 + VeiwDto_isAbsValue(false), //是否显示斜率
  19 + absValue(0), //是否显示斜率
  20 + FishGroupImageRecognition(true), //鱼群图像识别是否开启
  21 + FeedingControl(true), //鱼群图像识别投料控制是否开启
  22 + SerialPortConfig(new SerialPortConfig().defaultSerialPortConfig()),//串口配置
  23 + ;
  24 +
  25 + private Object value;
  26 +
  27 + ConfigurationParameter(Object value) {
  28 + this.value = value;
  29 + }
  30 +
  31 + public Object getValue()
  32 + {
  33 + return value;
  34 + }
10 35
11 } 36 }
  1 +package com.zhonglai.luhui.smart.feeder.dto;
  2 +
  3 +/**
  4 + * 斜率范围对应的档位
  5 + */
  6 +public class FishCurveControlCondition {
  7 + private Integer sartAbsValue; //开始斜率
  8 + private Integer gear; //档位
  9 +
  10 + public Integer getGear() {
  11 + return gear;
  12 + }
  13 +
  14 + public void setGear(Integer gear) {
  15 + this.gear = gear;
  16 + }
  17 +
  18 +
  19 + public Integer getSartAbsValue() {
  20 + return sartAbsValue;
  21 + }
  22 +
  23 + public void setSartAbsValue(Integer sartAbsValue) {
  24 + this.sartAbsValue = sartAbsValue;
  25 + }
  26 +}
  1 +package com.zhonglai.luhui.smart.feeder.dto;
  2 +
  3 +import org.ehcache.spi.serialization.Serializer;
  4 +import org.ehcache.spi.serialization.SerializerException;
  5 +
  6 +import java.io.*;
  7 +import java.nio.ByteBuffer;
  8 +
  9 +public class MyCustomSerializer implements Serializer<Object>{
  10 + private final ClassLoader classLoader;
  11 +
  12 + public MyCustomSerializer(ClassLoader classLoader) {
  13 + this.classLoader = classLoader;
  14 + }
  15 +
  16 + @Override
  17 + public ByteBuffer serialize(Object object) throws SerializerException {
  18 + try {
  19 + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  20 + ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
  21 + objectOutputStream.writeObject(object);
  22 + objectOutputStream.flush();
  23 + return ByteBuffer.wrap(byteArrayOutputStream.toByteArray());
  24 + } catch (IOException e) {
  25 + throw new SerializerException(e);
  26 + }
  27 + }
  28 +
  29 + @Override
  30 + public Object read(ByteBuffer byteBuffer) throws ClassNotFoundException, SerializerException {
  31 + try {
  32 + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteBuffer.array());
  33 + ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
  34 + return objectInputStream.readObject();
  35 + } catch (IOException e) {
  36 + throw new SerializerException(e);
  37 + }
  38 + }
  39 +
  40 + @Override
  41 + public boolean equals(Object o, ByteBuffer byteBuffer) throws ClassNotFoundException, SerializerException {
  42 + return o.equals(read(byteBuffer));
  43 + }
  44 +}
  1 +package com.zhonglai.luhui.smart.feeder.dto;
  2 +
  3 +import lombok.Data;
  4 +
  5 +import java.io.Serializable;
  6 +
  7 +/**
  8 + * 串口配置
  9 + */
  10 +@Data
  11 +public class SerialPortConfig implements Serializable {
  12 +
  13 + private static final long serialVersionUID = 3608437294824852022L;
  14 + private String portName; // 串口名称
  15 + private Integer baudrate; // 波特率,用于指定每秒传输的位数。
  16 + private Integer dataBits; // 数据位,表示每个字节的位数。常见的值为 5、6、7、8。
  17 + private Integer stopBits; // 停止位,用于指定每个字节的停止位数。
  18 + private Integer parity; // 校验位,用于验证数据的正确性。常见的值有 NONE(无校验)、ODD(奇校验)、EVEN(偶校验)等。
  19 +
  20 +
  21 + public SerialPortConfig defaultSerialPortConfig()
  22 + {
  23 + portName = "COM6";
  24 + baudrate = 9600;
  25 + dataBits = 8;
  26 + stopBits = 0;
  27 + parity = 0;
  28 + return this;
  29 + }
  30 +}
1 -package com.zhonglai.luhui.smart.feeder.dto;  
2 -  
3 -public class SysConfig {  
4 - public static Integer captureNumber = 0; //摄像头编号  
5 -  
6 - /**  
7 - * 反光阈值(reflectionThreshold)被设置为100。这意味着所有灰度值低于100的像素都会被设置为0(黑色),灰度值大于或等于100的像素都会被设置为255(白色)。如果你的图像中的对象或区域的灰度值接近或低于这个阈值,它们可能会被排除在二值图像之外。尝试调整这个阈值可能有助于改善结果  
8 - */  
9 - public static int reflectionThreshold = 100; // 反光阈值  
10 -  
11 - public static int kernelSize = 3; // 去噪调整内核大小,用来消除小的物体或噪声  
12 -  
13 - public static double maxValue = 255; //最大反光阈值  
14 -  
15 -  
16 -}  
@@ -3,9 +3,10 @@ package com.zhonglai.luhui.smart.feeder.dto; @@ -3,9 +3,10 @@ package com.zhonglai.luhui.smart.feeder.dto;
3 import org.opencv.core.Mat; 3 import org.opencv.core.Mat;
4 4
5 public class VeiwDto { 5 public class VeiwDto {
6 - private Mat frame;  
7 - private Mat binaryImage;  
8 - private Integer size; 6 + private Mat frame; //原始图像
  7 + private Mat binaryImage; //临时图像
  8 + private Integer size; //面积大小
  9 + private Double absValue; //变化的斜率
9 10
10 public VeiwDto(Mat frame, Integer size) { 11 public VeiwDto(Mat frame, Integer size) {
11 this.frame = frame; 12 this.frame = frame;
@@ -18,6 +19,21 @@ public class VeiwDto { @@ -18,6 +19,21 @@ public class VeiwDto {
18 this.size = size; 19 this.size = size;
19 } 20 }
20 21
  22 + public VeiwDto(Mat frame, Mat binaryImage, Integer size, Double absValue) {
  23 + this.frame = frame;
  24 + this.binaryImage = binaryImage;
  25 + this.size = size;
  26 + this.absValue = absValue;
  27 + }
  28 +
  29 + public Double getAbsValue() {
  30 + return absValue;
  31 + }
  32 +
  33 + public void setAbsValue(Double absValue) {
  34 + this.absValue = absValue;
  35 + }
  36 +
21 public VeiwDto() { 37 public VeiwDto() {
22 } 38 }
23 39
1 package com.zhonglai.luhui.smart.feeder.dto; 1 package com.zhonglai.luhui.smart.feeder.dto;
2 2
3 -public class WebSocketVO {  
4 - private int size;  
5 - private String img; 3 +import org.opencv.core.Mat;
6 4
7 - public int getSize() { 5 +import java.io.Serializable;
  6 +
  7 +public class WebSocketVO implements Serializable {
  8 + private static final long serialVersionUID = 1L;
  9 + private String frame; //原始图像
  10 + private String binaryImage; //临时图像
  11 + private Integer size; //面积大小
  12 + private Double absValue; //变化的斜率
  13 +
  14 + private String stateData; //运行数据json字符串
  15 +
  16 + public String getStateData() {
  17 + return stateData;
  18 + }
  19 +
  20 + public void setStateData(String stateData) {
  21 + this.stateData = stateData;
  22 + }
  23 +
  24 + public String getFrame() {
  25 + return frame;
  26 + }
  27 +
  28 + public void setFrame(String frame) {
  29 + this.frame = frame;
  30 + }
  31 +
  32 + public String getBinaryImage() {
  33 + return binaryImage;
  34 + }
  35 +
  36 + public void setBinaryImage(String binaryImage) {
  37 + this.binaryImage = binaryImage;
  38 + }
  39 +
  40 + public Integer getSize() {
8 return size; 41 return size;
9 } 42 }
10 43
11 - public void setSize(int size) { 44 + public void setSize(Integer size) {
12 this.size = size; 45 this.size = size;
13 } 46 }
14 47
15 - public String getImg() {  
16 - return img; 48 + public Double getAbsValue() {
  49 + return absValue;
17 } 50 }
18 51
19 - public void setImg(String img) {  
20 - this.img = img; 52 + public void setAbsValue(Double absValue) {
  53 + this.absValue = absValue;
21 } 54 }
22 } 55 }
@@ -3,12 +3,15 @@ package com.zhonglai.luhui.smart.feeder.opencv; @@ -3,12 +3,15 @@ package com.zhonglai.luhui.smart.feeder.opencv;
3 import com.ruoyi.common.utils.DESUtil; 3 import com.ruoyi.common.utils.DESUtil;
4 import com.zhonglai.luhui.smart.feeder.config.OpenCVConfig; 4 import com.zhonglai.luhui.smart.feeder.config.OpenCVConfig;
5 import com.zhonglai.luhui.smart.feeder.dto.VeiwDto; 5 import com.zhonglai.luhui.smart.feeder.dto.VeiwDto;
  6 +import com.zhonglai.luhui.smart.feeder.service.CameraService;
6 import com.zhonglai.luhui.smart.feeder.service.impl.HtmllVeiwServiceImpl; 7 import com.zhonglai.luhui.smart.feeder.service.impl.HtmllVeiwServiceImpl;
7 import com.zhonglai.luhui.smart.feeder.service.impl.JFrameVeiwServiceImpl; 8 import com.zhonglai.luhui.smart.feeder.service.impl.JFrameVeiwServiceImpl;
8 import org.opencv.core.*; 9 import org.opencv.core.*;
9 import org.opencv.highgui.HighGui; 10 import org.opencv.highgui.HighGui;
10 import org.opencv.videoio.VideoCapture; 11 import org.opencv.videoio.VideoCapture;
11 import org.opencv.imgproc.Imgproc; 12 import org.opencv.imgproc.Imgproc;
  13 +import org.slf4j.Logger;
  14 +import org.slf4j.LoggerFactory;
12 15
13 import java.io.IOException; 16 import java.io.IOException;
14 import java.util.ArrayList; 17 import java.util.ArrayList;
@@ -17,6 +20,7 @@ import java.util.List; @@ -17,6 +20,7 @@ import java.util.List;
17 20
18 21
19 public class OpenCVUtil { 22 public class OpenCVUtil {
  23 + private static final Logger logger = LoggerFactory.getLogger(OpenCVUtil.class);
20 24
21 public static void main(String[] args) { 25 public static void main(String[] args) {
22 System.out.println(DESUtil.decode("5F06AAC657B2E2B287289D25D950A829", "EXU5RUhI1"));; 26 System.out.println(DESUtil.decode("5F06AAC657B2E2B287289D25D950A829", "EXU5RUhI1"));;
@@ -50,12 +54,23 @@ public class OpenCVUtil { @@ -50,12 +54,23 @@ public class OpenCVUtil {
50 54
51 public static VideoCapture readVideoCaptureForVideo(int i) 55 public static VideoCapture readVideoCaptureForVideo(int i)
52 { 56 {
  57 + logger.info("初始化摄像头");
53 // 创建VideoCapture对象 58 // 创建VideoCapture对象
54 - VideoCapture videoCapture = new VideoCapture(i);  
55 - boolean isopen = videoCapture.isOpened();  
56 - System.out.println(isopen); 59 + VideoCapture videoCapture = new VideoCapture();
  60 + try {
  61 + Thread.sleep(1000);
  62 + } catch (InterruptedException e) {
  63 + throw new RuntimeException(e);
  64 + }
  65 + boolean isopen = videoCapture.open(i);
  66 + if(isopen)
  67 + {
  68 + logger.info("打开化摄像头"+i+"成功");
57 return videoCapture; 69 return videoCapture;
58 } 70 }
  71 + logger.info("打开化摄像头"+i+"失败");
  72 + return null;
  73 + }
59 74
60 public static VideoCapture readVideoCaptureForVideo(String videoPath ) 75 public static VideoCapture readVideoCaptureForVideo(String videoPath )
61 { 76 {
1 package com.zhonglai.luhui.smart.feeder.service; 1 package com.zhonglai.luhui.smart.feeder.service;
2 2
3 -import com.zhonglai.luhui.smart.feeder.Main;  
4 -import com.zhonglai.luhui.smart.feeder.dto.SysConfig; 3 +import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
5 import com.zhonglai.luhui.smart.feeder.opencv.OpenCVUtil; 4 import com.zhonglai.luhui.smart.feeder.opencv.OpenCVUtil;
6 import org.opencv.videoio.VideoCapture; 5 import org.opencv.videoio.VideoCapture;
7 -import org.opencv.videoio.Videoio;  
8 import org.slf4j.Logger; 6 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory; 7 import org.slf4j.LoggerFactory;
10 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.beans.factory.annotation.Autowired;
@@ -31,18 +29,46 @@ public class CameraService { @@ -31,18 +29,46 @@ public class CameraService {
31 @Autowired 29 @Autowired
32 private ScheduledExecutorService scheduledExecutorService; 30 private ScheduledExecutorService scheduledExecutorService;
33 31
  32 + @Autowired
  33 + private ConfigurationParameterService configurationParameterService;
  34 +
34 /** 35 /**
35 * 初始化摄像头 36 * 初始化摄像头
36 */ 37 */
37 private void openCapture() 38 private void openCapture()
38 { 39 {
39 - videoCapture = OpenCVUtil.readVideoCaptureForVideo(SysConfig.captureNumber);  
40 -// videoCapture.set(Videoio.CAP_PROP_FRAME_WIDTH,640);  
41 -// videoCapture.set(Videoio.CAP_PROP_FRAME_HEIGHT,480);  
42 -// videoCapture.set(Videoio.CAP_PROP_FOURCC, 0x32595559);  
43 -// videoCapture.set(Videoio.CAP_PROP_FPS, 25); 40 + videoCapture = OpenCVUtil.readVideoCaptureForVideo((Integer) configurationParameterService.getConfig(ConfigurationParameter.captureNumber));
44 monitorCapture(); 41 monitorCapture();
45 - logger.info("初始化摄像头"); 42 +
  43 +// if (!videoIsOpen)
  44 +// {
  45 +// logger.info("摄像头打开失败尝试自动识别流程");
  46 +// int i=0;
  47 +// int j =0;
  48 +// while (!videoIsOpen && i<10)
  49 +// {
  50 +// logger.info("等待3秒");
  51 +// try {
  52 +// Thread.sleep(1000);
  53 +// } catch (InterruptedException e) {
  54 +// throw new RuntimeException(e);
  55 +// }
  56 +// logger.info("开始尝试:"+i);
  57 +// videoCapture = OpenCVUtil.readVideoCaptureForVideo(i);
  58 +// monitorCapture();
  59 +// if(!videoIsOpen && j>=3)
  60 +// {
  61 +// j=0;
  62 +// i++;
  63 +// }
  64 +// j++;
  65 +// }
  66 +// if(!videoIsOpen)
  67 +// {
  68 +// logger.info("尝试0-10都没有成功退出尝试");
  69 +// }
  70 +//
  71 +// }
46 } 72 }
47 73
48 /** 74 /**
@@ -60,11 +86,11 @@ public class CameraService { @@ -60,11 +86,11 @@ public class CameraService {
60 private void monitorCapture() 86 private void monitorCapture()
61 { 87 {
62 // 检查视频是否成功打开 88 // 检查视频是否成功打开
63 - if (videoCapture.isOpened()) { 89 + if (null !=videoCapture && videoCapture.isOpened()) {
64 videoIsOpen = true; 90 videoIsOpen = true;
65 return; 91 return;
66 } 92 }
67 - System.out.println("无法打开视频文件"+SysConfig.captureNumber); 93 + System.out.println("无法打开视频文件"+ configurationParameterService.getConfig(ConfigurationParameter.captureNumber));
68 videoIsOpen = false; 94 videoIsOpen = false;
69 } 95 }
70 96
@@ -108,4 +134,9 @@ public class CameraService { @@ -108,4 +134,9 @@ public class CameraService {
108 return videoCapture; 134 return videoCapture;
109 } 135 }
110 136
  137 + public Boolean getVideoIsOpen()
  138 + {
  139 + return videoIsOpen;
  140 + }
  141 +
111 } 142 }
1 package com.zhonglai.luhui.smart.feeder.service; 1 package com.zhonglai.luhui.smart.feeder.service;
2 2
  3 +import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
  4 +import org.ehcache.Cache;
  5 +import org.springframework.beans.factory.annotation.Autowired;
3 import org.springframework.stereotype.Service; 6 import org.springframework.stereotype.Service;
4 7
  8 +import javax.annotation.PostConstruct;
  9 +
5 /** 10 /**
6 * 配置参数 11 * 配置参数
7 */ 12 */
8 @Service 13 @Service
9 public class ConfigurationParameterService { 14 public class ConfigurationParameterService {
  15 + @Autowired
  16 + private EhCacheService ehCacheService;
  17 +
  18 + @PostConstruct
  19 + public void initConfigurationParameter()
  20 + {
  21 + for(ConfigurationParameter configurationParameter:ConfigurationParameter.values())
  22 + {
  23 + if(null ==ehCacheService.readFromCache( configurationParameter))
  24 + {
  25 + ehCacheService.writeToDiske(configurationParameter,configurationParameter.getValue());
  26 + }
  27 + }
  28 + }
  29 +
  30 + public Cache<String, Object> getAll()
  31 + {
  32 + return ehCacheService.getMyCache();
  33 + }
  34 +
  35 + public void setConfig(ConfigurationParameter configurationParameter,Object value)
  36 + {
  37 + ehCacheService.writeToDiske(configurationParameter,value);
  38 + }
10 39
  40 + public Object getConfig(ConfigurationParameter configurationParameter)
  41 + {
  42 + return ehCacheService.readFromCache(configurationParameter);
  43 + }
11 } 44 }
1 package com.zhonglai.luhui.smart.feeder.service; 1 package com.zhonglai.luhui.smart.feeder.service;
2 2
3 -import com.sun.deploy.net.HttpResponse;  
4 -import com.zhonglai.luhui.smart.feeder.util.serial.GlobalCache;  
5 -import com.zhonglai.luhui.smart.feeder.util.serial.SerialResquest; 3 +import com.ruoyi.common.utils.GsonConstructor;
  4 +import com.ruoyi.common.utils.StringUtils;
  5 +import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
  6 +import com.zhonglai.luhui.smart.feeder.dto.FishCurveControlCondition;
  7 +import com.zhonglai.luhui.smart.feeder.dto.SerialPortConfig;
6 import com.zhonglai.luhui.smart.feeder.util.serial.SerialTool; 8 import com.zhonglai.luhui.smart.feeder.util.serial.SerialTool;
7 -import org.opencv.core.Core;  
8 -import org.opencv.core.Mat;  
9 -import org.opencv.highgui.HighGui;  
10 -import org.opencv.videoio.VideoCapture;  
11 import org.slf4j.Logger; 9 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory; 10 import org.slf4j.LoggerFactory;
  11 +import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.stereotype.Service; 12 import org.springframework.stereotype.Service;
14 import purejavacomm.SerialPort; 13 import purejavacomm.SerialPort;
15 import purejavacomm.SerialPortEvent; 14 import purejavacomm.SerialPortEvent;
16 -import purejavacomm.SerialPortEventListener;  
17 15
18 -import javax.servlet.http.HttpServletResponse;  
19 -import javax.websocket.Session; 16 +import javax.annotation.PostConstruct;
20 import java.io.IOException; 17 import java.io.IOException;
21 -import java.util.ArrayList;  
22 -import java.util.Map; 18 +import java.util.*;
23 import java.util.concurrent.BlockingQueue; 19 import java.util.concurrent.BlockingQueue;
24 import java.util.concurrent.LinkedBlockingQueue; 20 import java.util.concurrent.LinkedBlockingQueue;
  21 +import java.util.concurrent.ScheduledExecutorService;
  22 +import java.util.concurrent.TimeUnit;
25 23
26 /** 24 /**
27 * 设备管理 25 * 设备管理
@@ -43,12 +41,57 @@ public class DeviceService { @@ -43,12 +41,57 @@ public class DeviceService {
43 private Double backSlope; //斜率 41 private Double backSlope; //斜率
44 private Double slopeDifference; //斜率差值 42 private Double slopeDifference; //斜率差值
45 43
46 - public void controlDevice(double area) 44 + private Double absValue; //斜率差值的绝对值
  45 +
  46 + private Integer nowGear; //当前档位
  47 +
  48 + @Autowired
  49 + private ConfigurationParameterService configurationParameterService;
  50 +
  51 + @Autowired
  52 + private ScheduledExecutorService scheduledExecutorService;
  53 +
  54 + @Autowired
  55 + private EhCacheService ehCacheService;
  56 +
  57 + @PostConstruct
  58 + public void run()
  59 + {
  60 + //投料控制
  61 + scheduledExecutorService.scheduleWithFixedDelay(() -> {
  62 + if (((Boolean)ehCacheService.readFromCache(ConfigurationParameter.FeedingControl))) {
  63 + Map<Integer,String> map = (Map<Integer, String>) ehCacheService.readFromCache(ConfigurationParameter.gear_command);
  64 + if(null != map && StringUtils.isNotEmpty( map.get(nowGear)))
  65 + {
  66 + send485SerialData(map.get(nowGear));
  67 + }
  68 + }
  69 + },1,1, TimeUnit.SECONDS);
  70 + }
  71 +
  72 + public String getState()
  73 + {
  74 + Map<String,Object> map = new HashMap<>();
  75 + map.put("backArea",backArea);
  76 + map.put("slope",slope);
  77 + map.put("backSlope",backSlope);
  78 + map.put("slopeDifference",slopeDifference);
  79 + map.put("absValue",absValue);
  80 + map.put("nowGear",nowGear);
  81 + return GsonConstructor.get().toJson(map);
  82 + }
  83 +
  84 + /**
  85 + * 根据面积计算斜率
  86 + * @param area
  87 + * @return
  88 + */
  89 + public double controlDevice(double area)
47 { 90 {
48 if(null == backArea ) 91 if(null == backArea )
49 { 92 {
50 backArea = area; 93 backArea = area;
51 - return; 94 + return 0;
52 } 95 }
53 96
54 slope = area-backArea; 97 slope = area-backArea;
@@ -59,8 +102,57 @@ public class DeviceService { @@ -59,8 +102,57 @@ public class DeviceService {
59 102
60 slopeDifference = slope-backSlope; 103 slopeDifference = slope-backSlope;
61 104
62 - double absValue = Math.abs(slopeDifference); 105 + absValue = Math.abs(slopeDifference);
  106 +
  107 + nowGear = getGearFromAbsValue();
  108 + return absValue;
  109 + }
  110 +
  111 + private void send485SerialData(String commd)
  112 + {
  113 + if(null == serialPort)
  114 + {
  115 + openSerialPort();
  116 + }
  117 +
  118 + try {
  119 + sendData(commd);
  120 + } catch (IOException e) {
  121 + logger.error("串口指令发送错误",e);
  122 + }
  123 + }
  124 +
  125 + /**
  126 + * 根据斜率计算档位
  127 + * @return
  128 + */
  129 + private Integer getGearFromAbsValue()
  130 + {
  131 + Integer gear = null;
  132 + List<FishCurveControlCondition> list = (List<FishCurveControlCondition>) ehCacheService.readFromCache(ConfigurationParameter.absValue_command);
  133 + if(null != list && list.size() != 0)
  134 + {
  135 + list.sort(Comparator.comparing(FishCurveControlCondition::getSartAbsValue));//以 sartAbsValue 升序排序
63 136
  137 + for(FishCurveControlCondition fishCurveControlCondition:list) //根据斜率找到档位
  138 + {
  139 + if(absValue>=fishCurveControlCondition.getSartAbsValue()) //向下查找
  140 + {
  141 + gear = fishCurveControlCondition.getGear();
  142 + }
  143 + }
  144 + }
  145 + return gear;
  146 + }
  147 +
  148 + public void openSerialPort()
  149 + {
  150 + SerialPortConfig serialPortConfig = (SerialPortConfig) configurationParameterService.getConfig(ConfigurationParameter.SerialPortConfig);
  151 + try {
  152 + openSerialPort(serialPortConfig.getPortName(),serialPortConfig.getBaudrate(),serialPortConfig.getDataBits(),serialPortConfig.getStopBits(),serialPortConfig.getParity());
  153 + } catch (Exception e) {
  154 + throw new RuntimeException(e);
  155 + }
64 } 156 }
65 157
66 158
1 package com.zhonglai.luhui.smart.feeder.service; 1 package com.zhonglai.luhui.smart.feeder.service;
2 2
  3 +import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
3 import org.ehcache.Cache; 4 import org.ehcache.Cache;
4 import org.ehcache.CacheManager; 5 import org.ehcache.CacheManager;
5 import org.ehcache.config.CacheConfiguration; 6 import org.ehcache.config.CacheConfiguration;
6 import org.ehcache.config.ResourcePools; 7 import org.ehcache.config.ResourcePools;
7 import org.ehcache.config.builders.CacheConfigurationBuilder; 8 import org.ehcache.config.builders.CacheConfigurationBuilder;
8 import org.ehcache.config.builders.CacheManagerBuilder; 9 import org.ehcache.config.builders.CacheManagerBuilder;
9 -import org.ehcache.config.builders.ExpiryPolicyBuilder;  
10 import org.ehcache.config.builders.ResourcePoolsBuilder; 10 import org.ehcache.config.builders.ResourcePoolsBuilder;
11 import org.ehcache.config.units.MemoryUnit; 11 import org.ehcache.config.units.MemoryUnit;
  12 +import org.ehcache.impl.serialization.PlainJavaSerializer;
12 import org.springframework.beans.factory.annotation.Value; 13 import org.springframework.beans.factory.annotation.Value;
13 import org.springframework.stereotype.Service; 14 import org.springframework.stereotype.Service;
14 15
@@ -36,6 +37,13 @@ public class EhCacheService { @@ -36,6 +37,13 @@ public class EhCacheService {
36 cacheManager = CacheManagerBuilder.newCacheManagerBuilder() 37 cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
37 .with(CacheManagerBuilder.persistence(new File(cacheFilePath))) 38 .with(CacheManagerBuilder.persistence(new File(cacheFilePath)))
38 .build(true); 39 .build(true);
  40 +
  41 + if (cacheManager.getRuntimeConfiguration().getCacheConfigurations().containsKey(MY_CACHE))
  42 + {
  43 + // 缓存对象存在,直接读取
  44 + myCache = cacheManager.getCache(MY_CACHE, String.class, Object.class);
  45 + }else {
  46 +
39 // 指定缓存的存储形式,采用多级缓存,并开启缓存持久化操作 47 // 指定缓存的存储形式,采用多级缓存,并开启缓存持久化操作
40 ResourcePools resourcePools = ResourcePoolsBuilder.newResourcePoolsBuilder() 48 ResourcePools resourcePools = ResourcePoolsBuilder.newResourcePoolsBuilder()
41 .heap(1, MemoryUnit.MB) 49 .heap(1, MemoryUnit.MB)
@@ -44,22 +52,34 @@ public class EhCacheService { @@ -44,22 +52,34 @@ public class EhCacheService {
44 // 封装缓存配置对象,指定了键值类型、指定了使用TTL与TTI联合的过期淘汰策略 52 // 封装缓存配置对象,指定了键值类型、指定了使用TTL与TTI联合的过期淘汰策略
45 CacheConfiguration<String, Object> cacheConfiguration = 53 CacheConfiguration<String, Object> cacheConfiguration =
46 CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Object.class, resourcePools) 54 CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Object.class, resourcePools)
  55 + .withValueSerializer(new PlainJavaSerializer<>(this.getClass().getClassLoader()))
47 .build(); 56 .build();
  57 +
48 // 使用给定的配置参数,创建指定名称的缓存对象 58 // 使用给定的配置参数,创建指定名称的缓存对象
49 myCache = cacheManager.createCache(MY_CACHE, cacheConfiguration); 59 myCache = cacheManager.createCache(MY_CACHE, cacheConfiguration);
50 } 60 }
  61 + }
51 62
52 - public void writeToCache(String key, Object value) {  
53 - myCache.put(key, value); 63 + public void writeToCache(ConfigurationParameter key, Object value) {
  64 + myCache.put(key.name(), value);
54 } 65 }
55 66
56 - public Object readFromCache(String key) {  
57 - return myCache.get(key); 67 + public Object readFromCache(ConfigurationParameter key) {
  68 + return myCache.get(key.name());
58 } 69 }
59 70
60 - public Object writeToDiske(String key, Object value) {  
61 - myCache.put(key, value);  
62 - return cacheManager.getCache(MY_CACHE,String.class,Object.class).get(key); // 强制将数据同步到磁盘 71 + public Object writeToDiske(ConfigurationParameter key, Object value) {
  72 + myCache.put(key.name(), value);
  73 + return cacheManager.getCache(MY_CACHE,String.class,Object.class).get(key.name()); // 强制将数据同步到磁盘
63 } 74 }
64 75
  76 + public Cache<String, Object> getMyCache() {
  77 + return myCache;
  78 + }
  79 +
  80 + public void shutdown() {
  81 + if (cacheManager != null) {
  82 + cacheManager.close();
  83 + }
  84 + }
65 } 85 }
1 package com.zhonglai.luhui.smart.feeder.service; 1 package com.zhonglai.luhui.smart.feeder.service;
2 2
3 -import com.zhonglai.luhui.smart.feeder.dto.SysConfig; 3 +import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
4 import com.zhonglai.luhui.smart.feeder.dto.VeiwDto; 4 import com.zhonglai.luhui.smart.feeder.dto.VeiwDto;
5 import com.zhonglai.luhui.smart.feeder.dto.VeiwType; 5 import com.zhonglai.luhui.smart.feeder.dto.VeiwType;
6 import com.zhonglai.luhui.smart.feeder.opencv.OpenCVUtil; 6 import com.zhonglai.luhui.smart.feeder.opencv.OpenCVUtil;
7 import com.zhonglai.luhui.smart.feeder.service.impl.HtmllVeiwServiceImpl; 7 import com.zhonglai.luhui.smart.feeder.service.impl.HtmllVeiwServiceImpl;
8 import com.zhonglai.luhui.smart.feeder.service.impl.JFrameVeiwServiceImpl; 8 import com.zhonglai.luhui.smart.feeder.service.impl.JFrameVeiwServiceImpl;
  9 +import io.swagger.models.auth.In;
9 import org.opencv.core.Mat; 10 import org.opencv.core.Mat;
10 import org.opencv.core.MatOfPoint; 11 import org.opencv.core.MatOfPoint;
11 import org.opencv.core.Scalar; 12 import org.opencv.core.Scalar;
@@ -17,6 +18,7 @@ import org.slf4j.LoggerFactory; @@ -17,6 +18,7 @@ import org.slf4j.LoggerFactory;
17 import org.springframework.beans.factory.annotation.Autowired; 18 import org.springframework.beans.factory.annotation.Autowired;
18 import org.springframework.stereotype.Service; 19 import org.springframework.stereotype.Service;
19 20
  21 +import javax.annotation.PostConstruct;
20 import java.util.ArrayList; 22 import java.util.ArrayList;
21 import java.util.Arrays; 23 import java.util.Arrays;
22 import java.util.List; 24 import java.util.List;
@@ -35,35 +37,64 @@ public class FishGroupImageRecognitionService { @@ -35,35 +37,64 @@ public class FishGroupImageRecognitionService {
35 37
36 private DisplayVeiwService dsplayVeiwService; 38 private DisplayVeiwService dsplayVeiwService;
37 39
38 - private boolean isRun;  
39 40
40 @Autowired 41 @Autowired
41 private ScheduledExecutorService scheduledExecutorService; 42 private ScheduledExecutorService scheduledExecutorService;
42 43
  44 + @Autowired
  45 + private ConfigurationParameterService configurationParameterService;
  46 +
  47 + @Autowired
  48 + private DeviceService deviceService;
  49 +
  50 + @Autowired
  51 + private EhCacheService ehCacheService;
  52 +
  53 + private static Boolean isRun = false;
  54 +
  55 +
  56 + @PostConstruct
  57 + public void run()
  58 + {
  59 + scheduledExecutorService.scheduleWithFixedDelay(() -> {
  60 + if (!isRun)
  61 + {
  62 + start(VeiwType.html);
  63 + }
  64 + },1,1,TimeUnit.SECONDS);
  65 +
  66 + }
43 67
44 public void start(VeiwType veiwType) 68 public void start(VeiwType veiwType)
45 { 69 {
  70 + if(cameraService.getVideoIsOpen()) //摄像头打开才能识别
  71 + {
46 isRun = true; 72 isRun = true;
  73 + ehCacheService.writeToDiske(ConfigurationParameter.FishGroupImageRecognition,true);
47 switch (veiwType) 74 switch (veiwType)
48 { 75 {
49 case html: 76 case html:
50 - dsplayVeiwService = new HtmllVeiwServiceImpl(); 77 + dsplayVeiwService = new HtmllVeiwServiceImpl(configurationParameterService);
51 break; 78 break;
52 case jfram: 79 case jfram:
53 - dsplayVeiwService = new JFrameVeiwServiceImpl(); 80 + dsplayVeiwService = new JFrameVeiwServiceImpl(configurationParameterService);
54 break; 81 break;
55 default: 82 default:
56 - dsplayVeiwService = new HtmllVeiwServiceImpl(); 83 + dsplayVeiwService = new HtmllVeiwServiceImpl(configurationParameterService);
57 break; 84 break;
58 } 85 }
59 VideoCapture videoCapture = cameraService.getVideoCapture(); 86 VideoCapture videoCapture = cameraService.getVideoCapture();
60 brightnessIdentifyFishRegion(videoCapture); 87 brightnessIdentifyFishRegion(videoCapture);
  88 + }else {
  89 + logger.info("摄像头未打开");
  90 + }
61 } 91 }
62 92
63 public void stop() 93 public void stop()
64 { 94 {
65 - isRun = false; 95 + ehCacheService.writeToDiske(ConfigurationParameter.FishGroupImageRecognition,false);
66 cameraService.close(); 96 cameraService.close();
  97 + isRun = false;
67 } 98 }
68 99
69 /** 100 /**
@@ -73,7 +104,7 @@ public class FishGroupImageRecognitionService { @@ -73,7 +104,7 @@ public class FishGroupImageRecognitionService {
73 */ 104 */
74 private MatOfPoint getDefaultMatOfPoint(Mat previousFrame) 105 private MatOfPoint getDefaultMatOfPoint(Mat previousFrame)
75 { 106 {
76 - Mat firstBinaryImage = waterBybinary(previousFrame,SysConfig.reflectionThreshold); 107 + Mat firstBinaryImage = waterBybinary(previousFrame,(Integer) configurationParameterService.getConfig(ConfigurationParameter.reflectionThreshold));
77 // 绘制白色区域的轮廓 108 // 绘制白色区域的轮廓
78 List<MatOfPoint> contours = new ArrayList<>(); 109 List<MatOfPoint> contours = new ArrayList<>();
79 Mat hierarchy = new Mat(); 110 Mat hierarchy = new Mat();
@@ -112,11 +143,11 @@ public class FishGroupImageRecognitionService { @@ -112,11 +143,11 @@ public class FishGroupImageRecognitionService {
112 143
113 // 逐帧处理视频 144 // 逐帧处理视频
114 Mat frame = new Mat(); 145 Mat frame = new Mat();
115 - scheduledExecutorService.schedule(() -> {  
116 - while (isRun && videoCapture.read(frame)) { 146 + scheduledExecutorService.scheduleWithFixedDelay(() -> {
  147 + if (((Boolean)ehCacheService.readFromCache(ConfigurationParameter.FishGroupImageRecognition)) && videoCapture.read(frame)) {
117 identify(frame,largestContour); 148 identify(frame,largestContour);
118 } 149 }
119 - },0, TimeUnit.SECONDS); 150 + },0,1, TimeUnit.SECONDS);
120 151
121 } 152 }
122 153
@@ -152,9 +183,17 @@ public class FishGroupImageRecognitionService { @@ -152,9 +183,17 @@ public class FishGroupImageRecognitionService {
152 Imgproc.drawContours(frame, contours, -1, new Scalar(0, 0, 255), 2); 183 Imgproc.drawContours(frame, contours, -1, new Scalar(0, 0, 255), 2);
153 Imgproc.drawContours(frame, Arrays.asList(new MatOfPoint[]{largestContour}), 0, new Scalar(0, 255, 0), 2); 184 Imgproc.drawContours(frame, Arrays.asList(new MatOfPoint[]{largestContour}), 0, new Scalar(0, 255, 0), 2);
154 185
  186 + //计算斜率
  187 + double absValue = deviceService.controlDevice(area);
  188 + ehCacheService.writeToCache(ConfigurationParameter.absValue,absValue);
  189 +
155 // 显示图像 190 // 显示图像
156 // 在图像上显示结果 191 // 在图像上显示结果
157 - dsplayVeiwService.veiw(new VeiwDto(frame,binaryImage,new Double(area).intValue())); 192 + if((Boolean)ehCacheService.readFromCache(ConfigurationParameter.ifVeiw))
  193 + {
  194 + dsplayVeiwService.veiw(new VeiwDto(frame,binaryImage,new Double(area).intValue(),absValue));
  195 + }
  196 +
158 } 197 }
159 198
160 /** 199 /**
@@ -180,7 +219,6 @@ public class FishGroupImageRecognitionService { @@ -180,7 +219,6 @@ public class FishGroupImageRecognitionService {
180 if(-1 != maxAreaIndex) 219 if(-1 != maxAreaIndex)
181 { 220 {
182 double area = Imgproc.contourArea(contours.get(maxAreaIndex)); 221 double area = Imgproc.contourArea(contours.get(maxAreaIndex));
183 - maxArea = maxArea-area;  
184 222
185 contours.remove(maxAreaIndex); 223 contours.remove(maxAreaIndex);
186 } 224 }
@@ -195,7 +233,7 @@ public class FishGroupImageRecognitionService { @@ -195,7 +233,7 @@ public class FishGroupImageRecognitionService {
195 * @param frame 233 * @param frame
196 * @return 234 * @return
197 */ 235 */
198 - public static Mat waterBybinary(Mat frame,int reflectionThreshold) { 236 + public Mat waterBybinary(Mat frame,int reflectionThreshold) {
199 // 将加载的图像转换为灰度图像,以便进行亮度或反光的分析 237 // 将加载的图像转换为灰度图像,以便进行亮度或反光的分析
200 Mat grayImage = new Mat(); 238 Mat grayImage = new Mat();
201 Imgproc.cvtColor(frame, grayImage, Imgproc.COLOR_BGR2GRAY); 239 Imgproc.cvtColor(frame, grayImage, Imgproc.COLOR_BGR2GRAY);
@@ -203,10 +241,10 @@ public class FishGroupImageRecognitionService { @@ -203,10 +241,10 @@ public class FishGroupImageRecognitionService {
203 // 检测反光 241 // 检测反光
204 Mat binaryImage = new Mat(); 242 Mat binaryImage = new Mat();
205 243
206 - Imgproc.threshold(grayImage, binaryImage, reflectionThreshold, SysConfig.maxValue, Imgproc.THRESH_BINARY); 244 + Imgproc.threshold(grayImage, binaryImage, reflectionThreshold, (Double) configurationParameterService.getConfig(ConfigurationParameter.maxValue), Imgproc.THRESH_BINARY);
207 245
208 // 进行形态学操作,去除噪点 246 // 进行形态学操作,去除噪点
209 - Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(SysConfig.kernelSize, SysConfig.kernelSize)); 247 + Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size((Integer) configurationParameterService.getConfig(ConfigurationParameter.kernelSize),(Integer) configurationParameterService.getConfig(ConfigurationParameter.kernelSize)));
210 Imgproc.morphologyEx(binaryImage, binaryImage, Imgproc.MORPH_OPEN, kernel); 248 Imgproc.morphologyEx(binaryImage, binaryImage, Imgproc.MORPH_OPEN, kernel);
211 249
212 return binaryImage; 250 return binaryImage;
1 package com.zhonglai.luhui.smart.feeder.service; 1 package com.zhonglai.luhui.smart.feeder.service;
2 2
3 import com.ruoyi.common.utils.GsonConstructor; 3 import com.ruoyi.common.utils.GsonConstructor;
  4 +import com.ruoyi.common.utils.StringUtils;
4 import com.zhonglai.luhui.smart.feeder.config.WebSocketClien; 5 import com.zhonglai.luhui.smart.feeder.config.WebSocketClien;
5 import com.zhonglai.luhui.smart.feeder.dto.WebSocketVO; 6 import com.zhonglai.luhui.smart.feeder.dto.WebSocketVO;
6 import org.slf4j.Logger; 7 import org.slf4j.Logger;
7 import org.slf4j.LoggerFactory; 8 import org.slf4j.LoggerFactory;
  9 +import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.stereotype.Component; 10 import org.springframework.stereotype.Component;
9 11
10 import javax.websocket.*; 12 import javax.websocket.*;
@@ -22,9 +24,14 @@ import java.util.concurrent.CopyOnWriteArraySet; @@ -22,9 +24,14 @@ import java.util.concurrent.CopyOnWriteArraySet;
22 public class WebSocketSever { 24 public class WebSocketSever {
23 private static final Logger log = LoggerFactory.getLogger(WebSocketSever.class); 25 private static final Logger log = LoggerFactory.getLogger(WebSocketSever.class);
24 26
  27 + @Autowired
  28 + private DeviceService deviceService;
  29 +
25 // 与某个客户端的连接会话,需要通过它来给客户端发送数据 30 // 与某个客户端的连接会话,需要通过它来给客户端发送数据
26 private Session session; 31 private Session session;
27 32
  33 + private Boolean runState = false;
  34 +
28 /** 35 /**
29 * 建立WebSocket连接 36 * 建立WebSocket连接
30 * 37 *
@@ -69,6 +76,16 @@ public class WebSocketSever { @@ -69,6 +76,16 @@ public class WebSocketSever {
69 @OnMessage 76 @OnMessage
70 public void onMessage(String message) { 77 public void onMessage(String message) {
71 log.info("收到客户端发来的消息:{}", message); 78 log.info("收到客户端发来的消息:{}", message);
  79 + if(StringUtils.isNotEmpty(message))
  80 + {
  81 + switch (message)
  82 + {
  83 + case "openRunState":
  84 + runState = true;
  85 + case "closeRunState":
  86 + runState = false;
  87 + }
  88 + }
72 } 89 }
73 90
74 /** 91 /**
@@ -93,6 +110,10 @@ public class WebSocketSever { @@ -93,6 +110,10 @@ public class WebSocketSever {
93 */ 110 */
94 public void sendWebSocketVO(WebSocketVO webSocketVO) { 111 public void sendWebSocketVO(WebSocketVO webSocketVO) {
95 try { 112 try {
  113 + if(runState)
  114 + {
  115 + webSocketVO.setStateData(deviceService.getState());
  116 + }
96 session.getBasicRemote().sendText(GsonConstructor.get().toJson(webSocketVO)); 117 session.getBasicRemote().sendText(GsonConstructor.get().toJson(webSocketVO));
97 } catch (IOException e) { 118 } catch (IOException e) {
98 log.error("推送消息到指定用户发生错误:" + e.getMessage(), e); 119 log.error("推送消息到指定用户发生错误:" + e.getMessage(), e);
@@ -2,8 +2,10 @@ package com.zhonglai.luhui.smart.feeder.service.impl; @@ -2,8 +2,10 @@ package com.zhonglai.luhui.smart.feeder.service.impl;
2 2
3 import com.ruoyi.common.utils.sign.Base64; 3 import com.ruoyi.common.utils.sign.Base64;
4 import com.zhonglai.luhui.smart.feeder.config.WebSocketClien; 4 import com.zhonglai.luhui.smart.feeder.config.WebSocketClien;
  5 +import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
5 import com.zhonglai.luhui.smart.feeder.dto.VeiwDto; 6 import com.zhonglai.luhui.smart.feeder.dto.VeiwDto;
6 import com.zhonglai.luhui.smart.feeder.dto.WebSocketVO; 7 import com.zhonglai.luhui.smart.feeder.dto.WebSocketVO;
  8 +import com.zhonglai.luhui.smart.feeder.service.ConfigurationParameterService;
7 import com.zhonglai.luhui.smart.feeder.service.DisplayVeiwService; 9 import com.zhonglai.luhui.smart.feeder.service.DisplayVeiwService;
8 import com.zhonglai.luhui.smart.feeder.service.WebSocketSever; 10 import com.zhonglai.luhui.smart.feeder.service.WebSocketSever;
9 import org.apache.commons.lang3.ArrayUtils; 11 import org.apache.commons.lang3.ArrayUtils;
@@ -20,7 +22,11 @@ import java.io.InputStream; @@ -20,7 +22,11 @@ import java.io.InputStream;
20 22
21 public class HtmllVeiwServiceImpl implements DisplayVeiwService { 23 public class HtmllVeiwServiceImpl implements DisplayVeiwService {
22 24
23 - private boolean isRun; 25 + private ConfigurationParameterService configurationParameterService;
  26 +
  27 + public HtmllVeiwServiceImpl(ConfigurationParameterService configurationParameterService) {
  28 + this.configurationParameterService = configurationParameterService;
  29 + }
24 30
25 /** 31 /**
26 * Mat转换成BufferedImage 32 * Mat转换成BufferedImage
@@ -123,10 +129,24 @@ public class HtmllVeiwServiceImpl implements DisplayVeiwService { @@ -123,10 +129,24 @@ public class HtmllVeiwServiceImpl implements DisplayVeiwService {
123 @Override 129 @Override
124 public void veiw(VeiwDto veiwDto) { 130 public void veiw(VeiwDto veiwDto) {
125 try { 131 try {
126 - String str = matToString(veiwDto.getFrame(),"jpg");  
127 WebSocketVO webSocketVO = new WebSocketVO(); 132 WebSocketVO webSocketVO = new WebSocketVO();
128 - webSocketVO.setImg(str); 133 +
  134 + if((boolean)configurationParameterService.getConfig(ConfigurationParameter.VeiwDto_isFrame))
  135 + {
  136 + webSocketVO.setFrame(matToString(veiwDto.getFrame(),"jpg"));
  137 + }
  138 + if((boolean)configurationParameterService.getConfig(ConfigurationParameter.VeiwDto_isBinaryImage))
  139 + {
  140 + webSocketVO.setBinaryImage(matToString(veiwDto.getBinaryImage(),"jpg"));
  141 + }
  142 + if((boolean)configurationParameterService.getConfig(ConfigurationParameter.VeiwDto_isSize))
  143 + {
129 webSocketVO.setSize(veiwDto.getSize()); 144 webSocketVO.setSize(veiwDto.getSize());
  145 + }
  146 + if((boolean)configurationParameterService.getConfig(ConfigurationParameter.VeiwDto_isAbsValue))
  147 + {
  148 + webSocketVO.setAbsValue(veiwDto.getAbsValue());
  149 + }
130 for (WebSocketSever webSocketSever:WebSocketClien.webSocketSet) 150 for (WebSocketSever webSocketSever:WebSocketClien.webSocketSet)
131 { 151 {
132 webSocketSever.sendWebSocketVO(webSocketVO); 152 webSocketSever.sendWebSocketVO(webSocketVO);
1 package com.zhonglai.luhui.smart.feeder.service.impl; 1 package com.zhonglai.luhui.smart.feeder.service.impl;
2 2
3 import com.zhonglai.luhui.smart.feeder.draw.FishRegionPanel; 3 import com.zhonglai.luhui.smart.feeder.draw.FishRegionPanel;
  4 +import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
4 import com.zhonglai.luhui.smart.feeder.dto.VeiwDto; 5 import com.zhonglai.luhui.smart.feeder.dto.VeiwDto;
  6 +import com.zhonglai.luhui.smart.feeder.service.ConfigurationParameterService;
5 import com.zhonglai.luhui.smart.feeder.service.DisplayVeiwService; 7 import com.zhonglai.luhui.smart.feeder.service.DisplayVeiwService;
6 import com.zhonglai.luhui.smart.feeder.util.OpenCVUtils; 8 import com.zhonglai.luhui.smart.feeder.util.OpenCVUtils;
7 import org.opencv.core.Mat; 9 import org.opencv.core.Mat;
@@ -11,6 +13,13 @@ import java.awt.*; @@ -11,6 +13,13 @@ import java.awt.*;
11 import java.awt.image.BufferedImage; 13 import java.awt.image.BufferedImage;
12 14
13 public class JFrameVeiwServiceImpl implements DisplayVeiwService { 15 public class JFrameVeiwServiceImpl implements DisplayVeiwService {
  16 +
  17 + private ConfigurationParameterService configurationParameterService;
  18 +
  19 + public JFrameVeiwServiceImpl(ConfigurationParameterService configurationParameterService) {
  20 + this.configurationParameterService = configurationParameterService;
  21 + }
  22 +
14 private static FishRegionPanel fishRegionPanel; 23 private static FishRegionPanel fishRegionPanel;
15 24
16 public JFrameVeiwServiceImpl() 25 public JFrameVeiwServiceImpl()
@@ -28,19 +37,23 @@ public class JFrameVeiwServiceImpl implements DisplayVeiwService { @@ -28,19 +37,23 @@ public class JFrameVeiwServiceImpl implements DisplayVeiwService {
28 37
29 @Override 38 @Override
30 public void veiw(VeiwDto veiwDto) { 39 public void veiw(VeiwDto veiwDto) {
31 - if(null != veiwDto.getBinaryImage()) 40 +
  41 + if((boolean)configurationParameterService.getConfig(ConfigurationParameter.VeiwDto_isBinaryImage))
32 { 42 {
33 fishRegionPanel.getLblImage().setIcon(new ImageIcon(convertMatToImage(veiwDto.getBinaryImage()))); 43 fishRegionPanel.getLblImage().setIcon(new ImageIcon(convertMatToImage(veiwDto.getBinaryImage())));
34 } 44 }
35 - if(null != veiwDto.getFrame()) 45 + if((boolean)configurationParameterService.getConfig(ConfigurationParameter.VeiwDto_isFrame))
36 { 46 {
37 fishRegionPanel.getSrcImage().setIcon(new ImageIcon(convertMatToImage(veiwDto.getFrame()))); 47 fishRegionPanel.getSrcImage().setIcon(new ImageIcon(convertMatToImage(veiwDto.getFrame())));
38 } 48 }
39 - if(null != veiwDto.getSize()) 49 + if((boolean)configurationParameterService.getConfig(ConfigurationParameter.VeiwDto_isSize))
40 { 50 {
41 fishRegionPanel.getPnlGraph().getFishCountList().add(veiwDto.getSize()); 51 fishRegionPanel.getPnlGraph().getFishCountList().add(veiwDto.getSize());
42 fishRegionPanel.getPnlGraph().repaint(); 52 fishRegionPanel.getPnlGraph().repaint();
43 } 53 }
  54 + if((boolean)configurationParameterService.getConfig(ConfigurationParameter.VeiwDto_isFrame))
  55 + {
  56 + }
44 57
45 fishRegionPanel.getFrame().repaint(); 58 fishRegionPanel.getFrame().repaint();
46 } 59 }
  1 +<configuration>
  2 +<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  3 + <file>logs/output.log</file>
  4 + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  5 + <fileNamePattern>logs/output.%d{yyyy-MM-dd}.log</fileNamePattern>
  6 + <maxHistory>5</maxHistory>
  7 + </rollingPolicy>
  8 + <encoder>
  9 + <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
  10 + </encoder>
  11 +</appender>
  12 +
  13 +<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
  14 + <encoder>
  15 + <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
  16 + </encoder>
  17 +</appender>
  18 +
  19 +<root level="info">
  20 + <appender-ref ref="FILE" />
  21 + <appender-ref ref="CONSOLE" />
  22 +</root>
  23 +</configuration>
@@ -45,12 +45,21 @@ @@ -45,12 +45,21 @@
45 } 45 }
46 ws1.onmessage = function(message){ 46 ws1.onmessage = function(message){
47 console.log(message); 47 console.log(message);
48 - var data = JSON.parse(message.data);  
49 - $("#showVideo").attr("src", "data:image/jpg;base64," + data.img);  
50 48
  49 + if('{}' != message.data && undefined != message.data)
  50 + {
  51 + var data = JSON.parse(message.data);
  52 + if('{}' != data.frame && undefined != data.frame)
  53 + {
  54 + $("#showVideo").attr("src", "data:image/jpg;base64," + data.frame);
  55 + }
  56 + if(null != data.size && undefined != data.size)
  57 + {
51 addData(data.size); 58 addData(data.size);
  59 + }
52 drawChart(); 60 drawChart();
53 } 61 }
  62 + }
54 ws1.onclose = function (o) { 63 ws1.onclose = function (o) {
55 $("#result").textContent = "服务断开"; 64 $("#result").textContent = "服务断开";
56 } 65 }
@@ -11,6 +11,7 @@ @@ -11,6 +11,7 @@
11 <module>lh-common</module> 11 <module>lh-common</module>
12 <module>lh-jar</module> 12 <module>lh-jar</module>
13 <module>lh-modules</module> 13 <module>lh-modules</module>
  14 + <module>zl-modules</module>
14 </modules> 15 </modules>
15 16
16 <packaging>pom</packaging> 17 <packaging>pom</packaging>
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<project xmlns="http://maven.apache.org/POM/4.0.0"
  3 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5 + <modelVersion>4.0.0</modelVersion>
  6 + <parent>
  7 + <groupId>com.zhonglai.luhui</groupId>
  8 + <artifactId>Luhui</artifactId>
  9 + <version>1.0-SNAPSHOT</version>
  10 + </parent>
  11 +
  12 + <artifactId>zl-modules</artifactId>
  13 + <modules>
  14 + <module>zl-email-forwarding</module>
  15 + </modules>
  16 +
  17 + <properties>
  18 + <maven.compiler.source>8</maven.compiler.source>
  19 + <maven.compiler.target>8</maven.compiler.target>
  20 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  21 + </properties>
  22 +
  23 + <packaging>pom</packaging>
  24 + <description>
  25 + zl-modules 个人业务模块
  26 + </description>
  27 +</project>
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<project xmlns="http://maven.apache.org/POM/4.0.0"
  3 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5 + <modelVersion>4.0.0</modelVersion>
  6 + <parent>
  7 + <groupId>com.zhonglai.luhui</groupId>
  8 + <artifactId>zl-modules</artifactId>
  9 + <version>1.0-SNAPSHOT</version>
  10 + </parent>
  11 +
  12 + <artifactId>zl-email-forwarding</artifactId>
  13 +
  14 + <properties>
  15 + <maven.compiler.source>8</maven.compiler.source>
  16 + <maven.compiler.target>8</maven.compiler.target>
  17 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18 + </properties>
  19 +
  20 +</project>
  1 +package com.zhonglai.zl;
  2 +
  3 +public class Main {
  4 + public static void main(String[] args) {
  5 + System.out.println("Hello world!");
  6 + }
  7 +}