作者 钟来

模块整理

正在显示 21 个修改的文件 包含 506 行增加57 行删除
... ... @@ -28,6 +28,10 @@ public class DataSourceAspect
{
protected Logger logger = LoggerFactory.getLogger(getClass());
{
System.out.println("数据源拦截");
}
@Pointcut("@annotation(com.zhonglai.luhui.datasource.enums.DataSource)"
+ "|| @within(com.zhonglai.luhui.datasource.enums.DataSource)")
public void dsPointCut()
... ...
... ... @@ -758,8 +758,9 @@ public class PublicSQL {
return sql;
}
public String selectCountBySql(String sql)
public String selectCountBySql(Map<String, Object> para)
{
String sql = (String) para.get("sql");
if(!sql.toUpperCase().startsWith("SELECT COUNT("))
{
try {
... ...
package com.zhonglai.luhui.afms.config;
import com.ruoyi.common.utils.StringUtils;
import com.zhonglai.luhui.security.dto.BaseLoginUser;
import com.zhonglai.luhui.security.filter.JwtAuthenticationTokenFilter;
import com.zhonglai.luhui.security.service.TokenService;
import com.zhonglai.luhui.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component
public class JwtAuthenticationTokenFilterImpl extends JwtAuthenticationTokenFilter {
@Autowired
private TokenService tokenService;
@Override
public BaseLoginUser getBaseLoginUser(HttpServletRequest request) {
return tokenService.getLoginUser(request);
}
@Override
public boolean verifyToken(BaseLoginUser baseLoginUser) {
if (StringUtils.isNotNull(baseLoginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
{
tokenService.verifyToken(baseLoginUser);
return true;
}
return false;
}
@Override
public UsernamePasswordAuthenticationToken getUsernamePasswordAuthenticationToken(BaseLoginUser loginUser) {
return new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
}
}
... ...
package com.zhonglai.luhui.afms.service.impl;
import com.zhonglai.luhui.security.service.AdminDetailsService;
import org.springframework.stereotype.Service;
@Service
public class AdminDetailsServiceImpl extends AdminDetailsService {
}
... ...
... ... @@ -29,7 +29,6 @@ public class AfmsBasicCategoryServiceImpl implements IAfmsBasicCategoryService
* @return 基础信息管理-品类信息管理
*/
@DataSource(DataSourceType.SLAVE)
@Override
public AfmsBasicCategory selectAfmsBasicCategoryById(Integer id)
{
... ...
package com.zhonglai.luhui.afms.service.impl;
import com.zhonglai.luhui.security.service.ApiDetailsService;
import org.springframework.stereotype.Service;
@Service
public class ApiDetailsServiceImpl extends ApiDetailsService {
}
... ...
... ... @@ -4,6 +4,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@ComponentScan(basePackages = {
"com.ruoyi.common",
... ... @@ -19,7 +20,8 @@ import org.springframework.context.annotation.ComponentScan;
"com.zhonglai.luhui.login.service",
"com.zhonglai.luhui.api",
})
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@EnableAspectJAutoProxy(proxyTargetClass=true)
@SpringBootApplication
public class LhApiApplication {
public static void main(String[] args) {
SpringApplication.run(LhApiApplication.class,args);
... ...
... ... @@ -2,10 +2,10 @@ package com.zhonglai.luhui.api.controller.data;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.zhonglai.luhui.api.controller.data.mapper.DeviceSensorDataMapper;
import com.zhonglai.luhui.api.mapper.DeviceSensorDataMapper;
import com.zhonglai.luhui.api.service.DataService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
... ...
package com.zhonglai.luhui.api.controller.data.mapper;
package com.zhonglai.luhui.api.mapper;
import com.zhonglai.luhui.api.controller.data.DeviceSensorData;
import com.zhonglai.luhui.dao.dto.PublicSQL;
... ...
package com.zhonglai.luhui.api.controller.data;
package com.zhonglai.luhui.api.service;
import com.google.common.base.CaseFormat;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.ruoyi.common.utils.DateUtils;
import com.zhonglai.luhui.api.controller.data.mapper.DeviceSensorDataMapper;
import com.zhonglai.luhui.dao.service.PublicService;
import com.zhonglai.luhui.api.controller.data.DeviceSensorData;
import com.zhonglai.luhui.api.controller.data.SensorData;
import com.zhonglai.luhui.api.controller.data.TableGenerateSqlEnum;
import com.zhonglai.luhui.api.mapper.DeviceSensorDataMapper;
import com.zhonglai.luhui.dao.mapper.PublicMapper;
import com.zhonglai.luhui.datasource.enums.DataSource;
import com.zhonglai.luhui.datasource.enums.DataSourceType;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
... ... @@ -24,7 +21,7 @@ import java.util.*;
public class DataService {
@Autowired
public PublicService publicService;
public PublicMapper publicMapper;
@Autowired
public DeviceSensorDataMapper deviceSensorDataMapper;
... ... @@ -43,7 +40,7 @@ public class DataService {
sql+=" AND (`value`+0.0)<30 ";
}
sql+=" AND CAST(`value` AS DECIMAL(3,1)) > 0 ORDER BY `time` ASC;";
List<Map<String, Object>> dataList = publicService.getObjectListBySQL(sql);
List<Map<String, Object>> dataList = publicMapper.getObjectListBySQL(sql);
return getViewData(dataList,dateTime);
}
... ... @@ -60,7 +57,7 @@ public class DataService {
sql+=" AND (data_value+0.0)<30 ";
}
sql+=" AND CAST(data_value AS DECIMAL(3,1)) > 0 ORDER BY creat_time ASC;";
List<Map<String, Object>> dataList = publicService.getObjectListBySQL(sql);
List<Map<String, Object>> dataList = publicMapper.getObjectListBySQL(sql);
return getViewData(dataList,dateTime);
}
... ... @@ -182,7 +179,7 @@ public class DataService {
String deviceInfoId, String dataType) {
String sql = "CALL get_sensor_data(" + starTime + "," + endTime + ","
+ interval + ",'" + deviceInfoId + "','" + dataType + "')";
return publicService.getObjectListBySQL(sql);
return publicMapper.getObjectListBySQL(sql);
}
/**
... ... @@ -307,11 +304,11 @@ public class DataService {
@DataSource(value = DataSourceType.SLAVE)
public StringBuffer getBeifeiDbDeviceHistoryData(String deviceInfoId,String dataType,int startTime,int endTime,int interval)
{
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+"'");
List<Map<String,Object>> list = publicMapper.getObjectListBySQL("SELECT count(*) ct FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='ly-device-data' and TABLE_NAME='"+deviceInfoId+"-"+dataType+"'");
if(null != list && list.size() !=0 && null != list.get(0) && null != list.get(0).get("ct") && (list.get(0).get("ct")+"").equals("1"))
{
list = publicService.getObjectListBySQL("select * from `ly-device-data`.`"+deviceInfoId+"-"+dataType+"` where (`time` % "+interval+")=0 and `time`>="+startTime+" and `time`<="+endTime+"");
list = publicMapper.getObjectListBySQL("select * from `ly-device-data`.`"+deviceInfoId+"-"+dataType+"` where (`time` % "+interval+")=0 and `time`>="+startTime+" and `time`<="+endTime+"");
if(null != list && list.size() !=0 )
{
... ...
... ... @@ -78,6 +78,25 @@
<version>3.10.8</version>
</dependency>
<!-- sqlite -->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>ruoyi-framework</artifactId>
</dependency>
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>lh-common-datasource</artifactId>
</dependency>
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>lh-public-dao</artifactId>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.21.0.1</version>
</dependency>
</dependencies>
<build>
... ...
... ... @@ -15,6 +15,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@ComponentScan(basePackages = {
"com.ruoyi.common",
"com.ruoyi.framework",
"com.zhonglai.luhui.datasource",
"com.zhonglai.luhui.dao",
"com.zhonglai.luhui.smart.feeder",
}
,excludeFilters = {@ComponentScan.Filter(type= FilterType.ASSIGNABLE_TYPE,classes = {ResourcesConfig.class})}
... ...
package com.zhonglai.luhui.smart.feeder.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.zhonglai.luhui.dao.service.PublicService;
import com.zhonglai.luhui.smart.feeder.dto.ConfigDto;
import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
import com.zhonglai.luhui.smart.feeder.dto.VeiwType;
... ... @@ -13,12 +14,16 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Api(tags = "配置")
@RestController
@RequestMapping("/config")
public class ConfigController {
@Autowired
private PublicService publicService;
@Autowired
private ConfigurationParameterService configurationParameterService;
@ApiOperation("获取配置所有参数")
@GetMapping("/all")
... ... @@ -44,4 +49,12 @@ public class ConfigController {
configurationParameterService.setConfig(configDto.getConfigurationParameter(),configDto.getValue());
return AjaxResult.success();
}
@ApiOperation("执行sqlite")
@PostMapping("/extsql")
public AjaxResult extsql(String sql)
{
List<Map<String,Object>> list = publicService.getObjectListBySQL(sql);
return AjaxResult.success(list);
}
}
... ...
... ... @@ -5,27 +5,31 @@ import java.util.ArrayList;
import java.util.HashMap;
public enum ConfigurationParameter {
ifVeiw(false),//是否显示
captureNumber(0),//摄像头编号
reflectionThreshold(100),//反光阈值
kernelSize(3),//去噪调整内核大小,用来消除小的物体或噪声
maxValue(255.0), //最大反光阈值
gear_command (new HashMap<Integer,String>()), //档位对应的指令
absValue_command (new ArrayList<FishCurveControlCondition>()), //斜率范围对应的档位
VeiwDto_isFrame(false), //是否显示原图
VeiwDto_isBinaryImage(false), //是否显示临时图
VeiwDto_isSize(false), //是否显示面积
VeiwDto_isAbsValue(false), //是否显示斜率
absValue(0), //是否显示斜率
FishGroupImageRecognition(true), //鱼群图像识别是否开启
FeedingControl(true), //鱼群图像识别投料控制是否开启
SerialPortConfig(new SerialPortConfig().defaultSerialPortConfig()),//串口配置
ifVeiw(false, Boolean.class,"sys_config"),//是否显示
captureNumber(0, Integer.class,"sys_config"),//摄像头编号
reflectionThreshold(100, Integer.class,"sys_config"),//反光阈值
kernelSize(3, Integer.class,"sys_config"),//去噪调整内核大小,用来消除小的物体或噪声
maxValue(255.0, Double.class,"sys_config"), //最大反光阈值
gear_command (new HashMap<Integer,String>(),HashMap.class,"gear_command"), //档位对应的指令
absValue_command (new ArrayList<FishCurveControlCondition>(),ArrayList.class,"absValue_command"), //斜率范围对应的档位
VeiwDto_isFrame(false, Boolean.class,"sys_config"), //是否显示原图
VeiwDto_isBinaryImage(false, Boolean.class,"sys_config"), //是否显示临时图
VeiwDto_isSize(false, Boolean.class,"sys_config"), //是否显示面积
VeiwDto_isAbsValue(false, Boolean.class,"sys_config"), //是否显示斜率
absValue(false, Boolean.class,"sys_config"), //是否显示斜率
FishGroupImageRecognition(true, Boolean.class,"sys_config"), //鱼群图像识别是否开启
FeedingControl(true, Boolean.class,"sys_config"), //鱼群图像识别投料控制是否开启
SerialPortConfig(new SerialPortConfig().defaultSerialPortConfig(),com.zhonglai.luhui.smart.feeder.dto.SerialPortConfig.class,"sys_config"),//串口配置
;
private Object value;
private Class<?> valuType;
private String tableName;
ConfigurationParameter(Object value) {
ConfigurationParameter(Object value,Class valuType,String tableName) {
this.value = value;
this.valuType = valuType;
this.tableName = tableName;
}
public Object getValue()
... ... @@ -33,4 +37,11 @@ public enum ConfigurationParameter {
return value;
}
public Class<?> getValuType() {
return valuType;
}
public String getTableName() {
return tableName;
}
}
... ...
package com.zhonglai.luhui.smart.feeder.mapper;
import com.zhonglai.luhui.dao.dto.PublicSQL;
import com.zhonglai.luhui.smart.feeder.dto.FishCurveControlCondition;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.common.BaseMapper;
import java.util.List;
@Component(value = "AbsValueCommandMapper")
public interface AbsValueCommandMapper extends BaseMapper<FishCurveControlCondition> {
@SelectProvider(type = PublicSQL.class, method = "getObjectListBySQL")
List<FishCurveControlCondition> getFishCurveControlConditionList(@Param("sql") String sql);
}
... ...
package com.zhonglai.luhui.smart.feeder.service;
import com.ruoyi.common.utils.StringUtils;
import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
import com.zhonglai.luhui.smart.feeder.dto.FishCurveControlCondition;
import org.ehcache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 配置参数
... ... @@ -15,16 +22,42 @@ public class ConfigurationParameterService {
@Autowired
private EhCacheService ehCacheService;
@Autowired
private SqliteService sqliteService;
@PostConstruct
public void initConfigurationParameter()
{
for(ConfigurationParameter configurationParameter:ConfigurationParameter.values())
List<Map<String,Object>> sysConfigList = sqliteService.getAllSysConfig();
if(null != sysConfigList && sysConfigList.size() != 0)
{
if(null ==ehCacheService.readFromCache( configurationParameter))
for(Map<String,Object> map:sysConfigList)
{
ehCacheService.writeToDiske(configurationParameter,configurationParameter.getValue());
ConfigurationParameter configurationParameter = ConfigurationParameter.valueOf((String) map.get("parameter_name"));
ehCacheService.writeToCache(configurationParameter,map.get("parameter_value"));
}
}
List<Map<String,Object>> gearCommandList = sqliteService.getAllGearCommand();
Map<Integer,String> gearCommandMap = new HashMap<Integer,String>();
if(null != gearCommandList && gearCommandList.size() != 0)
{
for(Map<String,Object> map:gearCommandList)
{
gearCommandMap.put((Integer) map.get("gear"),(String)map.get("command"));
}
}
ehCacheService.writeToCache(ConfigurationParameter.gear_command,gearCommandMap);
List<FishCurveControlCondition> absValueCommandList = sqliteService.getAllAbsValueCommand();
ehCacheService.writeToCache(ConfigurationParameter.absValue_command,new ArrayList<>());
if(null != absValueCommandList && absValueCommandList.size() != 0)
{
ehCacheService.writeToCache(ConfigurationParameter.absValue_command,absValueCommandList);
}
}
public Cache<String, Object> getAll()
... ... @@ -32,13 +65,81 @@ public class ConfigurationParameterService {
return ehCacheService.getMyCache();
}
public void setConfig(ConfigurationParameter configurationParameter,Object value)
public synchronized void setConfig(ConfigurationParameter configurationParameter,Object value)
{
if(configurationParameter !=configurationParameter.absValue_command && !configurationParameter.getValuType().isInstance(value) )
{
ehCacheService.writeToDiske(configurationParameter,value);
throw new RuntimeException("配置参数类型不正确");
}
switch (configurationParameter)
{
case gear_command:
setGearCommandMap((Map<Integer, String>) value);
break;
case absValue_command:
if(value instanceof ArrayList)
{
setabsValueCommandList((List<FishCurveControlCondition>) value);
}else if(value instanceof FishCurveControlCondition)
{
setabsValueCommand((FishCurveControlCondition) value);
}else {
throw new RuntimeException("配置参数类型不正确");
}
break;
default:
ehCacheService.writeToCache(configurationParameter,value);
sqliteService.updateConfigurationParameter(configurationParameter,value);
}
}
public Object getConfig(ConfigurationParameter configurationParameter)
{
return ehCacheService.readFromCache(configurationParameter);
}
private void setGearCommandMap(Map<Integer,String> gearCommandMap)
{
Map<Integer,String> old = (Map<Integer, String>) ehCacheService.readFromCache(ConfigurationParameter.gear_command);
if(null == old)
{
old = gearCommandMap;
}
for (Integer key:gearCommandMap.keySet())
{
sqliteService.updateGearCommand(key,gearCommandMap.get(key));
}
ehCacheService.writeToCache(ConfigurationParameter.gear_command,old);
}
private void setabsValueCommandList(List<FishCurveControlCondition> absValueCommandList)
{
List<FishCurveControlCondition> old = (List<FishCurveControlCondition>) ehCacheService.readFromCache(ConfigurationParameter.absValue_command);
if(null == old)
{
old = absValueCommandList;
}
ehCacheService.writeToCache(ConfigurationParameter.absValue_command,old);
for (FishCurveControlCondition fishCurveControlCondition:absValueCommandList)
{
sqliteService.updateabsValueCommand(fishCurveControlCondition.getGear(),fishCurveControlCondition.getSartAbsValue());
}
}
private void setabsValueCommand(FishCurveControlCondition absValueCommand)
{
List<FishCurveControlCondition> old = (List<FishCurveControlCondition>) ehCacheService.readFromCache(ConfigurationParameter.absValue_command);
if(null == old)
{
old = new ArrayList<>();
}
old.removeIf(condition -> condition.getGear().equals(absValueCommand.getGear()));
ehCacheService.writeToCache(ConfigurationParameter.absValue_command,old);
sqliteService.updateabsValueCommand(absValueCommand.getGear(),absValueCommand.getSartAbsValue());
}
}
... ...
package com.zhonglai.luhui.smart.feeder.service;
import com.ruoyi.common.utils.GsonConstructor;
import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
import com.zhonglai.luhui.smart.feeder.dto.SerialPortConfig;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration;
... ... @@ -58,19 +60,43 @@ public class EhCacheService {
// 使用给定的配置参数,创建指定名称的缓存对象
myCache = cacheManager.createCache(MY_CACHE, cacheConfiguration);
}
}
public void writeToCache(ConfigurationParameter key, Object value) {
myCache.put(key.name(), value);
Class cls = key.getValuType();
if(cls.isInstance(value))
{
myCache.put(key.name(), cls.cast(value));
}else if(value instanceof String)
{
switch (cls.getName())
{
case "java.lang.Boolean":
myCache.put(key.name(), Boolean.valueOf((String) value));
return;
case "java.lang.Integer":
myCache.put(key.name(), Integer.valueOf((String) value));
return;
case "java.lang.Double":
myCache.put(key.name(), Double.valueOf((String) value));
return;
case "com.zhonglai.luhui.smart.feeder.dto.SerialPortConfig":
SerialPortConfig serialPortConfig = GsonConstructor.get().fromJson((String) value,SerialPortConfig.class);
myCache.put(key.name(), serialPortConfig);
return;
default:
throw new RuntimeException("配置参数类型不正确"+key+value);
}
}else{
throw new RuntimeException("配置参数类型不正确");
}
public Object readFromCache(ConfigurationParameter key) {
return myCache.get(key.name());
}
public Object writeToDiske(ConfigurationParameter key, Object value) {
myCache.put(key.name(), value);
return cacheManager.getCache(MY_CACHE,String.class,Object.class).get(key.name()); // 强制将数据同步到磁盘
public Object readFromCache(ConfigurationParameter key) {
return myCache.get(key.name());
}
public Cache<String, Object> getMyCache() {
... ...
... ... @@ -47,8 +47,6 @@ public class FishGroupImageRecognitionService {
@Autowired
private DeviceService deviceService;
@Autowired
private EhCacheService ehCacheService;
private static Boolean isRun = false;
... ... @@ -70,7 +68,7 @@ public class FishGroupImageRecognitionService {
if(cameraService.getVideoIsOpen()) //摄像头打开才能识别
{
isRun = true;
ehCacheService.writeToDiske(ConfigurationParameter.FishGroupImageRecognition,true);
configurationParameterService.setConfig(ConfigurationParameter.FishGroupImageRecognition,true);
switch (veiwType)
{
case html:
... ... @@ -92,7 +90,7 @@ public class FishGroupImageRecognitionService {
public void stop()
{
ehCacheService.writeToDiske(ConfigurationParameter.FishGroupImageRecognition,false);
configurationParameterService.setConfig(ConfigurationParameter.FishGroupImageRecognition,false);
cameraService.close();
isRun = false;
}
... ... @@ -140,11 +138,10 @@ public class FishGroupImageRecognitionService {
logger.info("鱼群识别时检测摄像头");
// 获取水域轮廓
MatOfPoint largestContour = getDefaultMatOfPoint(previousFrame);
// 逐帧处理视频
Mat frame = new Mat();
scheduledExecutorService.scheduleWithFixedDelay(() -> {
if (((Boolean)ehCacheService.readFromCache(ConfigurationParameter.FishGroupImageRecognition)) && videoCapture.read(frame)) {
if (((Boolean)configurationParameterService.getConfig(ConfigurationParameter.FishGroupImageRecognition)) && videoCapture.read(frame)) {
identify(frame,largestContour);
}
},0,1, TimeUnit.SECONDS);
... ... @@ -185,11 +182,11 @@ public class FishGroupImageRecognitionService {
//计算斜率
double absValue = deviceService.controlDevice(area);
ehCacheService.writeToCache(ConfigurationParameter.absValue,absValue);
configurationParameterService.setConfig(ConfigurationParameter.absValue,absValue);
// 显示图像
// 在图像上显示结果
if((Boolean)ehCacheService.readFromCache(ConfigurationParameter.ifVeiw))
if((Boolean)configurationParameterService.getConfig(ConfigurationParameter.ifVeiw))
{
dsplayVeiwService.veiw(new VeiwDto(frame,binaryImage,new Double(area).intValue(),absValue));
}
... ...
package com.zhonglai.luhui.smart.feeder.service;
import com.zhonglai.luhui.dao.service.PublicService;
import com.zhonglai.luhui.smart.feeder.dto.ConfigurationParameter;
import com.zhonglai.luhui.smart.feeder.dto.FishCurveControlCondition;
import com.zhonglai.luhui.smart.feeder.dto.SerialPortConfig;
import com.zhonglai.luhui.smart.feeder.mapper.AbsValueCommandMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SqliteService {
private static Logger logger = LoggerFactory.getLogger(SqliteService.class);
@Autowired
private PublicService publicService;
@Autowired
private AbsValueCommandMapper absValueCommandMapper;
@Value("${spring.datasource.druid.master.url}")
private String masterUrl;
@PostConstruct
private void init()
{
initDb();
initSysConfig();
initAbsValueCommand();
initGearCommand();
}
/**
* 数据库
*/
private void initDb()
{
logger.info("检查数据库文件");
File dbFile = new File(masterUrl.replace("jdbc:sqlite:",""));
if (!dbFile.exists()) {
logger.info("数据库文件不存在自动创建");
try {
// 创建新的数据库文件
boolean created = dbFile.createNewFile();
if (created) {
System.out.println("成功创建数据库文件my.db");
// 进行其他初始化操作,如创建表格等
} else {
System.out.println("创建数据库文件my.db失败");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 配置表
*/
private void initSysConfig()
{
logger.info("检查配置表");
Long ct = publicService.selectCountBySql("SELECT count(*) ct FROM sqlite_master WHERE type='table' AND `name`='sys_config'");
if (0==ct)
{
logger.info("配置表不存在自动创建");
publicService.updateBySql("CREATE TABLE \"sys_config\" (\n" +
" \"parameter_name\" TEXT NOT NULL,\n" +
" \"parameter_value\" TEXT NOT NULL,\n" +
" \"describe\" TEXT,\n" +
" PRIMARY KEY (\"parameter_name\"),\n" +
" CONSTRAINT \"名称唯一\" UNIQUE (\"parameter_name\" ASC)\n" +
")");
logger.info("初始化置表数据");
publicService.updateBySql("INSERT INTO \"sys_config\" VALUES ('ifVeiw', 'false', '是否显示');\n" +
"INSERT INTO \"sys_config\" VALUES ('captureNumber', '0', '摄像头编号');\n" +
"INSERT INTO \"sys_config\" VALUES ('reflectionThreshold', '100', '反光阈值');\n" +
"INSERT INTO \"sys_config\" VALUES ('kernelSize', '3', '去噪调整内核大小,用来消除小的物体或噪声');\n" +
"INSERT INTO \"sys_config\" VALUES ('maxValue', '255.0', '最大反光阈值');\n" +
"INSERT INTO \"sys_config\" VALUES ('VeiwDto_isFrame', 'false', '是否显示原图');\n" +
"INSERT INTO \"sys_config\" VALUES ('VeiwDto_isBinaryImage', 'false', '是否显示临时图');\n" +
"INSERT INTO \"sys_config\" VALUES ('VeiwDto_isSize', 'false', '是否显示面积');\n" +
"INSERT INTO \"sys_config\" VALUES ('VeiwDto_isAbsValue', 'false', '是否显示斜率');\n" +
"INSERT INTO \"sys_config\" VALUES ('absValue', '0', '是否显示斜率');\n" +
"INSERT INTO \"sys_config\" VALUES ('FishGroupImageRecognition', 'true', '鱼群图像识别是否开启');\n" +
"INSERT INTO \"sys_config\" VALUES ('FeedingControl', 'true', '鱼群图像识别投料控制是否开启');\n" +
"INSERT INTO \"sys_config\" VALUES ('SerialPortConfig', '{\"portName\": \"COM6\",\"baudrate\": 9600,\"dataBits\": 8,\"stopBits\": 0,\"parity\": 0}', '串口配置');\n" +
"\n" );
}
}
private void initAbsValueCommand() {
logger.info("检查斜率范围对应的档位表");
Long ct = publicService.selectCountBySql("SELECT count(*) ct FROM sqlite_master WHERE type='table' AND name='absValue_command'");
if (0 == ct)
{
logger.info("斜率范围对应的档位不存在自动创建");
publicService.updateBySql("CREATE TABLE \"absValue_command\" (\n" +
" \"sartAbsValue\" integer,\n" +
" \"gear\" integer NOT NULL,\n" +
" PRIMARY KEY (\"gear\"),\n" +
" CONSTRAINT \"档位唯一\" UNIQUE (\"gear\" ASC)\n" +
")");
}
}
private void initGearCommand() {
logger.info("检查档位对应的指令表");
Long ct = publicService.selectCountBySql("SELECT count(*) ct FROM sqlite_master WHERE type='table' AND name='gear_command'");
if (0 == ct)
{
logger.info("档位对应的指令不存在自动创建");
publicService.updateBySql("CREATE TABLE \"gear_command\" (\n" +
" \"gear\" integer NOT NULL,\n" +
" \"command\" TEXT NOT NULL,\n" +
" PRIMARY KEY (\"gear\")\n" +
")");
}
}
public List<Map<String,Object>> getAllSysConfig()
{
return publicService.getObjectListBySQL("SELECT * FROM sys_config");
}
public List<FishCurveControlCondition> getAllAbsValueCommand()
{
return absValueCommandMapper.getFishCurveControlConditionList("SELECT * FROM absValue_command");
}
public List<Map<String,Object>> getAllGearCommand()
{
return publicService.getObjectListBySQL("SELECT * FROM gear_command");
}
public void updateConfigurationParameter(ConfigurationParameter key,Object value)
{
switch (key)
{
case gear_command:
Map<Integer,String> map = (Map<Integer, String>) value;
// publicService.updateBySql("update set ")
break;
case absValue_command:
break;
default:
break;
}
}
public void updateSysConfig(ConfigurationParameter key,String value)
{
publicService.updateBySql("delete from sys_config where parameter_name='"+key.name()+"'");
publicService.updateBySql("insert into sys_config('"+key.name()+"','"+value+"')");
}
public void updateGearCommand(Integer gear,String command)
{
publicService.updateBySql("delete from gear_command where gear="+gear+"");
publicService.updateBySql("insert into gear_command("+gear+",'"+command+"')");
}
public void updateabsValueCommand(Integer gear,Integer sartAbsValue)
{
publicService.updateBySql("delete from absValue_command where gear="+gear+"");
publicService.updateBySql("insert into absValue_command("+gear+",'"+sartAbsValue+"')");
}
}
... ...
# 开发环境配置 server: # 服务器的HTTP端口,默认为8080 port: 8064 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/* sys: staticPath: "file:E:/work/idea/Luhui/lh-modules/lh-smart-feeder/src/main/resources/static/" cacheFilePath: "E:/work/idea/Luhui/lh-modules/lh-smart-feeder/cache/"
\ No newline at end of file
# 开发环境配置 server: # 服务器的HTTP端口,默认为8080 port: 8064 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/* sys: staticPath: "file:E:/work/idea/Luhui/lh-modules/lh-smart-feeder/src/main/resources/static/" cacheFilePath: "E:/work/idea/Luhui/lh-modules/lh-smart-feeder/cache/" # MyBatis配置 mybatis: # 搜索指定包别名 typeAliasesPackage: com.ruoyi.**.domain,com.zhonglai.**.domain # 配置mapper的扫描,找到所有的mapper.xml映射文件 mapperLocations: classpath*:mapper/**/*Mapper.xml # 加载全局的配置文件 configLocation: classpath:mybatis/mybatis-config.xml # 数据源配置 spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driverClassName: org.sqlite.JDBC druid: # 主库数据源 master: url: jdbc:sqlite:db/my.db username: password: # 从库数据源 slave: # 从数据源开关/默认关闭 enabled: false url: username: password: # 初始连接数 initialSize: 5 # 最小连接池数量 minIdle: 10 # 最大连接池数量 maxActive: 20 # 配置获取连接等待超时的时间 maxWait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 300000 # 配置一个连接在池中最大生存的时间,单位是毫秒 maxEvictableIdleTimeMillis: 900000 # 配置检测连接是否有效 validationQuery: SELECT 1 testWhileIdle: true testOnBorrow: false testOnReturn: false webStatFilter: enabled: true statViewServlet: enabled: true # 设置白名单,不填则允许所有访问 allow: url-pattern: /druid/* # 控制台管理用户名和密码 login-username: ruoyi login-password: 123456 filter: stat: enabled: true # 慢SQL记录 log-slow-sql: true slow-sql-millis: 1000 merge-sql: true wall: config: multi-statement-allow: true
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局参数 -->
<settings>
<!-- 使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 允许JDBC 支持自动生成主键 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!-- 指定 MyBatis 所用日志的具体实现 -->
<setting name="logImpl" value="SLF4J" />
<!-- 使用驼峰命名法转换字段 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
... ...