netty版本完成

This commit is contained in:
gaoben 2021-03-15 16:45:58 +08:00
parent 0079beeac2
commit 0becc9f841
76 changed files with 4598 additions and 2277 deletions

View File

@ -2,7 +2,7 @@
package net.shapelight;
import net.shapelight.modules.dev.mqtt.MqttClientUtil;
//import net.shapelight.modules.dev.mqtt.MqttClientUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -22,21 +22,21 @@ public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
//mqtt服务启动
MqttClientUtil.createClient();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
//释放工作
//...
} catch (Throwable e) {
e.printStackTrace();
}
}
});
// //mqtt服务启动
// MqttClientUtil.createClient();
//
// Runtime.getRuntime().addShutdownHook(new Thread() {
// @Override
// public void run() {
// try {
// //释放工作
// //...
//
// } catch (Throwable e) {
// e.printStackTrace();
// }
// }
// });
}
}

View File

@ -61,8 +61,7 @@ public class Constant {
public static final int PESON_SUATUS_WAITREVIEW = 2; //待审核
public static final int PESON_SUATUS_REJECT = 3; //审核不通过
public static final int PESON_SUATUS_FACE_FAILURE = 4; //照片质量不合格
// public static final int PESON_SUATUS_DATE_NOT_START = 5; //访客时间未到
// public static final int PESON_SUATUS_DATE_OUT = 6; //访客已过时
public static final int PESON_SUATUS_GUEST_DATE_OUT = 5; //访客已过时
public static final String IMAGE_DIR_CAR = "car";
public static final String IMAGE_DIR_REPAIR= "repair";
@ -84,6 +83,13 @@ public class Constant {
public static final int COMPANY_TYPE_CHUZU = 46;
//0未同步4已同步1新增2修改3删除
public static final int PERSON_SYNC_NO = 0;
public static final int PERSON_SYNC_OK = 4;
public static final int PERSON_SYNC_ADD = 1;
public static final int PERSON_SYNC_MODIFY = 2;
public static final int PERSON_SYNC_DELETE = 3;

View File

@ -15,7 +15,8 @@ import net.shapelight.modules.app.entity.AppUserEntity;
import net.shapelight.modules.app.entity.AppUserScopeEntity;
import net.shapelight.modules.app.service.AppUserScopeService;
import net.shapelight.modules.app.service.AppUserService;
import net.shapelight.modules.dev.mqtt.CmdProcess;
//import net.shapelight.modules.dev.mqtt.CmdProcess;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.sys.entity.*;
import net.shapelight.modules.sys.service.*;
import io.swagger.annotations.Api;
@ -71,6 +72,8 @@ public class AppApiController {
private SysUserService sysUserService;
@Autowired
private SysDeviceAppService sysDeviceAppService;
@Autowired
private ServerApiService serverApiService;
@Login
@ -134,8 +137,6 @@ public class AppApiController {
return R.error("姓名在此房间已存在");
}
int res = tenPersonService.save(tenPerson);
if (res==2) {
return R.error("照片未检测到人脸");
@ -155,7 +156,9 @@ public class AppApiController {
tenPerson.setAppUserId(user.getUserId());
tenPerson.setPersonType(Constant.PERSON_TYPE_OWNER);
tenPerson.setTenantId(cell.getTenantId());
tenPerson.setCreateTime(new Date());
Date now = new Date();
tenPerson.setCreateTime(now);
tenPerson.setLastUpdateTime(now);
tenPerson.setRegisterType(Constant.RESGISTER_TYPE_APP);
tenPerson.setAppFlag(Constant.APP_LOGIN_YES);
tenPerson.setStatus(Constant.PESON_SUATUS_NOMOR);
@ -238,8 +241,6 @@ public class AppApiController {
// public static final int PERSON_TYPE_GUEST = 5005; //访客
tenPerson.setPersonType(Constant.PERSON_TYPE_GUEST);
tenPerson.setAppFlag(Constant.APP_LOGIN_NO);
// TenPersonEntity tenPersonEntity = tenPersonService.findByName(tenPerson.getName(),
// tenPerson.getRoomId(),tenPerson.getCellId());
// if(tenPersonEntity!=null){
@ -365,17 +366,22 @@ public class AppApiController {
public R remoteOpenDoor(@LoginUser AppUserEntity user, @RequestBody Map params) {
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
TenPersonEntity loginPerson = tenPersonService.getById(scope.getPersonId(),scope.getCellId());
String personId = loginPerson.getPersonId().toString();
Long personId = loginPerson.getPersonId(); //.toString();
String deviceSn = (String) params.get("deviceSn");
String cellId = loginPerson.getCellId().toString();
TenPersonEntity person = tenPersonService.getById(Long.parseLong(personId),Long.parseLong(cellId));
TenPersonEntity person = tenPersonService.getById(personId,Long.parseLong(cellId));
Integer memberId = person.getMemberId();
boolean flag = tenDeviceService.remoteOpenDoor(deviceSn,personId,memberId);
if (flag) {
return R.ok();
}else{
return R.error("开门失败");
// boolean flag = tenDeviceService.remoteOpenDoor(deviceSn,personId,memberId);
// if (flag) {
// return R.ok();
// }else{
// return R.error("开门失败");
// }
int r = serverApiService.openDoor(deviceSn,personId);
if(r == -1){
return R.error("设备离线");
}
return R.ok();
}
@ -423,8 +429,6 @@ public class AppApiController {
return R.error("手机号已经注册");
}
}
TenPersonEntity tenPersonEntity = tenPersonService.findByName(tenPerson.getName(),
tenPerson.getRoomId(),tenPerson.getCellId());
if(tenPersonEntity!=null){
@ -438,6 +442,7 @@ public class AppApiController {
tenPerson.setCreateBy(user.getUsername());
tenPerson.setCreateTime(new Date());
tenPerson.setRegisterType(Constant.RESGISTER_TYPE_APP);
tenPerson.setStatus(Constant.PESON_SUATUS_NOMOR);
int res = tenPersonService.save(tenPerson);
if (res==2) {
return R.error("照片未检测到人脸");
@ -462,6 +467,10 @@ public class AppApiController {
TenPersonEntity loginPerson = tenPersonService.getById(scope.getPersonId(),scope.getCellId());
TenCellEntity cell = tenCellService.getById(scope.getCellId());
if(loginPerson.getStatus().intValue() != Constant.PESON_SUATUS_NOMOR){
return R.error("您还没有审核通过,请联系小区管理员");
}
// TenPersonEntity loginPerson = tenPersonService.getById(tenPerson.getAppLoginPersonId(),tenPerson.getCellId());

View File

@ -250,6 +250,8 @@ public class AppInfoApiController {
public R openDoorRecordList(@LoginUser AppUserEntity user,@RequestBody Map<String, Object> params){
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
params.put("tenantId",user.getTenantId());
int during = Integer.parseInt((String)params.get("during"));
String recordTimeStart = null;
String recordTimeEnd = null;

View File

@ -1,34 +1,34 @@
package net.shapelight.modules.dev;
import lombok.Data;
import net.shapelight.common.config.GlobalValue;
import net.shapelight.common.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
@Data
public class AppSecret {
private String sysAppId;
private String sysAppSecret;
private String appId;
private String appSecret;
private String timestamp;//毫秒
private String sign;
public int check(){
if(!appId.equals(sysAppId)){
return 1;
}
long now = new Date().getTime();
long c = (Long.parseLong(timestamp)-now)/1000;
long abs = Math.abs(c);
if(abs > 30){
return 2;
}
String sysSign = MD5Utils.getMD5Str(appId+timestamp+sysAppSecret);
if(!sign.equals(sysSign)){
return 3;
}
return 0;
}
}
//package net.shapelight.modules.dev;
//
//import lombok.Data;
//import net.shapelight.common.config.GlobalValue;
//import net.shapelight.common.utils.MD5Utils;
//import org.springframework.beans.factory.annotation.Autowired;
//
//import java.util.Date;
//
//@Data
//public class AppSecret {
// private String sysAppId;
// private String sysAppSecret;
// private String appId;
// private String appSecret;
// private String timestamp;//毫秒
// private String sign;
// public int check(){
// if(!appId.equals(sysAppId)){
// return 1;
// }
// long now = new Date().getTime();
// long c = (Long.parseLong(timestamp)-now)/1000;
// long abs = Math.abs(c);
// if(abs > 30){
// return 2;
// }
// String sysSign = MD5Utils.getMD5Str(appId+timestamp+sysAppSecret);
// if(!sign.equals(sysSign)){
// return 3;
// }
// return 0;
// }
//}

View File

@ -1,411 +1,411 @@
package net.shapelight.modules.dev.mqtt;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import net.shapelight.common.utils.DateUtils;
import net.shapelight.common.utils.RedisUtils;
import net.shapelight.modules.ten.entity.TenDeviceAlertEntity;
import net.shapelight.modules.ten.entity.TenDeviceEntity;
import net.shapelight.modules.ten.entity.TenPersonEntity;
import net.shapelight.modules.ten.entity.TenRecordEntity;
import net.shapelight.modules.ten.service.TenDeviceService;
import net.shapelight.modules.vo.TenDeviceParamVo;
import net.shapelight.modules.vo.TenPersonVo;
import net.shapelight.modules.vo.TenRecordVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
public class CmdProcess {
private static CmdProcess cmdProcess;
@Autowired
private RedisUtils redisUtils;
@Autowired
private TenDeviceService tenDeviceService;
public void setRedisUtils(RedisUtils redisUtils) {
this.redisUtils = redisUtils;
}
public void setTenDeviceService(TenDeviceService tenDeviceService) {
this.tenDeviceService = tenDeviceService;
}
@PostConstruct
public void init(){
cmdProcess = this;
cmdProcess.redisUtils = this.redisUtils;
cmdProcess.tenDeviceService = this.tenDeviceService;
}
public static void execute(String topic, String content) {
JSONObject contentJson = JSONObject.parseObject(content);
String deviceSn = topic.substring(topic.indexOf("device/") + 7, topic.lastIndexOf("/client"));
String cmd = contentJson.getString("cmd");
TopicCmdEnum cmdEnum = TopicCmdEnum.valueOf(cmd);
switch (cmdEnum) {
case remoteOpenDoor:
log.info("removeOpenDoor:", cmdEnum.getCmd());
subscribeRemoteOpenDoor(deviceSn,content);
break;
case personChange:
log.info("personChange", cmdEnum.getCmd());
break;
case cleanPerson:
log.info("cleanPerson", cmdEnum.getCmd());
break;
case faceCount:
subFaceCount(deviceSn,content);
log.info("faceCount", cmdEnum.getCmd());
break;
case alert:
subAlert(deviceSn,content);
log.info("alert", cmdEnum.getCmd());
break;
case addPerson:
log.info("addPerson", cmdEnum.getCmd());
break;
case getParam:
subGetParam(deviceSn,content);
log.info("getParam", cmdEnum.getCmd());
break;
}
}
/**
* {
* "cmd": "remoteOpenDoor",
* "data": {
* "personId": "721041148851781632",
* }
* }
* @param deviceSn
* @param memberId
*/
public static void publishRemoteOpenDoor(String deviceSn,Integer memberId){
//获取 发送给 指定id 的app用户的topic
String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
//要发送消息的内容
JSONObject sendContent = new JSONObject();
// sendContent.put("cmd", cmd_id + "/response");
// sendContent.put("ret", "0");
// sendContent.put("msg", "测试消息已经处成功处理");
// sendContent.put("code", 0);
Map<String,Object> data = new HashMap<>();
// data.put("personId",personId);
TenDeviceEntity device = cmdProcess.tenDeviceService.findBySn(deviceSn);
// TenPersonEntity personEntity = cmdProcess.tenDeviceService.getByPersonId(Long.parseLong(personId),device.getCellId());
data.put("memberId",memberId);
data.put("deviceSn",deviceSn);
sendContent.put("cmd", "remoteOpenDoor");
sendContent.put("data", data);
//发布消息
MqttClientUtil.publish_common(topic, sendContent.toString());
}
/**
*
* @param deviceSn
* @param content
* {
* "cmd":"remoteOpenDoor",
* "data":{
* "personId":"721041148851781632",
* "recordTime":"2020-07-06 14:36:23",
* "openType":2, //1人脸识别2远程一键开门
* "recordFaceStr":"/9j/4AAQSkZJRgABAQAAAQABAAD"
* }
* }
*/
private static void subscribeRemoteOpenDoor(String deviceSn,String content){
JSONObject resJson = JSONObject.parseObject(content);
JSONObject data = resJson.getJSONObject("data");
// String personId = data.getString("personId");
Integer memberId = data.getInteger("memberId");
String recordTime = data.getString("recordTime");
Integer openType = data.getInteger("openType");
TenDeviceEntity device = cmdProcess.tenDeviceService.findBySn(deviceSn);
TenPersonEntity person = cmdProcess.tenDeviceService.getByMemberId(memberId,device.getCellId());
TenRecordEntity record = new TenRecordEntity();
record.setDeviceSn(deviceSn);
record.setPersonId(person.getPersonId());
record.setCellId(device.getCellId());
// DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// LocalDateTime parse = LocalDateTime.parse(recordTime, dtf);
record.setRecordTime(new Date());
record.setOpenType(openType);
//添加到redis
// cmdProcess.redisUtils.set(personId+"-"+deviceSn,openDate,60L);
cmdProcess.redisUtils.set(person.getPersonId()+"-"+deviceSn,recordTime,10L);
//添加到记录里
// log.info("----------------------------------------收到意见开门记录");
cmdProcess.tenDeviceService.upRecord(record);
}
/**
*
* @param deviceSn
*
* {
* "cmd":" personChange",
* "data":{
* }
* }
*/
public static void publishPersonChange(String deviceSn){
//获取 发送给 指定id 的app用户的topic
String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
//要发送消息的内容
JSONObject sendContent = new JSONObject();
Map<String,Object> data = new HashMap<>();
sendContent.put("cmd", "personChange");
sendContent.put("data", data);
//发布消息
MqttClientUtil.publish_common(topic, sendContent.toString());
}
/**
*
* @param deviceSn
*
* {
* "cmd":"addPerson",
* "data":{TenPersonVo
* }
* }
*/
public static void publishAddPerson(String deviceSn, TenPersonVo personVo){
//获取 发送给 指定id 的app用户的topic
String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
//要发送消息的内容
JSONObject sendContent = new JSONObject();
// Map<String,Object> data = new HashMap<>();
sendContent.put("cmd", "addPerson");
sendContent.put("data", personVo);
// if(((JSONObject)sendContent.get("data")).get("liveStart")!=null){
// ((JSONObject)sendContent.get("data")).put("liveStart", DateUtils.format(personVo.getLiveStart(),DateUtils.DATE_TIME_PATTERN));
// }
//package net.shapelight.modules.dev.mqtt;
//
// if(((JSONObject)sendContent.get("data")).get("liveEnd")!=null){
// ((JSONObject)sendContent.get("data")).put("liveEnd", DateUtils.format(personVo.getLiveEnd(),DateUtils.DATE_TIME_PATTERN));
//
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.google.gson.JsonObject;
//import lombok.extern.slf4j.Slf4j;
//import net.shapelight.common.utils.DateUtils;
//import net.shapelight.common.utils.RedisUtils;
//import net.shapelight.modules.ten.entity.TenDeviceAlertEntity;
//import net.shapelight.modules.ten.entity.TenDeviceEntity;
//import net.shapelight.modules.ten.entity.TenPersonEntity;
//import net.shapelight.modules.ten.entity.TenRecordEntity;
//import net.shapelight.modules.ten.service.TenDeviceService;
//import net.shapelight.modules.vo.TenDeviceParamVo;
//import net.shapelight.modules.vo.TenPersonVo;
//import net.shapelight.modules.vo.TenRecordVo;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//@Slf4j
//@Component
//public class CmdProcess {
// private static CmdProcess cmdProcess;
//
// @Autowired
// private RedisUtils redisUtils;
// @Autowired
// private TenDeviceService tenDeviceService;
//
// public void setRedisUtils(RedisUtils redisUtils) {
// this.redisUtils = redisUtils;
// }
//
// public void setTenDeviceService(TenDeviceService tenDeviceService) {
// this.tenDeviceService = tenDeviceService;
// }
//
// @PostConstruct
// public void init(){
// cmdProcess = this;
// cmdProcess.redisUtils = this.redisUtils;
// cmdProcess.tenDeviceService = this.tenDeviceService;
// }
//
// public static void execute(String topic, String content) {
// JSONObject contentJson = JSONObject.parseObject(content);
// String deviceSn = topic.substring(topic.indexOf("device/") + 7, topic.lastIndexOf("/client"));
// String cmd = contentJson.getString("cmd");
// TopicCmdEnum cmdEnum = TopicCmdEnum.valueOf(cmd);
// switch (cmdEnum) {
// case remoteOpenDoor:
// log.info("removeOpenDoor:", cmdEnum.getCmd());
// subscribeRemoteOpenDoor(deviceSn,content);
// break;
// case personChange:
// log.info("personChange", cmdEnum.getCmd());
// break;
// case cleanPerson:
// log.info("cleanPerson", cmdEnum.getCmd());
// break;
// case faceCount:
// subFaceCount(deviceSn,content);
// log.info("faceCount", cmdEnum.getCmd());
// break;
// case alert:
// subAlert(deviceSn,content);
// log.info("alert", cmdEnum.getCmd());
// break;
// case addPerson:
// log.info("addPerson", cmdEnum.getCmd());
// break;
// case getParam:
// subGetParam(deviceSn,content);
// log.info("getParam", cmdEnum.getCmd());
// break;
// }
//发布消息
MqttClientUtil.publish_common(topic, sendContent.toString());
}
/**
*
* @param deviceSn
*
* {
* "cmd":" cleanPerson",
* "data":{
* }
* }
*/
public static void publishCleanPerson(String deviceSn){
//获取 发送给 指定id 的app用户的topic
String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
//要发送消息的内容
JSONObject sendContent = new JSONObject();
Map<String,Object> data = new HashMap<>();
sendContent.put("cmd", "cleanPerson");
sendContent.put("data", data);
//发布消息
MqttClientUtil.publish_common(topic, sendContent.toString());
}
/**
*
* @param deviceSn
*
* {
* "cmd":" updateApp",
* "data":{
* "apkUrl":"https://2222.apk"
* }
* }
*/
public static void publishUpdateApp(String deviceSn,String apkUrl){
String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
//要发送消息的内容
JSONObject sendContent = new JSONObject();
Map<String,Object> data = new HashMap<>();
data.put("apkUrl",apkUrl);
sendContent.put("cmd", "updateApp");
sendContent.put("data", data);
//发布消息
MqttClientUtil.publish_common(topic, sendContent.toString());
}
/**
*
* @param deviceSn
* @param content
* {
* "cmd": "faceCount"
* "data": {
* "faceCount"23,
* "faceFailurePerson"
* [730721748076462081, 730721748076462082, 730721748076462083]
* }
* }
*/
private static void subFaceCount(String deviceSn,String content){
JSONObject resJson = JSONObject.parseObject(content);
JSONObject data = resJson.getJSONObject("data");
Integer faceCount = data.getInteger("faceCount");
if(faceCount!=null){
log.info("收到人脸库个数:"+faceCount);
cmdProcess.tenDeviceService.updateFaceCount(deviceSn,faceCount);
}
JSONArray failPerson = data.getJSONArray("faceFailurePerson");
if(failPerson!=null){
List<Integer> memberIdList = failPerson.toJavaList(Integer.class);
cmdProcess.tenDeviceService.updateFailurePerson(deviceSn,memberIdList);
}
}
/**
*
* @param deviceSn
* @param content
* {
* "cmd": "alert"
* "data": {
* "sn"2342342,
* "alertType"数据异常,
* alertLevel:严重,
* alertTime:2020-07-28 10:23:22,
* errorLog:数据同步失败
* }
* }
*/
private static void subAlert(String deviceSn,String content){
JSONObject resJson = JSONObject.parseObject(content);
JSONObject data = resJson.getJSONObject("data");
TenDeviceAlertEntity alert = data.toJavaObject(TenDeviceAlertEntity.class);
cmdProcess.tenDeviceService.addDeviceAlert(alert);
}
/**
*
* @param deviceSn
* @param content
* {
* "cmd": "getParam"
* "data": {
* }
* }
*/
private static void subGetParam(String deviceSn,String content){
JSONObject resJson = JSONObject.parseObject(content);
JSONObject data = resJson.getJSONObject("data");
TenDeviceParamVo paramVo = data.toJavaObject(TenDeviceParamVo.class);
paramVo.setSn(deviceSn);
log.debug("收到mqtt设备参数"+content);
TenDeviceEntity dev = cmdProcess.tenDeviceService.findBySn(deviceSn);
BeanUtils.copyProperties(paramVo,dev);
cmdProcess.tenDeviceService.evictupdateById(dev);
}
/**
*
* @param deviceSn
*
* {
* "cmd":" getParam",
* "data":{
* }
* }
*/
public static void publishGetParam(String deviceSn){
String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
//要发送消息的内容
JSONObject sendContent = new JSONObject();
Map<String,Object> data = new HashMap<>();
sendContent.put("cmd", "getParam");
sendContent.put("data", data);
//发布消息
MqttClientUtil.publish_common(topic, sendContent.toString());
}
/**
*
* @param deviceSn
*
* {
* "cmd":" setParam",
* "data":{
* }
* }
*/
public static void publishSetParam(String deviceSn, TenDeviceParamVo paramVo){
String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
//要发送消息的内容
JSONObject sendContent = new JSONObject();
Map<String,Object> data = new HashMap<>();
sendContent.put("cmd", "setParam");
sendContent.put("data", paramVo);
//发布消息
MqttClientUtil.publish_common(topic, sendContent.toString());
}
/**
*
* @param sysUserId
*
* {
* "cmd":" upRecord",
* "data":{
* }
* }
*/
public static void publishUpRecord(Long sysUserId, TenRecordVo recordVo){
//获取 发送给 指定id 的app用户的topic
String topic = MqttClientUtil.getWebPublishTopic(sysUserId);
//要发送消息的内容
JSONObject sendContent = new JSONObject();
// }
//
// /**
// * {
// * "cmd": "remoteOpenDoor",
// * "data": {
// * "personId": "721041148851781632",
// * }
// * }
// * @param deviceSn
// * @param memberId
// */
// public static void publishRemoteOpenDoor(String deviceSn,Integer memberId){
// //获取 发送给 指定id 的app用户的topic
// String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
//
// //要发送消息的内容
// JSONObject sendContent = new JSONObject();
//// sendContent.put("cmd", cmd_id + "/response");
//// sendContent.put("ret", "0");
//// sendContent.put("msg", "测试消息已经处成功处理");
//// sendContent.put("code", 0);
// Map<String,Object> data = new HashMap<>();
sendContent.put("cmd", "upRecord");
sendContent.put("data", recordVo);
//发布消息
MqttClientUtil.publish_common(topic, sendContent.toString());
}
}
//// data.put("personId",personId);
// TenDeviceEntity device = cmdProcess.tenDeviceService.findBySn(deviceSn);
//// TenPersonEntity personEntity = cmdProcess.tenDeviceService.getByPersonId(Long.parseLong(personId),device.getCellId());
// data.put("memberId",memberId);
// data.put("deviceSn",deviceSn);
// sendContent.put("cmd", "remoteOpenDoor");
// sendContent.put("data", data);
// //发布消息
// MqttClientUtil.publish_common(topic, sendContent.toString());
//
// }
//
// /**
// *
// * @param deviceSn
// * @param content
// * {
// * "cmd":"remoteOpenDoor",
// * "data":{
// * "personId":"721041148851781632",
// * "recordTime":"2020-07-06 14:36:23",
// * "openType":2, //1人脸识别2远程一键开门
// * "recordFaceStr":"/9j/4AAQSkZJRgABAQAAAQABAAD"
// * }
// * }
// */
// private static void subscribeRemoteOpenDoor(String deviceSn,String content){
// JSONObject resJson = JSONObject.parseObject(content);
// JSONObject data = resJson.getJSONObject("data");
//// String personId = data.getString("personId");
// Integer memberId = data.getInteger("memberId");
// String recordTime = data.getString("recordTime");
// Integer openType = data.getInteger("openType");
//
// TenDeviceEntity device = cmdProcess.tenDeviceService.findBySn(deviceSn);
// TenPersonEntity person = cmdProcess.tenDeviceService.getByMemberId(memberId,device.getCellId());
//
// TenRecordEntity record = new TenRecordEntity();
// record.setDeviceSn(deviceSn);
// record.setPersonId(person.getPersonId());
// record.setCellId(device.getCellId());
//// DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//// LocalDateTime parse = LocalDateTime.parse(recordTime, dtf);
// record.setRecordTime(new Date());
// record.setOpenType(openType);
// //添加到redis
//// cmdProcess.redisUtils.set(personId+"-"+deviceSn,openDate,60L);
// cmdProcess.redisUtils.set(person.getPersonId()+"-"+deviceSn,recordTime,10L);
// //添加到记录里
//// log.info("----------------------------------------收到意见开门记录");
// cmdProcess.tenDeviceService.upRecord(record);
// }
//
// /**
// *
// * @param deviceSn
// *
// * {
// * "cmd":" personChange",
// * "data":{
// * }
// * }
// */
//
// public static void publishPersonChange(String deviceSn){
// //获取 发送给 指定id 的app用户的topic
// String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
// //要发送消息的内容
// JSONObject sendContent = new JSONObject();
// Map<String,Object> data = new HashMap<>();
// sendContent.put("cmd", "personChange");
// sendContent.put("data", data);
// //发布消息
// MqttClientUtil.publish_common(topic, sendContent.toString());
// }
//
//
// /**
// *
// * @param deviceSn
// *
// * {
// * "cmd":"addPerson",
// * "data":{TenPersonVo
// * }
// * }
// */
//
// public static void publishAddPerson(String deviceSn, TenPersonVo personVo){
// //获取 发送给 指定id 的app用户的topic
// String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
// //要发送消息的内容
// JSONObject sendContent = new JSONObject();
//// Map<String,Object> data = new HashMap<>();
// sendContent.put("cmd", "addPerson");
// sendContent.put("data", personVo);
//// if(((JSONObject)sendContent.get("data")).get("liveStart")!=null){
//// ((JSONObject)sendContent.get("data")).put("liveStart", DateUtils.format(personVo.getLiveStart(),DateUtils.DATE_TIME_PATTERN));
//// }
////
//// if(((JSONObject)sendContent.get("data")).get("liveEnd")!=null){
//// ((JSONObject)sendContent.get("data")).put("liveEnd", DateUtils.format(personVo.getLiveEnd(),DateUtils.DATE_TIME_PATTERN));
//// }
//
// //发布消息
// MqttClientUtil.publish_common(topic, sendContent.toString());
// }
//
//
//
//
// /**
// *
// * @param deviceSn
// *
// * {
// * "cmd":" cleanPerson",
// * "data":{
// * }
// * }
// */
// public static void publishCleanPerson(String deviceSn){
// //获取 发送给 指定id 的app用户的topic
// String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
// //要发送消息的内容
// JSONObject sendContent = new JSONObject();
// Map<String,Object> data = new HashMap<>();
// sendContent.put("cmd", "cleanPerson");
// sendContent.put("data", data);
// //发布消息
// MqttClientUtil.publish_common(topic, sendContent.toString());
// }
//
// /**
// *
// * @param deviceSn
// *
// * {
// * "cmd":" updateApp",
// * "data":{
// * "apkUrl":"https://2222.apk"
// * }
// * }
// */
// public static void publishUpdateApp(String deviceSn,String apkUrl){
// String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
// //要发送消息的内容
// JSONObject sendContent = new JSONObject();
// Map<String,Object> data = new HashMap<>();
// data.put("apkUrl",apkUrl);
// sendContent.put("cmd", "updateApp");
// sendContent.put("data", data);
// //发布消息
// MqttClientUtil.publish_common(topic, sendContent.toString());
// }
//
//
//
// /**
// *
// * @param deviceSn
// * @param content
// * {
// * "cmd": "faceCount"
// * "data": {
// * "faceCount"23,
// * "faceFailurePerson"
// * [730721748076462081, 730721748076462082, 730721748076462083]
// * }
// * }
// */
// private static void subFaceCount(String deviceSn,String content){
// JSONObject resJson = JSONObject.parseObject(content);
// JSONObject data = resJson.getJSONObject("data");
// Integer faceCount = data.getInteger("faceCount");
// if(faceCount!=null){
// log.info("收到人脸库个数:"+faceCount);
// cmdProcess.tenDeviceService.updateFaceCount(deviceSn,faceCount);
// }
// JSONArray failPerson = data.getJSONArray("faceFailurePerson");
// if(failPerson!=null){
// List<Integer> memberIdList = failPerson.toJavaList(Integer.class);
// cmdProcess.tenDeviceService.updateFailurePerson(deviceSn,memberIdList);
// }
// }
//
// /**
// *
// * @param deviceSn
// * @param content
// * {
// * "cmd": "alert"
// * "data": {
// * "sn"2342342,
// * "alertType"数据异常,
// * alertLevel:严重,
// * alertTime:2020-07-28 10:23:22,
// * errorLog:数据同步失败
// * }
// * }
// */
// private static void subAlert(String deviceSn,String content){
// JSONObject resJson = JSONObject.parseObject(content);
// JSONObject data = resJson.getJSONObject("data");
// TenDeviceAlertEntity alert = data.toJavaObject(TenDeviceAlertEntity.class);
// cmdProcess.tenDeviceService.addDeviceAlert(alert);
// }
//
//
//
//
// /**
// *
// * @param deviceSn
// * @param content
// * {
// * "cmd": "getParam"
// * "data": {
//
// * }
// * }
// */
// private static void subGetParam(String deviceSn,String content){
// JSONObject resJson = JSONObject.parseObject(content);
// JSONObject data = resJson.getJSONObject("data");
// TenDeviceParamVo paramVo = data.toJavaObject(TenDeviceParamVo.class);
// paramVo.setSn(deviceSn);
// log.debug("收到mqtt设备参数"+content);
// TenDeviceEntity dev = cmdProcess.tenDeviceService.findBySn(deviceSn);
// BeanUtils.copyProperties(paramVo,dev);
// cmdProcess.tenDeviceService.evictupdateById(dev);
// }
//
//
//
// /**
// *
// * @param deviceSn
// *
// * {
// * "cmd":" getParam",
// * "data":{
// * }
// * }
// */
// public static void publishGetParam(String deviceSn){
// String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
// //要发送消息的内容
// JSONObject sendContent = new JSONObject();
// Map<String,Object> data = new HashMap<>();
// sendContent.put("cmd", "getParam");
// sendContent.put("data", data);
// //发布消息
// MqttClientUtil.publish_common(topic, sendContent.toString());
// }
//
//
// /**
// *
// * @param deviceSn
// *
// * {
// * "cmd":" setParam",
// * "data":{
// * }
// * }
// */
// public static void publishSetParam(String deviceSn, TenDeviceParamVo paramVo){
// String topic = MqttClientUtil.getDevicePublishTopic(deviceSn);
// //要发送消息的内容
// JSONObject sendContent = new JSONObject();
// Map<String,Object> data = new HashMap<>();
// sendContent.put("cmd", "setParam");
// sendContent.put("data", paramVo);
// //发布消息
// MqttClientUtil.publish_common(topic, sendContent.toString());
// }
//
//
// /**
// *
// * @param sysUserId
// *
// * {
// * "cmd":" upRecord",
// * "data":{
// * }
// * }
// */
//
// public static void publishUpRecord(Long sysUserId, TenRecordVo recordVo){
// //获取 发送给 指定id 的app用户的topic
// String topic = MqttClientUtil.getWebPublishTopic(sysUserId);
// //要发送消息的内容
// JSONObject sendContent = new JSONObject();
//// Map<String,Object> data = new HashMap<>();
// sendContent.put("cmd", "upRecord");
// sendContent.put("data", recordVo);
// //发布消息
// MqttClientUtil.publish_common(topic, sendContent.toString());
// }
//}

View File

@ -1,162 +1,162 @@
package net.shapelight.modules.dev.mqtt;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import net.shapelight.common.config.GlobalValue;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
//import org.json.JSONArray;
//import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Component
public class EmqHttpApi {
private static final String getClients = "/api/v4/clients";
private static final String getClient = "/api/v4/clients/";
private static final String getWebClients = "/api/v4/clients/username/web";
@Autowired
private GlobalValue globalValue;
// private static String mqttUsername = "11f6a78ee6922";
// private static String mqttPassword = "MjkzODM4Mzc2NTMyNjIzOTg3NTI5MDMwMzU3NjMwOTc2MDA";
// private static String mqttApi = "http://192.168.1.111:8081";
/**
* 查看设备在线状态
* @param devSn
* @return
*/
public boolean getClient(String devSn){
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 设置BasicAuth
CredentialsProvider provider = new BasicCredentialsProvider();
// Create the authentication scope
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// Create credential pair在此处填写用户名和密码
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(globalValue.getMqttUsername(),
globalValue.getMqttPassword());
// Inject the credentials
provider.setCredentials(scope, credentials);
// Set the default credentials provider
httpClientBuilder.setDefaultCredentialsProvider(provider);
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
String result = "";
HttpGet httpGet = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
httpGet = new HttpGet(globalValue.getMqttApi()+"/"+getClient+"/"+devSn);
try {
httpResponse = closeableHttpClient.execute(httpGet);
entity = httpResponse.getEntity();
if( entity != null ){
result = EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 关闭连接
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject json = JSONObject.parseObject(result);
JSONArray devArray = json.getJSONArray("data");
// JSONObject json = new JSONObject(result);
//package net.shapelight.modules.dev.mqtt;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.google.gson.JsonObject;
//import lombok.extern.slf4j.Slf4j;
//import net.shapelight.common.config.GlobalValue;
//import org.apache.http.HttpEntity;
//import org.apache.http.HttpResponse;
//import org.apache.http.auth.AuthScope;
//import org.apache.http.auth.UsernamePasswordCredentials;
//import org.apache.http.client.ClientProtocolException;
//import org.apache.http.client.CredentialsProvider;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.impl.client.BasicCredentialsProvider;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClientBuilder;
//import org.apache.http.util.EntityUtils;
////import org.json.JSONArray;
////import org.json.JSONObject;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.List;
//
//@Slf4j
//@Component
//public class EmqHttpApi {
// private static final String getClients = "/api/v4/clients";
// private static final String getClient = "/api/v4/clients/";
// private static final String getWebClients = "/api/v4/clients/username/web";
// @Autowired
// private GlobalValue globalValue;
//
//// private static String mqttUsername = "11f6a78ee6922";
//// private static String mqttPassword = "MjkzODM4Mzc2NTMyNjIzOTg3NTI5MDMwMzU3NjMwOTc2MDA";
//// private static String mqttApi = "http://192.168.1.111:8081";
//
//
// /**
// * 查看设备在线状态
// * @param devSn
// * @return
// */
// public boolean getClient(String devSn){
// // 创建HttpClientBuilder
// HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// // 设置BasicAuth
// CredentialsProvider provider = new BasicCredentialsProvider();
// // Create the authentication scope
// AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// // Create credential pair在此处填写用户名和密码
// UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(globalValue.getMqttUsername(),
// globalValue.getMqttPassword());
// // Inject the credentials
// provider.setCredentials(scope, credentials);
// // Set the default credentials provider
// httpClientBuilder.setDefaultCredentialsProvider(provider);
// // HttpClient
// CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
//
// String result = "";
// HttpGet httpGet = null;
// HttpResponse httpResponse = null;
// HttpEntity entity = null;
// httpGet = new HttpGet(globalValue.getMqttApi()+"/"+getClient+"/"+devSn);
// try {
// httpResponse = closeableHttpClient.execute(httpGet);
// entity = httpResponse.getEntity();
// if( entity != null ){
// result = EntityUtils.toString(entity);
// }
// } catch (ClientProtocolException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// // 关闭连接
// try {
// closeableHttpClient.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// JSONObject json = JSONObject.parseObject(result);
// JSONArray devArray = json.getJSONArray("data");
//log.info(result);
if(devArray.size() == 0){
return false;
}else{
return true;
}
}
public List<Long> getWebClients(){
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 设置BasicAuth
CredentialsProvider provider = new BasicCredentialsProvider();
// Create the authentication scope
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// Create credential pair在此处填写用户名和密码
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(globalValue.getMqttUsername(),
globalValue.getMqttPassword());
// Inject the credentials
provider.setCredentials(scope, credentials);
// Set the default credentials provider
httpClientBuilder.setDefaultCredentialsProvider(provider);
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
String result = "";
HttpGet httpGet = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
// 192.168.1.111:8081/api/v4/clients/username/web
httpGet = new HttpGet(globalValue.getMqttApi()+"/"+getWebClients);
try {
httpResponse = closeableHttpClient.execute(httpGet);
entity = httpResponse.getEntity();
if( entity != null ){
result = EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 关闭连接
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject json = JSONObject.parseObject(result);
JSONArray webArray = json.getJSONArray("data");
List<Long> cellIds = new ArrayList<>();
if(webArray.size()>0){
for(int i = 0;i<webArray.size();i++){
JSONObject webClient = webArray.getJSONObject(i);
cellIds.add(webClient.getLong("clientid"));
}
}
return cellIds;
}
// public static void main(String args[]){
// getWebClients();
//
//// JSONObject json = new JSONObject(result);
//// JSONArray devArray = json.getJSONArray("data");
// //log.info(result);
// if(devArray.size() == 0){
// return false;
// }else{
// return true;
// }
// }
}
//
//
//
// public List<Long> getWebClients(){
// // 创建HttpClientBuilder
// HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// // 设置BasicAuth
// CredentialsProvider provider = new BasicCredentialsProvider();
// // Create the authentication scope
// AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// // Create credential pair在此处填写用户名和密码
// UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(globalValue.getMqttUsername(),
// globalValue.getMqttPassword());
// // Inject the credentials
// provider.setCredentials(scope, credentials);
// // Set the default credentials provider
// httpClientBuilder.setDefaultCredentialsProvider(provider);
// // HttpClient
// CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
//
// String result = "";
// HttpGet httpGet = null;
// HttpResponse httpResponse = null;
// HttpEntity entity = null;
// // 192.168.1.111:8081/api/v4/clients/username/web
// httpGet = new HttpGet(globalValue.getMqttApi()+"/"+getWebClients);
// try {
// httpResponse = closeableHttpClient.execute(httpGet);
// entity = httpResponse.getEntity();
// if( entity != null ){
// result = EntityUtils.toString(entity);
// }
// } catch (ClientProtocolException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// // 关闭连接
// try {
// closeableHttpClient.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// JSONObject json = JSONObject.parseObject(result);
// JSONArray webArray = json.getJSONArray("data");
// List<Long> cellIds = new ArrayList<>();
// if(webArray.size()>0){
// for(int i = 0;i<webArray.size();i++){
// JSONObject webClient = webArray.getJSONObject(i);
// cellIds.add(webClient.getLong("clientid"));
// }
//
// }
// return cellIds;
// }
//
//// public static void main(String args[]){
//// getWebClients();
//// }
//}

View File

@ -1,50 +1,50 @@
package net.shapelight.modules.dev.mqtt;
//import org.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @author
*/
public class HandlerThread implements Runnable {
private String topic;
private String content;
public HandlerThread(String topic, String content) {
this.topic = topic;
this.content = content;
}
/*
e.g.,
http://172.168.2.10/action/SetAudio
下发body
{
"operator": "SetAudio",
"info": {
"DeviceID":1300001,
"AudioType":0,
"AudioName":"welcome.wav"
}
}
*/
@Override
public void run() {
if (this.content.length() > 0) {
try {
// JSONObject json = new JSONObject(content);
JSONObject json = JSON.parseObject(content);
// String cmd_id = json.optString("cmd");
String cmd_id = json.getString("cmd");
CmdProcess.execute(topic,content);
} catch (Throwable e) {
System.out.println("mqtt HandlerThread run");
e.printStackTrace();
}
}
}
}
//package net.shapelight.modules.dev.mqtt;
//
////import org.json.JSONObject;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//
///**
// * @author
// */
//public class HandlerThread implements Runnable {
//
// private String topic;
// private String content;
//
// public HandlerThread(String topic, String content) {
// this.topic = topic;
// this.content = content;
// }
//
// /*
// e.g.,
//http://172.168.2.10/action/SetAudio
//下发body
//{
//"operator": "SetAudio",
//"info": {
//"DeviceID":1300001,
//"AudioType":0,
//"AudioName":"welcome.wav"
//}
//}
// */
//
// @Override
// public void run() {
// if (this.content.length() > 0) {
// try {
//// JSONObject json = new JSONObject(content);
// JSONObject json = JSON.parseObject(content);
//// String cmd_id = json.optString("cmd");
// String cmd_id = json.getString("cmd");
// CmdProcess.execute(topic,content);
// } catch (Throwable e) {
// System.out.println("mqtt HandlerThread run");
// e.printStackTrace();
// }
// }
// }
//}

View File

@ -1,234 +1,234 @@
package net.shapelight.modules.dev.mqtt;
import lombok.extern.slf4j.Slf4j;
import net.shapelight.common.config.GlobalValue;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
/**
*
*/
@Slf4j
@Component
public class MqttClientUtil {
private static MqttClientUtil mqttClientUtil;
@Autowired
private GlobalValue globalValue;
public static MqttAsyncClient mqttSubscribeClient;
public static MqttAsyncClient mqttPublishClient;
public static String TOPIC_PREFIX_DEVICE = "device";
// public static String TOPIC_PREFIX_APP = "app";
public static String TOPIC_PREFIX_WEB = "web";
private static MqttSubscribeClientCallback mqttClientSubscribeCallback = new MqttSubscribeClientCallback();
/**
* 要发布的消息队列
*/
private static LinkedBlockingQueue<String[]> queue = new LinkedBlockingQueue<String[]>();
public static ExecutorService executorService = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors() + 1);
/**
* mqtt broker 连接配置,填自己的mqtt地址,及账号密码
*/
// private static String broker = globalValue.getMqttUrl();
// private static String username = globalValue.getMqttUsername();
// private static String password = globalValue.getMqttPassword();
// private static String broker = "tcp://192.168.1.111:1883";
// private static String username = "admin";
// private static String password = "public";
public void setGlobalValue(GlobalValue globalValue) {
this.globalValue = globalValue;
}
@PostConstruct
public void init(){
mqttClientUtil = this;
mqttClientUtil.globalValue = this.globalValue;
}
public static void createClient() {
// System.out.println("mqtt createClient, " + broker);
// String clientId = "mqttserver";// + String.valueOf(System.currentTimeMillis());
// System.out.println("mqtt sub_clientId="+clientId+",pub_clientId="+clientId+"-publish");
try {
//subscribe client
mqttSubscribeClient = new MqttAsyncClient(mqttClientUtil.globalValue.getMqttUrl(), "server-sub-" + System.currentTimeMillis(), new MemoryPersistence());
mqttSubscribeClient.setCallback(mqttClientSubscribeCallback);
//publish client
mqttPublishClient = new MqttAsyncClient(mqttClientUtil.globalValue.getMqttUrl(), "server-pub-" + System.currentTimeMillis(), new MemoryPersistence());
mqttPublishClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable arg0) {
MqttClientUtil.publishReconnect();
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
}
@Override
public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
}
});
subscribeReconnect();
publishReconnect();
} catch (MqttException me) {
// log.error("reason " + me.getReasonCode());
// log.error("msg " + me.getMessage());
// log.error("loc " + me.getLocalizedMessage());
// log.error("cause " + me.getCause());
// System.out.println("reason " + me.getReasonCode());
// System.out.println("msg " + me.getMessage());
// System.out.println("loc " + me.getLocalizedMessage());
// System.out.println("cause " + me.getCause());
// System.out.println("excep " + me);
me.printStackTrace();
}
//启动发布消息的线程, 循环从队列queue 获取要发布的消息 发布也就是说要发消息只要将消息写入队列queue
new Thread(new PublishThread()).start();
}
/**
* 发布消息
* @param topic
* @param content
*/
public static void publish_common(String topic, String content) {
String[] array = { topic, content };
//要发布的消息入队列
//PublishThread 会循环从这个队列获取消息发布.
queue.offer(array);
}
public static String[] poll() {
return (String[]) queue.poll();
}
public static String getDeviceIdByTopic(String topic) {
String[] array = topic.split("/");
if (array.length >= 2) {
return array[1];
}
return "";
}
public static String getDevicePublishTopic(String deviceId) {
return TOPIC_PREFIX_DEVICE + "/" + deviceId + "/server";
}
public static String getWebPublishTopic(Long sysUserId) {
return TOPIC_PREFIX_WEB + "/" + sysUserId + "/server";
}
// public static String getAppPublishTopic(String deviceId) {
// return TOPIC_PREFIX_APP + "/" + deviceId + "/server";
//package net.shapelight.modules.dev.mqtt;
//
//import lombok.extern.slf4j.Slf4j;
//import net.shapelight.common.config.GlobalValue;
//import org.eclipse.paho.client.mqttv3.*;
//import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//import java.util.concurrent.LinkedBlockingQueue;
//
///**
// *
// */
//@Slf4j
//@Component
//public class MqttClientUtil {
// private static MqttClientUtil mqttClientUtil;
//
// @Autowired
// private GlobalValue globalValue;
//
// public static MqttAsyncClient mqttSubscribeClient;
// public static MqttAsyncClient mqttPublishClient;
// public static String TOPIC_PREFIX_DEVICE = "device";
//// public static String TOPIC_PREFIX_APP = "app";
//public static String TOPIC_PREFIX_WEB = "web";
// private static MqttSubscribeClientCallback mqttClientSubscribeCallback = new MqttSubscribeClientCallback();
//
// /**
// * 要发布的消息队列
// */
// private static LinkedBlockingQueue<String[]> queue = new LinkedBlockingQueue<String[]>();
// public static ExecutorService executorService = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors() + 1);
//
// /**
// * mqtt broker 连接配置,填自己的mqtt地址,及账号密码
// */
//// private static String broker = globalValue.getMqttUrl();
//// private static String username = globalValue.getMqttUsername();
//// private static String password = globalValue.getMqttPassword();
//
//// private static String broker = "tcp://192.168.1.111:1883";
//// private static String username = "admin";
//// private static String password = "public";
//
// public void setGlobalValue(GlobalValue globalValue) {
// this.globalValue = globalValue;
// }
//
// @PostConstruct
// public void init(){
// mqttClientUtil = this;
// mqttClientUtil.globalValue = this.globalValue;
// }
//
// public static void createClient() {
//// System.out.println("mqtt createClient, " + broker);
//// String clientId = "mqttserver";// + String.valueOf(System.currentTimeMillis());
//// System.out.println("mqtt sub_clientId="+clientId+",pub_clientId="+clientId+"-publish");
// try {
// //subscribe client
// mqttSubscribeClient = new MqttAsyncClient(mqttClientUtil.globalValue.getMqttUrl(), "server-sub-" + System.currentTimeMillis(), new MemoryPersistence());
// mqttSubscribeClient.setCallback(mqttClientSubscribeCallback);
//
// //publish client
// mqttPublishClient = new MqttAsyncClient(mqttClientUtil.globalValue.getMqttUrl(), "server-pub-" + System.currentTimeMillis(), new MemoryPersistence());
// mqttPublishClient.setCallback(new MqttCallback() {
// @Override
// public void connectionLost(Throwable arg0) {
// MqttClientUtil.publishReconnect();
// }
// @Override
// public void deliveryComplete(IMqttDeliveryToken arg0) {
// }
// @Override
// public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
// }
// });
// subscribeReconnect();
// publishReconnect();
// } catch (MqttException me) {
//// log.error("reason " + me.getReasonCode());
//// log.error("msg " + me.getMessage());
//// log.error("loc " + me.getLocalizedMessage());
//// log.error("cause " + me.getCause());
//// System.out.println("reason " + me.getReasonCode());
//// System.out.println("msg " + me.getMessage());
//// System.out.println("loc " + me.getLocalizedMessage());
//// System.out.println("cause " + me.getCause());
//// System.out.println("excep " + me);
// me.printStackTrace();
// }
//
// //启动发布消息的线程, 循环从队列queue 获取要发布的消息 发布也就是说要发消息只要将消息写入队列queue
// new Thread(new PublishThread()).start();
// }
/**
* 订阅连接 重连
*/
public static void subscribeReconnect() {
if (mqttSubscribeClient != null) {
// System.out.println("mqtt subscribeReconnect");
try {
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setMaxInflight(100000);
connOpts.setUserName(mqttClientUtil.globalValue.getMqttUsername());
connOpts.setPassword(mqttClientUtil.globalValue.getMqttPassword().toCharArray());
mqttSubscribeClient.connect(connOpts, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
try {
log.info("mqtt 订阅连接 已连接!");
// System.out.println("mqtt 已连接!");
MqttClientUtil.mqttSubscribeClient.subscribe(MqttClientUtil.TOPIC_PREFIX_DEVICE + "/+/client", 0);
// MqttClientUtil.mqttSubscribeClient.subscribe(MqttClientUtil.TOPIC_PREFIX_APP + "/+/client", 0);
// System.out.println("订阅主题:"+MqttClientUtil.TOPIC_PREFIX_DEVICE + "/+/client");
// System.out.println("订阅主题:"+MqttClientUtil.TOPIC_PREFIX_APP + "/+/client");
} catch (MqttException me) {
// System.out.println("reason " + me.getReasonCode());
// System.out.println("msg " + me.getMessage());
// System.out.println("loc " + me.getLocalizedMessage());
// System.out.println("cause " + me.getCause());
// System.out.println("excep " + me);
me.printStackTrace();
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// System.out.println("mqtt 没有连接上:" + exception.getMessage());
try {
Thread.sleep(60000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
MqttClientUtil.subscribeReconnect();
}
});
} catch (MqttException me) {
// System.out.println("reason " + me.getReasonCode());
// System.out.println("msg " + me.getMessage());
// System.out.println("loc " + me.getLocalizedMessage());
// System.out.println("cause " + me.getCause());
// System.out.println("excep " + me);
me.printStackTrace();
}
}
}
/**
* 发布连接 重连
*/
public static void publishReconnect() {
if (mqttPublishClient != null) {
// System.out.println("mqtt publishReconnect");
try {
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setMaxInflight(100000);
connOpts.setUserName(mqttClientUtil.globalValue.getMqttUsername());
connOpts.setPassword(mqttClientUtil.globalValue.getMqttPassword().toCharArray());
mqttPublishClient.connect(connOpts, null, new IMqttActionListener() {
@Override
public void onFailure(IMqttToken arg0, Throwable arg1) {
// System.out.println("mqtt publish client connect is failed" + arg1.getMessage());
try {
Thread.sleep(30000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
MqttClientUtil.publishReconnect();
}
@Override
public void onSuccess(IMqttToken arg0) {
log.info("mqtt 发布连接 已连接!");
// System.out.println("mqtt publish client is connected");
}
});
} catch (MqttException me) {
// System.out.println("reason " + me.getReasonCode());
// System.out.println("msg " + me.getMessage());
// System.out.println("loc " + me.getLocalizedMessage());
// System.out.println("cause " + me.getCause());
// System.out.println("excep " + me);
me.printStackTrace();
}
}
}
}
//
// /**
// * 发布消息
// * @param topic
// * @param content
// */
// public static void publish_common(String topic, String content) {
// String[] array = { topic, content };
// //要发布的消息入队列
// //PublishThread 会循环从这个队列获取消息发布.
// queue.offer(array);
// }
//
// public static String[] poll() {
// return (String[]) queue.poll();
// }
//
// public static String getDeviceIdByTopic(String topic) {
// String[] array = topic.split("/");
// if (array.length >= 2) {
// return array[1];
// }
// return "";
// }
//
// public static String getDevicePublishTopic(String deviceId) {
// return TOPIC_PREFIX_DEVICE + "/" + deviceId + "/server";
// }
//
// public static String getWebPublishTopic(Long sysUserId) {
// return TOPIC_PREFIX_WEB + "/" + sysUserId + "/server";
// }
//
//// public static String getAppPublishTopic(String deviceId) {
//// return TOPIC_PREFIX_APP + "/" + deviceId + "/server";
//// }
//
// /**
// * 订阅连接 重连
// */
// public static void subscribeReconnect() {
// if (mqttSubscribeClient != null) {
//// System.out.println("mqtt subscribeReconnect");
// try {
// MqttConnectOptions connOpts = new MqttConnectOptions();
// connOpts.setCleanSession(true);
// connOpts.setMaxInflight(100000);
// connOpts.setUserName(mqttClientUtil.globalValue.getMqttUsername());
// connOpts.setPassword(mqttClientUtil.globalValue.getMqttPassword().toCharArray());
//
// mqttSubscribeClient.connect(connOpts, null, new IMqttActionListener() {
// @Override
// public void onSuccess(IMqttToken asyncActionToken) {
// try {
// log.info("mqtt 订阅连接 已连接!");
//// System.out.println("mqtt 已连接!");
// MqttClientUtil.mqttSubscribeClient.subscribe(MqttClientUtil.TOPIC_PREFIX_DEVICE + "/+/client", 0);
//// MqttClientUtil.mqttSubscribeClient.subscribe(MqttClientUtil.TOPIC_PREFIX_APP + "/+/client", 0);
//
//// System.out.println("订阅主题:"+MqttClientUtil.TOPIC_PREFIX_DEVICE + "/+/client");
//// System.out.println("订阅主题:"+MqttClientUtil.TOPIC_PREFIX_APP + "/+/client");
// } catch (MqttException me) {
//// System.out.println("reason " + me.getReasonCode());
//// System.out.println("msg " + me.getMessage());
//// System.out.println("loc " + me.getLocalizedMessage());
//// System.out.println("cause " + me.getCause());
//// System.out.println("excep " + me);
// me.printStackTrace();
// }
// }
//
// @Override
// public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//// System.out.println("mqtt 没有连接上:" + exception.getMessage());
// try {
// Thread.sleep(60000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// MqttClientUtil.subscribeReconnect();
// }
// });
// } catch (MqttException me) {
//// System.out.println("reason " + me.getReasonCode());
//// System.out.println("msg " + me.getMessage());
//// System.out.println("loc " + me.getLocalizedMessage());
//// System.out.println("cause " + me.getCause());
//// System.out.println("excep " + me);
// me.printStackTrace();
// }
// }
// }
//
// /**
// * 发布连接 重连
// */
// public static void publishReconnect() {
// if (mqttPublishClient != null) {
//// System.out.println("mqtt publishReconnect");
// try {
// MqttConnectOptions connOpts = new MqttConnectOptions();
// connOpts.setCleanSession(true);
// connOpts.setMaxInflight(100000);
// connOpts.setUserName(mqttClientUtil.globalValue.getMqttUsername());
// connOpts.setPassword(mqttClientUtil.globalValue.getMqttPassword().toCharArray());
// mqttPublishClient.connect(connOpts, null, new IMqttActionListener() {
// @Override
// public void onFailure(IMqttToken arg0, Throwable arg1) {
//// System.out.println("mqtt publish client connect is failed" + arg1.getMessage());
// try {
// Thread.sleep(30000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// MqttClientUtil.publishReconnect();
// }
//
// @Override
// public void onSuccess(IMqttToken arg0) {
// log.info("mqtt 发布连接 已连接!");
//// System.out.println("mqtt publish client is connected");
// }
// });
// } catch (MqttException me) {
//// System.out.println("reason " + me.getReasonCode());
//// System.out.println("msg " + me.getMessage());
//// System.out.println("loc " + me.getLocalizedMessage());
//// System.out.println("cause " + me.getCause());
//// System.out.println("excep " + me);
// me.printStackTrace();
// }
// }
// }
//}

View File

@ -1,37 +1,37 @@
package net.shapelight.modules.dev.mqtt;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
/**
* @author
*/
@Slf4j
public class MqttSubscribeClientCallback implements MqttCallback {
@Override
public void connectionLost(Throwable arg0) {
// System.out.println("mqtt 失去了连接");
log.info("mqtt 失去连接");
MqttClientUtil.subscribeReconnect();
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
log.info("mqtt 发送完成");
// System.out.println("mqtt 发送完成!");
}
@Override
public void messageArrived(String topic, MqttMessage message)
throws Exception {
String content = new String(message.getPayload(), "utf-8");
// System.out.println("收到mqtt消息,topic: " + topic + " ,content: " + content);
log.info("收到mqtt消息,topic: " + topic + " ,content: " + content+"\n");
if (MqttClientUtil.executorService != null) {
MqttClientUtil.executorService.execute(new HandlerThread(topic, content));
}
}
}
//package net.shapelight.modules.dev.mqtt;
//
//import lombok.extern.slf4j.Slf4j;
//import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
//import org.eclipse.paho.client.mqttv3.MqttCallback;
//import org.eclipse.paho.client.mqttv3.MqttMessage;
//
///**
// * @author
// */
//@Slf4j
//public class MqttSubscribeClientCallback implements MqttCallback {
//
// @Override
// public void connectionLost(Throwable arg0) {
//// System.out.println("mqtt 失去了连接");
// log.info("mqtt 失去连接");
// MqttClientUtil.subscribeReconnect();
// }
//
// @Override
// public void deliveryComplete(IMqttDeliveryToken arg0) {
// log.info("mqtt 发送完成");
//// System.out.println("mqtt 发送完成!");
// }
//
// @Override
// public void messageArrived(String topic, MqttMessage message)
// throws Exception {
// String content = new String(message.getPayload(), "utf-8");
//// System.out.println("收到mqtt消息,topic: " + topic + " ,content: " + content);
// log.info("收到mqtt消息,topic: " + topic + " ,content: " + content+"\n");
// if (MqttClientUtil.executorService != null) {
// MqttClientUtil.executorService.execute(new HandlerThread(topic, content));
// }
// }
//}

View File

@ -1,61 +1,61 @@
package net.shapelight.modules.dev.mqtt;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import java.io.UnsupportedEncodingException;
/**
* @author
*/
@Slf4j
public class PublishThread implements Runnable {
@Override
public void run()
{
String[] obj = null;
// System.out.println("mqtt publish thread start");
while (true)
{
obj = MqttClientUtil.poll();
if (obj != null) {
String topic = obj[0];
String content = obj[1];
// System.out.println("mqtt从队列取出topic:"+topic+",content:"+content);
byte[] array = null;
try {
array = content.getBytes("utf-8");
}
catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
MqttMessage message2 = new MqttMessage(array);
message2.setQos(1);
try
{
MqttClientUtil.mqttPublishClient.publish(topic, message2);
log.info("发送mqtt消息,topic: "+topic+" ,content: "+content);
// System.out.println("发送mqtt消息,topic: "+topic+" ,content: "+content);
} catch (MqttPersistenceException e) {
e.printStackTrace();
} catch (MqttException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
else{
try {
Thread.sleep(1000L);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
//package net.shapelight.modules.dev.mqtt;
//
//import lombok.extern.slf4j.Slf4j;
//import org.eclipse.paho.client.mqttv3.MqttException;
//import org.eclipse.paho.client.mqttv3.MqttMessage;
//import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
//
//import java.io.UnsupportedEncodingException;
//
///**
// * @author
// */
//@Slf4j
//public class PublishThread implements Runnable {
// @Override
// public void run()
// {
// String[] obj = null;
//// System.out.println("mqtt publish thread start");
// while (true)
// {
// obj = MqttClientUtil.poll();
// if (obj != null) {
// String topic = obj[0];
// String content = obj[1];
//// System.out.println("mqtt从队列取出topic:"+topic+",content:"+content);
// byte[] array = null;
// try {
// array = content.getBytes("utf-8");
// }
// catch (UnsupportedEncodingException e1) {
// e1.printStackTrace();
// }
//
// MqttMessage message2 = new MqttMessage(array);
// message2.setQos(1);
// try
// {
// MqttClientUtil.mqttPublishClient.publish(topic, message2);
// log.info("发送mqtt消息,topic: "+topic+" ,content: "+content);
//// System.out.println("发送mqtt消息,topic: "+topic+" ,content: "+content);
// } catch (MqttPersistenceException e) {
// e.printStackTrace();
// } catch (MqttException e) {
// e.printStackTrace();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// else{
// try {
// Thread.sleep(1000L);
// }
// catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
// }
//
//}

View File

@ -1,21 +1,21 @@
package net.shapelight.modules.dev.mqtt;
public class RunMqtt {
public static void main(String[] args){
//mqtt服务启动
MqttClientUtil.createClient();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
//释放工作
//...
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
}
//package net.shapelight.modules.dev.mqtt;
//
//public class RunMqtt {
// public static void main(String[] args){
// //mqtt服务启动
// MqttClientUtil.createClient();
//
// Runtime.getRuntime().addShutdownHook(new Thread() {
// @Override
// public void run() {
// try {
// //释放工作
// //...
//
// } catch (Throwable e) {
// e.printStackTrace();
// }
// }
// });
// }
//}

View File

@ -1,23 +1,23 @@
package net.shapelight.modules.dev.mqtt;
public enum TopicCmdEnum {
remoteOpenDoor("remoteOpenDoor"),
personChange("personChange"),
cleanPerson("cleanPerson"),
faceCount("faceCount"),
alert("alert"),
upRecord("upRecord"),
addPerson("addPerson"),
getParam("getParam");
private String cmd;
TopicCmdEnum(String cmd){
this.cmd = cmd;
}
public String getCmd() {
return cmd;
}
}
//package net.shapelight.modules.dev.mqtt;
//
//public enum TopicCmdEnum {
// remoteOpenDoor("remoteOpenDoor"),
// personChange("personChange"),
// cleanPerson("cleanPerson"),
// faceCount("faceCount"),
// alert("alert"),
// upRecord("upRecord"),
// addPerson("addPerson"),
// getParam("getParam");
//
//
// private String cmd;
//
// TopicCmdEnum(String cmd){
// this.cmd = cmd;
// }
//
// public String getCmd() {
// return cmd;
// }
//}

View File

@ -3,6 +3,7 @@ package net.shapelight.modules.excel.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONObject;
import io.minio.PutObjectOptions;
import lombok.Getter;
import net.shapelight.common.utils.UUIDUtil;
import net.shapelight.commons.engine.sdk.PicSDK;
@ -16,7 +17,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;
@ -155,6 +158,9 @@ public class PersonExcelListener extends AnalysisEventListener<PersonModel> {
}else{
personModel.setOrgImage(image);
}
//检测图片人脸
//---------------------------------------------------------------------
String tempPath = "";
@ -165,14 +171,37 @@ public class PersonExcelListener extends AnalysisEventListener<PersonModel> {
}
String tempFaceFileName = UUIDUtil.uuid() + ".jpg";
String tempFaceFilePath = tempPath + tempFaceFileName;
int res = PicSDK.getFace(personModel.getOrgImage(), tempFaceFilePath);
if (res != 0) {
personModel.setMessage("图片不合格,未检测到人脸");
personModel.setStatus(0);
list.add(personModel);
return;
String osName = System.getProperty("os.name");//获取指定键即os.name的系统属性,Windows 7
if (!Pattern.matches("Windows.*", osName)) {
int res = PicSDK.getFace(personModel.getOrgImage(), tempFaceFilePath);
if (res != 0) {
personModel.setMessage("图片不合格,未检测到人脸");
personModel.setStatus(0);
list.add(personModel);
return;
}
}
// int res = PicSDK.getFace(personModel.getOrgImage(), tempFaceFilePath);
// if (res != 0) {
// personModel.setMessage("图片不合格,未检测到人脸");
// personModel.setStatus(0);
// list.add(personModel);
// return;
// }
//---------------------------------------------------------------------
//门禁卡号
String doorCard = personModel.getDoorCard();
if(doorCard!=null&&doorCard.length()>0){
personModel.setDoorCard(doorCard);
}
personModel.setStatus(1);
list.add(personModel);

View File

@ -35,6 +35,9 @@ public class PersonModel extends BaseRowModel implements Serializable {
@ExcelProperty(value = "房间名称", index = 7)
private String roomName;
@ExcelProperty(value = "门禁卡号", index = 8)
private String doorCard;
/**
* 原始头像
*/

View File

@ -0,0 +1,60 @@
package net.shapelight.modules.job.task;
import lombok.Data;
import net.shapelight.common.utils.Constant;
import net.shapelight.common.utils.DateUtils;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.sys.entity.SysDbBakEntity;
import net.shapelight.modules.sys.service.SysDbBakService;
import net.shapelight.modules.ten.entity.TenPersonEntity;
import net.shapelight.modules.ten.entity.TenPersonSyncEntity;
import net.shapelight.modules.ten.service.TenPersonService;
import net.shapelight.modules.ten.service.TenPersonSyncService;
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.Component;
import java.io.*;
import java.util.Date;
import java.util.List;
/**
*
*/
@Component("personProcessTask")
@Data
public class PersonProcessTask implements ITask {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private TenPersonService tenPersonService;
@Autowired
private TenPersonSyncService tenPersonSyncService;
@Autowired
private ServerApiService serverApiService;
@Override
public void run(String params) {
logger.debug("personProcessTask定时任务正在执行参数为{}", params);
//1. 遍历人员表找出所有过期的访客并设置为过期不可用
List<TenPersonEntity> guestList = tenPersonService.getAllExpireGuest();
for (TenPersonEntity guest : guestList) {
guest.setStatus(Constant.PESON_SUATUS_GUEST_DATE_OUT);
//修改人员表
tenPersonService.updateStatusById(guest);
//修改同步表
List<TenPersonSyncEntity> syncEntityList = tenPersonSyncService.findByPersonId(guest.getPersonId(),guest.getTenantId());
for(TenPersonSyncEntity syncEntity: syncEntityList){
syncEntity.setState(Constant.PERSON_SYNC_DELETE);
tenPersonSyncService.updateById(syncEntity);
}
}
//断开说有设备
serverApiService.closeAll();
logger.debug("personProcessTask定时任务执行完毕");
}
}

View File

@ -38,7 +38,7 @@ public class MyMessageDecoder extends ByteToMessageDecoder {
if((c0&0xFF) != 0x58){
in.resetReaderIndex();
in.skipBytes(1);
// log.debug(String.format("c0:is 0x%x",c0));
log.debug(String.format("c0:is 0x%x",c0));
return;
}
@ -46,7 +46,7 @@ public class MyMessageDecoder extends ByteToMessageDecoder {
if((c1&0xFF) != 0x49){
in.resetReaderIndex();
in.skipBytes(1);
// log.debug(String.format("c1:is 0x%x",c1));
log.debug(String.format("c1:is 0x%x",c1));
return;
}
@ -54,7 +54,7 @@ public class MyMessageDecoder extends ByteToMessageDecoder {
if((c2&0xFF) != 0x54){
in.resetReaderIndex();
in.skipBytes(1);
// log.debug(String.format("c2:is 0x%x",c2));
log.debug(String.format("c2:is 0x%x",c2));
return;
}
@ -62,7 +62,7 @@ public class MyMessageDecoder extends ByteToMessageDecoder {
if((c3&0xFF) != 0x55){
in.resetReaderIndex();
in.skipBytes(1);
// log.debug(String.format("c3:is 0x%x",c3));
log.debug(String.format("c3:is 0x%x",c3));
return;
}
@ -71,6 +71,9 @@ public class MyMessageDecoder extends ByteToMessageDecoder {
final byte cmd = in.readByte();
final int dataLength = in.readInt();
log.debug(String.format("verson:is 0x%x,datatype:0x%x,cmd:0x%x,lenth:%d",version,dataType,cmd,dataLength));
if(in.readableBytes()<dataLength){
in.resetReaderIndex();
return;//数据不够继续读
@ -88,6 +91,7 @@ public class MyMessageDecoder extends ByteToMessageDecoder {
// String content = new String(contentBytes);
// log.debug("收到数据:"+content);
// log.debug("");
final MyMessage o = new MyMessage(cmd,dataLength,contentBytes);// convertToObject(body);
out.add(o);

View File

@ -40,7 +40,7 @@ public class MyServer {
// Encoder
pipeline.addLast("encoder", new MyMessageEncoder());
//pipeline.addLast("idleStateHandler", new IdleStateHandler(6, 3, 0));//心跳机制
pipeline.addLast("idleStateHandler", new IdleStateHandler(600, 600, 600));//心跳机制
pipeline.addLast("idleStateHandler", new IdleStateHandler(40, 40, 40));//心跳机制
pipeline.addLast(new MyServerHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128) // (5)//BACKLOG用于构造服务端套接字ServerSocket对象标识当服务器请求处理线程全满时用于临时存放已完成三次握手的请求的队列的最大长度如果未设置或所设置的值小于1Java将使用默认值50

View File

@ -14,4 +14,7 @@ public interface DeviceApiService {
boolean isOnline(String sn);
}

View File

@ -1,8 +1,12 @@
package net.shapelight.modules.nettyapi.service;
import io.netty.channel.Channel;
import net.shapelight.modules.vo.TenAppVerison;
import net.shapelight.modules.vo.TenDeviceConfig;
import net.shapelight.modules.vo.TenPersonOperationVo;
import java.util.List;
public interface ServerApiService {
@ -14,9 +18,17 @@ public interface ServerApiService {
int openDoor(String sn, Long personId);
int enableDevice(String sn);
int stopDevice(String sn);
int appUpdate(String sn,TenAppVerison appVerison);
int personOperation(String sn,List<TenPersonOperationVo> operationVoList);
void cleanDataRes(Channel channel, String content);
int close(String sn);
void closeAll();
}

View File

@ -8,16 +8,16 @@ import io.netty.channel.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.shapelight.common.config.GlobalValue;
import net.shapelight.common.utils.DateUtils;
import net.shapelight.common.utils.ImageUtils;
import net.shapelight.common.utils.TreeUtils;
import net.shapelight.common.utils.UUIDUtil;
import net.shapelight.common.utils.*;
import net.shapelight.modules.nettyapi.config.ClientMap;
import net.shapelight.modules.nettyapi.config.CmdConstant;
import net.shapelight.modules.nettyapi.config.MyMessage;
import net.shapelight.modules.nettyapi.service.DeviceApiService;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.nettyapi.utils.Result;
import net.shapelight.modules.sys.entity.SysDeviceEntity;
import net.shapelight.modules.sys.service.SysDeviceAppService;
import net.shapelight.modules.sys.service.SysDeviceService;
import net.shapelight.modules.ten.entity.*;
import net.shapelight.modules.ten.service.*;
import net.shapelight.modules.vo.TenPersonIdUpdateAllVo;
@ -53,6 +53,12 @@ public class DeviceApiServiceImpl implements DeviceApiService {
private TenDeviceAlertService tenDeviceAlertService;
@Autowired
private TenPersonExtractService tenPersonExtractService;
@Autowired
private TenPersonSyncService tenPersonSyncService;
@Autowired
private SysDeviceService sysDeviceService;
@Autowired
private TenDoorCardService tenDoorCardService;
/*
@ -99,6 +105,7 @@ public class DeviceApiServiceImpl implements DeviceApiService {
String appKey = loginJson.getString("app_key");
String appSecret = loginJson.getString("app_secret");
String devId = loginJson.getString("dev_id");
String version = loginJson.getString("version_name");
if(appKey==null || appKey.length()==0 || appSecret == null || appSecret.length()==0
|| !gAppKey.equals(appKey) || !gAppSecret.equals(appSecret)){
@ -121,8 +128,26 @@ public class DeviceApiServiceImpl implements DeviceApiService {
}
//1.判断sn是否存在 设备不存在1002
SysDeviceEntity sysDeviceEntity = sysDeviceService.getOne(new QueryWrapper<SysDeviceEntity>()
.eq("sn",devId));
if(sysDeviceEntity == null){
Result res = Result.error(201, "Device Is Not Bind");
String resContent = JSONObject.toJSONString(res);
MyMessage message = new MyMessage(CmdConstant.CMD_LOGIN,resContent.length(),resContent.getBytes());
channel.writeAndFlush(message);
return;
}
if(sysDeviceEntity.getState() == 0){
Result res = Result.error(202, "Device Is Stop");
String resContent = JSONObject.toJSONString(res);
MyMessage message = new MyMessage(CmdConstant.CMD_LOGIN,resContent.length(),resContent.getBytes());
channel.writeAndFlush(message);
return;
}
//1.判断sn是否存在 设备不存在1002
TenDeviceEntity deviceEntity = tenDeviceService.findBySn(devId);
if(deviceEntity == null){
Result res = Result.error(201, "Device Is Not Bind");
@ -142,19 +167,26 @@ public class DeviceApiServiceImpl implements DeviceApiService {
dataMap.put("building_name",cellEntity.getName());
Map<String,Object> configMap = new HashMap<>();
configMap.put("work_mode",0);
configMap.put("recognize_interval",3);
configMap.put("work_mode",deviceEntity.getHealthCodeFlag());
configMap.put("recognize_interval",deviceEntity.getRecSpace());
configMap.put("relay_suck_time",5);
configMap.put("support_liveness",true);
configMap.put("liveness_score",60);
configMap.put("recognize_score",65);
configMap.put("recognize_distance",2);
configMap.put("alert_temp_threshold",37.3);
if(deviceEntity.getLivenessFlag().intValue() == 1){
configMap.put("support_liveness",true);
}else{
configMap.put("support_liveness",false);
}
configMap.put("liveness_score",deviceEntity.getRgbLiveThd().intValue());
configMap.put("recognize_score",deviceEntity.getRecThd().intValue());
configMap.put("recognize_distance",1);
configMap.put("alert_temp_threshold",deviceEntity.getTemperatureAlert());
configMap.put("upload_face_pic",true);
configMap.put("upload_pic_mode",0);
configMap.put("upload_http_url","http://upload.face.com/face/pic/upload");
configMap.put("support_stranger",false);
configMap.put("upload_pic_mode",deviceEntity.getUploadImageFlag());
configMap.put("upload_http_url","");
if(deviceEntity.getStrangerFlag().intValue() == 1){
configMap.put("support_stranger",true);
}else{
configMap.put("support_stranger",false);
}
dataMap.put("config",configMap);
res.put("data",dataMap);
@ -164,7 +196,9 @@ public class DeviceApiServiceImpl implements DeviceApiService {
clientMap.online(channel, devId);
tenDeviceService.updateById(deviceEntity);
deviceEntity.setApkVersion(version);
tenDeviceService.evictupdateById(deviceEntity);
log.debug("设备:" + devId + " 登录");
return;
@ -187,9 +221,24 @@ public class DeviceApiServiceImpl implements DeviceApiService {
return;
}
TenCellEntity cellEntity = tenCellService.getById(deviceEntity.getCellId());
SysDeviceEntity sysDeviceEntity = sysDeviceService.getOne(new QueryWrapper<SysDeviceEntity>()
.eq("sn",devId));
if(sysDeviceEntity.getState() == 0){
Result res = Result.error(202, "Device Is Stop");
String resContent = JSONObject.toJSONString(res);
MyMessage message = new MyMessage(CmdConstant.CMD_GETALL,resContent.length(),resContent.getBytes());
channel.writeAndFlush(message);
return;
}
List<TenPersonIdUpdateAllVo> all = tenPersonService.findAllPersonIdUpdateAll(cellEntity.getCellId(),null,null);
// TenCellEntity cellEntity = tenCellService.getById(deviceEntity.getCellId());
// List<TenPersonIdUpdateAllVo> all = tenPersonService.findAllPersonIdUpdateAll(cellEntity.getCellId(),null,null);
List<TenPersonIdUpdateAllVo> all = tenPersonSyncService.getDeviceAllPersonIdUpdateTime(deviceEntity.getDeviceId(),deviceEntity.getTenantId());
//删除状态为删除的人员
tenPersonSyncService.removeAllDeletePersons(deviceEntity.getDeviceId(),deviceEntity.getTenantId());
Result res = new Result();
res.put("data",all);
@ -217,24 +266,71 @@ public class DeviceApiServiceImpl implements DeviceApiService {
log.error("设备已删除");
return;
}
SysDeviceEntity sysDeviceEntity = sysDeviceService.getOne(new QueryWrapper<SysDeviceEntity>()
.eq("sn",devId));
if(sysDeviceEntity.getState() == 0){
Result res = Result.error(202, "Device Is Stop");
String resContent = JSONObject.toJSONString(res);
MyMessage message = new MyMessage(CmdConstant.CMD_GETONE,resContent.length(),resContent.getBytes());
channel.writeAndFlush(message);
return;
}
TenCellEntity cellEntity = tenCellService.getById(deviceEntity.getCellId());
TenPersonEntity p = tenPersonService.getById(uid,cellEntity.getCellId());
TenUserVo puser = new TenUserVo();
if (p==null) {
return;
}else{
TenDoorCardEntity doorCardEntity = tenDoorCardService.getOne(
new QueryWrapper<TenDoorCardEntity>()
.eq("person_id",p.getPersonId())
);
if(doorCardEntity!=null){
puser.setCard_id(doorCardEntity.getDoorCard());
}else{
TenDoorCardEntity doorCardRoom = tenDoorCardService.getOne(
new QueryWrapper<TenDoorCardEntity>()
.eq("room_id",p.getRoomId())
);
if(doorCardEntity!=null){
puser.setCard_id(doorCardRoom.getDoorCard());
}
}
}
puser.setUid(p.getPersonId());
puser.setUser_name(p.getName());
puser.setUser_type(0);
puser.setActive_start_time(0);
puser.setActive_end_time(0);
if(p.getLiveStart()!=null){
puser.setActive_start_time((int)(p.getLiveStart().getTime()/1000));
}
if(p.getLiveEnd()!=null){
puser.setActive_end_time((int)(p.getLiveEnd().getTime()/1000));
}
// puser.setActive_start_time(0);
// puser.setActive_end_time(0);
puser.setLast_update_stamp(p.getLastUpdateTime().getTime());
puser.setCard_id("");
puser.setFace_pic_download_url(globalValue.getMinioEndpoint()+"/"
+ globalValue.getMinioBucketName()+"/"
+ p.getOrgImage());
puser.setFace_pic_base64("");
// TenPersonSyncEntity syncEntity = tenPersonSyncService.getOne(new QueryWrapper<TenPersonSyncEntity>()
// .eq("device_id",deviceEntity.getDeviceId())
// .eq("person_id",p.getPersonId()));
TenPersonSyncEntity syncEntity = tenPersonSyncService.findByDeviceIdAndPersonId(deviceEntity.getDeviceId(),
p.getPersonId(),deviceEntity.getTenantId());
syncEntity.setState(Constant.PERSON_SYNC_OK);
tenPersonSyncService.updateById(syncEntity);
Result res = new Result();
res.put("data",puser);
@ -272,9 +368,19 @@ public class DeviceApiServiceImpl implements DeviceApiService {
return;
}
SysDeviceEntity sysDeviceEntity = sysDeviceService.getOne(new QueryWrapper<SysDeviceEntity>()
.eq("sn",sn));
if(sysDeviceEntity.getState() == 0){
Result res = Result.error(202, "Device Is Stop");
String resContent = JSONObject.toJSONString(res);
MyMessage message = new MyMessage(CmdConstant.CMD_HART,resContent.length(),resContent.getBytes());
channel.writeAndFlush(message);
return;
}
//保存人脸个数
deviceEntity.setFaceCount(faceCount);
tenDeviceService.updateById(deviceEntity);
tenDeviceService.evictupdateById(deviceEntity);
TenCellEntity cellEntity = tenCellService.getById(deviceEntity.getCellId());
@ -349,6 +455,18 @@ public class DeviceApiServiceImpl implements DeviceApiService {
log.error("设备已删除");
return;
}
SysDeviceEntity sysDeviceEntity = sysDeviceService.getOne(new QueryWrapper<SysDeviceEntity>()
.eq("sn",sn));
if(sysDeviceEntity.getState() == 0){
Result res = Result.error(202, "Device Is Stop");
String resContent = JSONObject.toJSONString(res);
MyMessage message = new MyMessage(CmdConstant.CMD_UPRECORD,resContent.length(),resContent.getBytes());
channel.writeAndFlush(message);
return;
}
TenCellEntity cellEntity = tenCellService.getById(deviceEntity.getCellId());
TenRecordEntity record = new TenRecordEntity();
record.setDeviceSn(sn);
@ -394,6 +512,17 @@ public class DeviceApiServiceImpl implements DeviceApiService {
log.error("设备已删除");
return;
}
SysDeviceEntity sysDeviceEntity = sysDeviceService.getOne(new QueryWrapper<SysDeviceEntity>()
.eq("sn",sn));
if(sysDeviceEntity.getState() == 0){
Result res = Result.error(202, "Device Is Stop");
String resContent = JSONObject.toJSONString(res);
MyMessage message = new MyMessage(CmdConstant.CMD_EXTRACT,resContent.length(),resContent.getBytes());
channel.writeAndFlush(message);
return;
}
TenCellEntity cellEntity = tenCellService.getById(deviceEntity.getCellId());

View File

@ -9,6 +9,7 @@ import net.shapelight.modules.nettyapi.config.CmdConstant;
import net.shapelight.modules.nettyapi.config.MyMessage;
import net.shapelight.modules.nettyapi.service.DeviceApiService;
import net.shapelight.modules.nettyapi.service.MessageService;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.nettyapi.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
@ -26,6 +27,8 @@ public class MessageServiceImpl implements MessageService {
private ClientMap clientMap;
@Autowired
private CacheManager cacheManager;
@Autowired
private ServerApiService serverApiService;
@Override
public void receive(ChannelHandlerContext ctx, MyMessage msg) {
@ -133,6 +136,7 @@ public class MessageServiceImpl implements MessageService {
case CmdConstant.CMD_CLEANDATA: {
log.debug("清除数据:" + msg.cmd);
serverApiService.cleanDataRes(channel,content);
break;
}
@ -142,7 +146,7 @@ public class MessageServiceImpl implements MessageService {
}
default:
log.debug("unknown cmd type:" + msg.cmd);
log.debug("未知类型:" + msg.cmd);
break;
}
}

View File

@ -1,23 +1,35 @@
package net.shapelight.modules.nettyapi.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import net.shapelight.modules.nettyapi.config.ClientMap;
import net.shapelight.modules.nettyapi.config.CmdConstant;
import net.shapelight.modules.nettyapi.config.MyMessage;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.nettyapi.utils.Result;
import net.shapelight.modules.sys.entity.SysDeviceEntity;
import net.shapelight.modules.sys.service.SysDeviceService;
import net.shapelight.modules.ten.entity.TenDeviceEntity;
import net.shapelight.modules.ten.entity.TenPersonSyncEntity;
import net.shapelight.modules.ten.service.TenDeviceService;
import net.shapelight.modules.ten.service.TenPersonService;
import net.shapelight.modules.ten.service.TenPersonSyncService;
import net.shapelight.modules.vo.TenAppVerison;
import net.shapelight.modules.vo.TenDeviceConfig;
import net.shapelight.modules.vo.TenPersonIdUpdateAllVo;
import net.shapelight.modules.vo.TenPersonOperationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@ -27,6 +39,12 @@ public class ServerApiServiceImpl implements ServerApiService {
ClientMap clientMap;
@Autowired
private TenDeviceService tenDeviceService;
@Autowired
private TenPersonService tenPersonService;
@Autowired
private TenPersonSyncService tenPersonSyncService;
@Autowired
private SysDeviceService sysDeviceService;
@Override
@ -38,11 +56,36 @@ public class ServerApiServiceImpl implements ServerApiService {
// Map<String,Object> data = new HashMap<>();
// data.put("data",data);
String content = JSONObject.toJSONString(dc);
MyMessage message = new MyMessage(CmdConstant.CMD_CONFIG,content.length(),content.getBytes());
MyMessage message = new MyMessage(CmdConstant.CMD_CONFIG,content.getBytes().length,content.getBytes());
channel.writeAndFlush(message);
return 0;
}
@Override
public int personOperation(String sn,List<TenPersonOperationVo> operationVoList) {
Channel channel = clientMap.getChannelByUserId(sn);
if(channel == null){
return -1;
}
String content = JSONObject.toJSONString(operationVoList);
MyMessage message = new MyMessage(CmdConstant.CMD_CHANGE,content.getBytes().length,content.getBytes());
channel.writeAndFlush(message);
return 0;
}
// @Override
// public int personOperation(String sn) {
// Channel channel = clientMap.getChannelByUserId(sn);
// if(channel == null){
// return -1;
// }
// String content = JSONObject.toJSONString(operationVoList);
// MyMessage message = new MyMessage(CmdConstant.CMD_CHANGE,content.length(),content.getBytes());
// channel.writeAndFlush(message);
// return 0;
// }
@Override
public int openDoor(String sn,Long personId) {
Channel channel = clientMap.getChannelByUserId(sn);
@ -53,7 +96,7 @@ public class ServerApiServiceImpl implements ServerApiService {
data.put("dev_id",sn);
data.put("uid",personId);
String content = JSONObject.toJSONString(data);
MyMessage message = new MyMessage(CmdConstant.CMD_OPENDOOR,content.length(),content.getBytes());
MyMessage message = new MyMessage(CmdConstant.CMD_OPENDOOR,content.getBytes().length,content.getBytes());
channel.writeAndFlush(message);
return 0;
}
@ -68,7 +111,7 @@ public class ServerApiServiceImpl implements ServerApiService {
Map<String,Object> data = new HashMap<>();
data.put("dev_id",sn);
String content = JSONObject.toJSONString(data);
MyMessage message = new MyMessage(CmdConstant.CMD_RESTART,content.length(),content.getBytes());
MyMessage message = new MyMessage(CmdConstant.CMD_RESTART,content.getBytes().length,content.getBytes());
channel.writeAndFlush(message);
return 0;
}
@ -82,13 +125,13 @@ public class ServerApiServiceImpl implements ServerApiService {
Map<String,Object> data = new HashMap<>();
data.put("dev_id",sn);
String content = JSONObject.toJSONString(data);
MyMessage message = new MyMessage(CmdConstant.CMD_CLEANDATA,content.length(),content.getBytes());
MyMessage message = new MyMessage(CmdConstant.CMD_CLEANDATA,content.getBytes().length,content.getBytes());
channel.writeAndFlush(message);
return 0;
}
@Override
public int enableDevice(String sn) {
public int stopDevice(String sn) {
Channel channel = clientMap.getChannelByUserId(sn);
if(channel == null){
return -1;
@ -96,7 +139,7 @@ public class ServerApiServiceImpl implements ServerApiService {
Map<String,Object> data = new HashMap<>();
data.put("dev_id",sn);
String content = JSONObject.toJSONString(data);
MyMessage message = new MyMessage(CmdConstant.CMD_ENABLE,content.length(),content.getBytes());
MyMessage message = new MyMessage(CmdConstant.CMD_ENABLE,content.getBytes().length,content.getBytes());
channel.writeAndFlush(message);
return 0;
}
@ -110,11 +153,58 @@ public class ServerApiServiceImpl implements ServerApiService {
// Map<String,Object> data = new HashMap<>();
// data.put("data",data);
String content = JSONObject.toJSONString(appVerison);
MyMessage message = new MyMessage(CmdConstant.CMD_APPUPDATE,content.length(),content.getBytes());
MyMessage message = new MyMessage(CmdConstant.CMD_APPUPDATE,content.getBytes().length,content.getBytes());
channel.writeAndFlush(message);
return 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void cleanDataRes(Channel channel, String content) {
String sn = clientMap.getUserIdByChannel(channel);
TenDeviceEntity deviceEntity = tenDeviceService.findBySn(sn);
//1.删除同步表中数据
// tenPersonSyncService.remove(new QueryWrapper<TenPersonSyncEntity>()
// .eq("device_id",deviceEntity.getDeviceId()));
tenPersonSyncService.removeByDeviceId(deviceEntity.getDeviceId(),deviceEntity.getTenantId());
//2.在同步表中插入所有信息
List<TenPersonIdUpdateAllVo> list = tenPersonService.findAllPersonIdUpdateAll(deviceEntity.getCellId(),
deviceEntity.getBuildId(),
deviceEntity.getRoomId());
// List<TenPersonSyncEntity> sList = new ArrayList<>();
for(TenPersonIdUpdateAllVo vo:list){
TenPersonSyncEntity entity = new TenPersonSyncEntity();
entity.setDeviceId(deviceEntity.getDeviceId());
entity.setDeviceSn(deviceEntity.getSn());
entity.setLastUpdateTime(vo.getLast_update_stamp());
entity.setPersonId(vo.getUid());
entity.setState(0);
entity.setTenantId(deviceEntity.getTenantId());
tenPersonSyncService.insert(entity);
}
// tenPersonSyncService.saveBatch(sList);
}
@Override
public int close(String sn) {
Channel channel = clientMap.getChannelByUserId(sn);
if(channel == null){
return -1;
}
channel.close();
return 0;
}
@Override
public void closeAll() {
ConcurrentHashMap<String, Channel> list = clientMap.getChannelMap();
for(Map.Entry<String, Channel> entry:list.entrySet()){
Channel channel = entry.getValue();
channel.close();
log.debug("断开设备:"+entry.getKey());
}
}
}

View File

@ -121,8 +121,9 @@ public class SysDeviceAppController {
InputStream inputStream = null;
try {
String userFileUrl = globalValue.getApkDir() + "/";
String extension = FilenameUtils.getExtension(file.getOriginalFilename()); //后缀名
String fileName = userFileUrl + UUIDUtil.uuid() + "." + extension;
// String extension = FilenameUtils.getExtension(file.getOriginalFilename()); //后缀名
// String fileName = userFileUrl + UUIDUtil.uuid() + "." + extension;
String fileName = userFileUrl + file.getOriginalFilename();
inputStream = file.getInputStream();
PutObjectOptions putObjectOptions = new PutObjectOptions(inputStream.available(), -1);
putObjectOptions.setContentType(file.getContentType());

View File

@ -8,6 +8,7 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.sys.entity.SysDeviceEntity;
import net.shapelight.modules.sys.service.SysDeviceService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
@ -30,6 +31,9 @@ public class SysDeviceController {
@Autowired
private SysDeviceService sysDeviceService;
@Autowired
private ServerApiService serverApiService;
/**
* 列表
*/
@ -85,6 +89,29 @@ public class SysDeviceController {
return R.ok();
}
/**
* 停用
*/
@PostMapping("/stop")
@RequiresPermissions("sys:device")
@ApiOperation(value = "修改")
public R stop(@RequestBody SysDeviceEntity sysDevice){
if(sysDevice.getState().intValue() == 0){
int flag = serverApiService.stopDevice(sysDevice.getSn());
if(flag == -1){
return R.error("设备不在线");
}else {
sysDeviceService.updateById(sysDevice);
}
}else{
sysDeviceService.updateById(sysDevice);
}
return R.ok();
}
/**
* 删除
*/
@ -92,7 +119,7 @@ public class SysDeviceController {
@RequiresPermissions("sys:device")
@ApiOperation(value = "删除")
public R delete(@RequestBody Long[] deviceIds){
sysDeviceService.removeByIds(Arrays.asList(deviceIds));
return R.ok();

View File

@ -61,4 +61,9 @@ public class SysDeviceAppEntity implements Serializable {
@ApiModelProperty("0未删除1删除")
private Integer deleteFlag;
@TableField(exist=false)
private String deviceSn;
}

View File

@ -48,6 +48,9 @@ public class SysDeviceEntity implements Serializable {
@ApiModelProperty("0未删除1删除")
private Integer deleteFlag;
@ApiModelProperty("1正常0停用")
private Integer state;
/**

View File

@ -2,7 +2,8 @@ package net.shapelight.modules.sys.service.impl;
import net.shapelight.common.utils.RedisUtils;
import net.shapelight.common.utils.StringUtils;
import net.shapelight.modules.dev.mqtt.EmqHttpApi;
//import net.shapelight.modules.dev.mqtt.EmqHttpApi;
import net.shapelight.modules.nettyapi.service.DeviceApiService;
import net.shapelight.modules.sys.dao.SysDeviceDao;
import net.shapelight.modules.sys.entity.SysDeviceEntity;
import net.shapelight.modules.sys.entity.SysDeviceTypeEntity;
@ -32,10 +33,12 @@ public class SysDeviceServiceImpl extends ServiceImpl<SysDeviceDao, SysDeviceEnt
private TenDeviceService tenDeviceService;
@Autowired
private TenCellService tenCellService;
@Autowired
private EmqHttpApi emqHttpApi;
// @Autowired
// private EmqHttpApi emqHttpApi;
@Autowired
private SysUserService sysUserService;
@Autowired
private DeviceApiService deviceApiService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
@ -56,7 +59,8 @@ public class SysDeviceServiceImpl extends ServiceImpl<SysDeviceDao, SysDeviceEnt
String cellName = tenCellService.getCellName(tenDeviceEntity.getCellId().toString());
deviceEntity.setCellName(cellName);
}
boolean onlineFlag = emqHttpApi.getClient(tenDeviceEntity.getSn());
// boolean onlineFlag = emqHttpApi.getClient(tenDeviceEntity.getSn());
boolean onlineFlag = deviceApiService.isOnline(deviceEntity.getSn());
if(onlineFlag){
deviceEntity.setStatus(1);
}else{

View File

@ -234,6 +234,7 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> i
appUser.setCreateTime(new Date());
//app用户保存系统用户id号
appUser.setSysUserId(user.getUserId());
appUser.setTenantId(user.getTenantId());
appUserService.save(appUser);
//保存权限

View File

@ -8,8 +8,8 @@ import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.shapelight.common.utils.Constant;
import net.shapelight.modules.dev.mqtt.CmdProcess;
import net.shapelight.modules.dev.mqtt.EmqHttpApi;
//import net.shapelight.modules.dev.mqtt.CmdProcess;
//import net.shapelight.modules.dev.mqtt.EmqHttpApi;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.sys.controller.AbstractController;
import net.shapelight.modules.sys.entity.SysDeviceAppEntity;
@ -59,8 +59,8 @@ public class TenDeviceController extends AbstractController {
private SysDeviceService sysDeviceService;
@Autowired
private SysDeviceAppService sysDeviceAppService;
@Autowired
private EmqHttpApi emqHttpApi;
// @Autowired
// private EmqHttpApi emqHttpApi;
@Autowired
private ServerApiService serverApiService;
@ -158,19 +158,87 @@ public class TenDeviceController extends AbstractController {
})
public R cleanPerson(@RequestBody Map<String, Object> deviceSn){
String sn = (String)deviceSn.get("deviceSn");
CmdProcess.publishCleanPerson(sn);
// CmdProcess.publishCleanPerson(sn);
//清除数据
int r = serverApiService.cleanData(sn);
//配置参数
TenDeviceConfig dc = new TenDeviceConfig();
int s = serverApiService.devConfig(sn,dc);
for(int i =0;i<1000;i++){
}
// TenDeviceConfig dc = new TenDeviceConfig();
// int s = serverApiService.devConfig(sn,dc);
// for(int i =0;i<1000;i++){
//
// }
//升级app
TenAppVerison v = new TenAppVerison();
int a = serverApiService.appUpdate(sn,v);
// TenAppVerison v = new TenAppVerison();
// int a = serverApiService.appUpdate(sn,v);
if(r == -1){
return R.error("设备离线");
}
//重新配置同步表
return R.ok();
}
/**
* 远程重启
*/
@PostMapping("/restart")
@ApiOperation(value = "远程重启")
@ApiImplicitParams({
@ApiImplicitParam(name="deviceSn",value = "设备Sn",paramType = "query",dataType = "String",required = true),
})
public R restart(@RequestBody Map<String, Object> deviceSn){
String sn = (String)deviceSn.get("deviceSn");
// CmdProcess.publishCleanPerson(sn);
//清除数据
int r = serverApiService.restart(sn);
if(r == -1){
return R.error("设备离线");
}
return R.ok();
}
/**
* 远程开门
*/
@PostMapping("/opendoor")
@ApiOperation(value = "远程开门")
@ApiImplicitParams({
@ApiImplicitParam(name="deviceSn",value = "设备Sn",paramType = "query",dataType = "String",required = true),
@ApiImplicitParam(name="personId",value = "人员id",paramType = "query",dataType = "String",required = true),
})
public R opendoor(@RequestBody Map<String, Object> params){
String sn = (String)params.get("deviceSn");
Long personIdStr = Long.parseLong((String)params.get("personId"));
//远程开门
int r = serverApiService.openDoor(sn,personIdStr);
if(r == -1){
return R.error("设备离线");
}
return R.ok();
}
/**
* 断开
*/
@PostMapping("/close")
@ApiOperation(value = "断开设备")
@ApiImplicitParams({
@ApiImplicitParam(name="deviceSn",value = "设备Sn",paramType = "query",dataType = "String",required = true),
})
public R close(@RequestBody Map<String, Object> params){
String sn = (String)params.get("deviceSn");
//远程开门
int r = serverApiService.close(sn);
if(r == -1){
return R.error("设备离线");
}
@ -179,49 +247,113 @@ public class TenDeviceController extends AbstractController {
/**
* 获取设备参数
*/
@GetMapping("/getParam/{sn}")
@ApiOperation(value = "获取设备参数")
public R getParam(@PathVariable("sn") String sn){
boolean onlineFlag = emqHttpApi.getClient(sn);
if(onlineFlag){
// /**
// * 获取设备参数
// */
// @GetMapping("/getParam/{sn}")
// @ApiOperation(value = "获取设备参数")
// public R getParam(@PathVariable("sn") String sn){
// boolean onlineFlag = emqHttpApi.getClient(sn);
// if(onlineFlag){
//
// }else{
// return R.error("设备离线,无法更新");
// }
// CmdProcess.publishGetParam(sn);
// try {
// Thread.sleep(3000);
// TenDeviceEntity dev = tenDeviceService.findBySn(sn);
// TenDeviceParamVo paramVo = new TenDeviceParamVo();
// BeanUtils.copyProperties(dev,paramVo);
// return R.ok().put("data",paramVo);
// }catch (Exception e){
// return R.error("获取失败,请重试");
// }
// }
}else{
return R.error("设备离线,无法更新");
}
CmdProcess.publishGetParam(sn);
try {
Thread.sleep(3000);
TenDeviceEntity dev = tenDeviceService.findBySn(sn);
TenDeviceParamVo paramVo = new TenDeviceParamVo();
BeanUtils.copyProperties(dev,paramVo);
return R.ok().put("data",paramVo);
}catch (Exception e){
return R.error("获取失败,请重试");
}
}
/**
* 设置设备参数
* 设置设备参数 TCP 设备
private Integer work_mode; //0表示门禁模式,1表示门禁+测温模式默认为0 health_code_flag
private Integer recognize_interval; //连续两次人脸识别时间间隔默认3s rec_space
private Integer relay_suck_time; //继电器吸合开锁持续时间,默认5s
private Boolean support_liveness; //是否支持活体检测,默认true liveness_flag
private Integer liveness_score; //活体检测超过此值则判断为活体,默认60 rgb_live_thd
private Integer recognize_score; //人脸比对分值超过此值则判断为同一个人,默认65 rec_thd
private Integer recognize_distance; //默认1m
private Float alert_temp_threshold; //人脸温度超过此值则报警,默认5s temperature_alert
private Boolean upload_face_pic; //默认true upload_image_flag
private Integer upload_pic_mode; //枚举值0表示人脸图base64编码和人脸识别记录同时上传, 1表示人脸图通过http协议post上传
private String upload_http_url; //人脸图通过http上传的url地址
private Boolean support_stranger; //是否支持陌生人抓拍 默认false stranger_flag
public TenDeviceConfig(){
this.work_mode = 0;
this.recognize_interval = 3;
this.relay_suck_time = 5;
this.support_liveness = true;
this.liveness_score = 60;
this.recognize_score = 65;
this.recognize_distance = 1;
this.alert_temp_threshold = 37.3f;
this.upload_face_pic = true;
this.upload_pic_mode = 0;
this.upload_http_url = "";
this.support_stranger = true;
}
*/
@PostMapping("/setParam")
@PostMapping("/setConfig")
@ApiOperation(value = "设置设备参数")
public R setParam(@RequestBody TenDeviceParamVo paramVo){
String sn = paramVo.getSn();
boolean onlineFlag = emqHttpApi.getClient(sn);
if(onlineFlag){
}else{
return R.error("设备离线,无法更新");
public R setConfig(@RequestBody TenDeviceEntity tenDevice){
TenDeviceConfig config = new TenDeviceConfig();
config.setWork_mode(tenDevice.getHeartbeatCycle());
config.setRecognize_interval(tenDevice.getRecSpace());
config.setRelay_suck_time(5);
if(tenDevice.getLivenessFlag().intValue() == 1){
config.setSupport_liveness(true);
}else{
config.setSupport_liveness(false);
}
config.setLiveness_score(tenDevice.getRgbLiveThd().intValue());
config.setRecognize_score(tenDevice.getRecThd().intValue());
config.setRecognize_distance(1);
config.setAlert_temp_threshold(tenDevice.getTemperatureAlert());
config.setUpload_pic_mode(tenDevice.getUploadImageFlag());
config.setUpload_http_url("");
if(tenDevice.getStrangerFlag().intValue() == 1){
config.setSupport_stranger(true);
}else{
config.setSupport_stranger(false);
}
//配置推送
int r = serverApiService.devConfig(tenDevice.getSn(),config);
if(r == -1){
return R.error("设备离线");
}
CmdProcess.publishSetParam(paramVo.getSn(),paramVo);
return R.ok();
tenDeviceService.evictupdateById(tenDevice);
return R.ok();
}
// /**
// * 设置设备参数
// */
// @PostMapping("/setParam")
// @ApiOperation(value = "设置设备参数")
// public R setParam(@RequestBody TenDeviceParamVo paramVo){
// String sn = paramVo.getSn();
// boolean onlineFlag = emqHttpApi.getClient(sn);
// if(onlineFlag){
//
// }else{
// return R.error("设备离线,无法更新");
// }
// CmdProcess.publishSetParam(paramVo.getSn(),paramVo);
// return R.ok();
// }
/**
* 查询设备版本号
*/
@ -243,22 +375,45 @@ public class TenDeviceController extends AbstractController {
/**
* 下发app版本
*/
// @PostMapping("/updateApp")
// @ApiOperation(value = "升级app版本")
// @ApiImplicitParams({
// @ApiImplicitParam(name="deviceSn",value = "设备Sn",paramType = "query",dataType = "String",required = true),
// @ApiImplicitParam(name="apkUrl",value = "apk下载地址",paramType = "query",dataType = "String",required = true),
// })
// public R updateApp(@RequestBody Map<String, Object> params){
// String sn = (String)params.get("deviceSn");
// String apkUrl = (String)params.get("apkUrl");
// boolean onlineFlag = emqHttpApi.getClient(sn);
// if(onlineFlag){
//
// }else{
// return R.error("设备离线,无法更新");
// }
// CmdProcess.publishUpdateApp(sn,apkUrl);
// return R.ok();
// }
@PostMapping("/updateApp")
@ApiOperation(value = "升级app版本")
@ApiImplicitParams({
@ApiImplicitParam(name="deviceSn",value = "设备Sn",paramType = "query",dataType = "String",required = true),
@ApiImplicitParam(name="apkUrl",value = "apk下载地址",paramType = "query",dataType = "String",required = true),
})
public R updateApp(@RequestBody Map<String, Object> params){
String sn = (String)params.get("deviceSn");
String apkUrl = (String)params.get("apkUrl");
boolean onlineFlag = emqHttpApi.getClient(sn);
if(onlineFlag){
public R updateApp(@RequestBody SysDeviceAppEntity app){
}else{
return R.error("设备离线,无法更新");
TenAppVerison appVerison = new TenAppVerison();
appVerison.setApk_url(app.getUrl());
appVerison.setApp_name(app.getAppName());
appVerison.setDev_id(app.getDeviceSn());
appVerison.setDesc(app.getRemark());
appVerison.setLatest_version(Integer.parseInt(app.getVersion()));
String sn = app.getDeviceSn();
//清除数据
int r = serverApiService.appUpdate(sn,appVerison);
if(r == -1){
return R.error("设备离线");
}
CmdProcess.publishUpdateApp(sn,apkUrl);
return R.ok();
}
}

View File

@ -20,21 +20,21 @@ import net.shapelight.commons.engine.sdk.PicSDK;
import net.shapelight.modules.app.entity.AppUserEntity;
import net.shapelight.modules.app.service.AppUserService;
import net.shapelight.modules.excel.model.PersonModel;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.sys.controller.AbstractController;
import net.shapelight.modules.sys.entity.SysUserEntity;
import net.shapelight.modules.sys.service.SysUserRoleService;
import net.shapelight.modules.sys.service.SysUserService;
import net.shapelight.modules.ten.entity.TenCellEntity;
import net.shapelight.modules.ten.entity.TenDoorCardEntity;
import net.shapelight.modules.ten.entity.TenUserScopeEntity;
import net.shapelight.modules.ten.entity.*;
import net.shapelight.modules.ten.service.*;
import net.shapelight.modules.vo.TenDeviceVo;
import net.shapelight.modules.vo.TenPersonOperationVo;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import net.shapelight.modules.ten.entity.TenPersonEntity;
import org.springframework.web.multipart.MultipartFile;
@ -70,6 +70,12 @@ public class TenPersonController extends AbstractController {
private TenRecordService tenRecordService;
@Autowired
private SysUserService sysUserService;
@Autowired
private TenDeviceService tenDeviceService;
@Autowired
private TenPersonSyncService tenPersonSyncService;
@Autowired
private ServerApiService serverApiService;
/**
@ -261,7 +267,7 @@ public class TenPersonController extends AbstractController {
}
person.setDoorCardEntity(doorCard);
String lastRecordTime = tenRecordService.findLastRecordTime(personId,cellId);
String lastRecordTime = tenRecordService.findLastRecordTime(personId,person.getTenantId());
person.setLastRecordTime(lastRecordTime);
String lastLoginTime = appUserService.findLastLoginTime(personId, cellId);
@ -350,6 +356,7 @@ public class TenPersonController extends AbstractController {
tenPerson.setCreateBy(getUser().getUsername());
tenPerson.setCreateTime(new Date());
tenPerson.setRegisterType(Constant.RESGISTER_TYPE_WEB);
tenPerson.setStatus(Constant.PESON_SUATUS_NOMOR);
int res = tenPersonService.save(tenPerson);
if (res==2) {
return R.error("照片未检测到人脸");
@ -392,7 +399,7 @@ public class TenPersonController extends AbstractController {
/**
* 修改状态,审核人员
* 修改状态,审核人员 停用禁用
*/
@PostMapping("/updateStatus")
@RequiresPermissions("ten:person")
@ -402,6 +409,71 @@ public class TenPersonController extends AbstractController {
tenPerson.setLastUpdateBy(getUser().getUsername());
tenPerson.setLastUpdateTime(new Date());
tenPersonService.updateStatusById(tenPerson);
//一下推送
//状态为正常时添加到同步表并推送
List<TenDeviceVo> devList = tenDeviceService.findByCellId(tenPerson.getCellId());
if(tenPerson.getStatus().intValue() == Constant.PESON_SUATUS_NOMOR){
//状态是0正常发送推送
for (TenDeviceVo dev : devList) {
//添加到同步表下发设备通知
TenPersonSyncEntity syncEntity = tenPersonSyncService.findByDeviceIdAndPersonId(dev.getDeviceId(),tenPerson.getPersonId(),tenPerson.getTenantId());
if(syncEntity==null){
syncEntity = new TenPersonSyncEntity();
syncEntity.setPersonId(tenPerson.getPersonId());
syncEntity.setTenantId(tenPerson.getTenantId());
syncEntity.setDeviceSn(dev.getSn());
syncEntity.setDeviceId(dev.getDeviceId());
syncEntity.setState(Constant.PERSON_SYNC_ADD);
syncEntity.setLastUpdateTime(tenPerson.getLastUpdateTime());
tenPersonSyncService.insert(syncEntity);
//下发通知
List<TenPersonOperationVo> list = new ArrayList<>();
TenPersonOperationVo vo = new TenPersonOperationVo();
vo.setUid(syncEntity.getPersonId());
vo.setOperation(Constant.PERSON_SYNC_ADD);
vo.setLast_update_stamp(syncEntity.getLastUpdateTime());
list.add(vo);
serverApiService.personOperation(dev.getSn(),list);
}else{
syncEntity.setState(Constant.PERSON_SYNC_MODIFY);
syncEntity.setLastUpdateTime(tenPerson.getLastUpdateTime());
tenPersonSyncService.updateById(syncEntity);
//下发通知
List<TenPersonOperationVo> list = new ArrayList<>();
TenPersonOperationVo vo = new TenPersonOperationVo();
vo.setUid(syncEntity.getPersonId());
vo.setOperation(Constant.PERSON_SYNC_MODIFY);
vo.setLast_update_stamp(syncEntity.getLastUpdateTime());
list.add(vo);
serverApiService.personOperation(dev.getSn(),list);
}
}
}
//状态为其他时删除同步表中的数据并推送
else{
for (TenDeviceVo dev : devList) {
//添加到同步表下发设备通知
TenPersonSyncEntity syncEntity = tenPersonSyncService.findByDeviceIdAndPersonId(dev.getDeviceId(),tenPerson.getPersonId(),tenPerson.getTenantId());
if(syncEntity!=null){
syncEntity.setState(Constant.PERSON_SYNC_DELETE);
syncEntity.setLastUpdateTime(tenPerson.getLastUpdateTime());
tenPersonSyncService.updateById(syncEntity);
//下发通知
List<TenPersonOperationVo> list = new ArrayList<>();
TenPersonOperationVo vo = new TenPersonOperationVo();
vo.setUid(syncEntity.getPersonId());
vo.setOperation(Constant.PERSON_SYNC_DELETE);
vo.setLast_update_stamp(syncEntity.getLastUpdateTime());
list.add(vo);
int flag = serverApiService.personOperation(dev.getSn(),list);
if(flag!= -1){
tenPersonSyncService.removeByPersonSyncId(syncEntity.getPersonSyncId(),syncEntity.getTenantId());
}
}
}
}
return R.ok();
}
@ -458,6 +530,7 @@ public class TenPersonController extends AbstractController {
})
public R delete(@RequestBody List<Map<String, String>> params) {
//tenRoomService.removeByIds(Arrays.asList(roomIds));
tenPersonService.removeByIdList(params);
return R.ok();
}

View File

@ -3,6 +3,9 @@ package net.shapelight.modules.ten.controller;
import java.util.Arrays;
import java.util.Map;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import net.shapelight.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@ -20,7 +23,7 @@ import net.shapelight.common.utils.R;
*/
@RestController
@RequestMapping("ten/personextract")
public class TenPersonExtractController {
public class TenPersonExtractController extends AbstractController {
@Autowired
private TenPersonExtractService tenPersonExtractService;
@ -29,7 +32,13 @@ public class TenPersonExtractController {
*/
@GetMapping("/list")
@RequiresPermissions("ten:personextract:list")
@ApiImplicitParams({
@ApiImplicitParam(name = "limit", value = "每页条数", paramType = "query", dataType = "String", required = true),
@ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "String", required = true),
@ApiImplicitParam(name = "name", value = "姓名", paramType = "query", dataType = "String", required = true),
})
public R list(@RequestParam Map<String, Object> params){
params.put("tenantId",getUser().getTenantId());
PageUtils page = tenPersonExtractService.queryPage(params);
return R.ok().put("data", page);

View File

@ -0,0 +1,83 @@
package net.shapelight.modules.ten.controller;
import java.util.Arrays;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import net.shapelight.modules.ten.entity.TenPersonSyncEntity;
import net.shapelight.modules.ten.service.TenPersonSyncService;
import net.shapelight.common.utils.PageUtils;
import net.shapelight.common.utils.R;
/**
*
*
*/
@RestController
@RequestMapping("ten/personsync")
public class TenPersonSyncController {
@Autowired
private TenPersonSyncService tenPersonSyncService;
// /**
// * 列表
// */
// @GetMapping("/list")
// @RequiresPermissions("ten:personsync:list")
// public R list(@RequestParam Map<String, Object> params){
// PageUtils page = tenPersonSyncService.queryPage(params);
//
// return R.ok().put("data", page);
// }
//
//
// /**
// * 信息
// */
// @GetMapping("/info/{personSyncId}")
// @RequiresPermissions("ten:personsync:info")
// public R info(@PathVariable("personSyncId") Long personSyncId){
// TenPersonSyncEntity tenPersonSync = tenPersonSyncService.getById(personSyncId);
//
// return R.ok().put("data", tenPersonSync);
// }
//
// /**
// * 保存
// */
// @PostMapping("/save")
// @RequiresPermissions("ten:personsync:save")
// public R save(@RequestBody TenPersonSyncEntity tenPersonSync){
// tenPersonSyncService.save(tenPersonSync);
//
// return R.ok();
// }
//
// /**
// * 修改
// */
// @PostMapping("/update")
// @RequiresPermissions("ten:personsync:update")
// public R update(@RequestBody TenPersonSyncEntity tenPersonSync){
// tenPersonSyncService.updateById(tenPersonSync);
//
// return R.ok();
// }
//
// /**
// * 删除
// */
// @PostMapping("/delete")
// @RequiresPermissions("ten:personsync:delete")
// public R delete(@RequestBody Long[] personSyncIds){
// tenPersonSyncService.removeByIds(Arrays.asList(personSyncIds));
//
// return R.ok();
// }
}

View File

@ -108,8 +108,10 @@ public class TenRecordController extends AbstractController {
// @RequiresPermissions("ten:tenrecord:info")
public R info(@PathVariable("recordId") Long recordId,@PathVariable("cellId") Long cellId){
TenRecordEntity tenRecord = tenRecordService.getById(recordId,cellId);
return R.ok().put("data", tenRecord);
// String tenantId = getUser().getTenantId()+"";
//// params.put("tenantId",tenantId+"");
// TenRecordEntity tenRecord = tenRecordService.getById(recordId,cellId);
return R.ok().put("data", null);
}
/**

View File

@ -17,12 +17,14 @@ import java.util.Map;
@Mapper
public interface TenCellDao extends BaseMapper<TenCellEntity> {
void createTenBuild(@Param("cellId")String cellId);
void createTenRoom(@Param("cellId")String cellId);
void createTenPerson(@Param("cellId")String cellId);
void createTenRecord(@Param("cellId")String cellId);
void createTenCar(@Param("cellId")String cellId);
void createTenPackRecord(@Param("cellId")String cellId);
void createTenBuild(@Param("tenantId")String tenantId);
void createTenRoom(@Param("tenantId")String tenantId);
void createTenPerson(@Param("tenantId")String tenantId);
void createTenRecord(@Param("tenantId")String tenantId);
void createTenCar(@Param("tenantId")String tenantId);
void createTenPackRecord(@Param("tenantId")String tenantId);
void createTenPersonExtract(@Param("tenantId")String tenantId);
void createTenPersonSync(@Param("tenantId")String tenantId);

View File

@ -77,4 +77,9 @@ public interface TenPersonDao {
@Param("roomId")Long roomId,
@Param("cellId")Long cellId);
List<TenPersonEntity> getAllExpireGuest();
}

View File

@ -0,0 +1,40 @@
package net.shapelight.modules.ten.dao;
import net.shapelight.modules.ten.entity.TenPersonSyncEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import net.shapelight.modules.vo.TenPersonIdUpdateAllVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
*
*
*/
@Mapper
public interface TenPersonSyncDao {
List<TenPersonIdUpdateAllVo> getDeviceAllPersonIdUpdateTime(@Param("deviceId")Long deviceId,@Param("tenantId")Long tenantId);
int insert(TenPersonSyncEntity tenLicenseEntity);
int updateById(TenPersonSyncEntity entity);
void removeByDeviceId(@Param("deviceId")Long deviceId,@Param("tenantId")Long tenantId);
void removeAllDeletePersons(@Param("deviceId")Long deviceId,@Param("tenantId")Long tenantId);
TenPersonSyncEntity findByDeviceIdAndPersonId(@Param("deviceId")Long deviceId, @Param("personId")Long personId, @Param("tenantId")Long tenantId);
List<TenPersonSyncEntity> findByPersonId(@Param("personId")Long personId, @Param("tenantId")Long tenantId);
List<Map<String,String>> findGroupDevicePersons(@Param("personIds")List<Long> personIds, @Param("tenantId")Long tenantId);
List<TenPersonSyncEntity> findDeviceAllDeletePersons(@Param("deviceId")Long deviceId,@Param("tenantId")Long tenantId);
List<TenPersonSyncEntity> findDeviceAllAddPersons(@Param("deviceId")Long deviceId,@Param("tenantId")Long tenantId);
void removePersonSyncId(@Param("personSyncId")Long personSyncId,@Param("tenantId")Long tenantId);
}

View File

@ -17,9 +17,9 @@ import java.util.Map;
@Mapper
public interface TenRecordDao{
int insert(TenRecordEntity tenRecordEntity);
int deleteById(@Param("recordId")Long id, @Param("cellId")Long cellId);
int deleteById(@Param("recordId")Long id, @Param("tenantId")Long tenantId);
boolean updateById(TenRecordEntity entity);
TenRecordEntity selectById(@Param("recordId")Long recordId,@Param("cellId")Long cellId);
TenRecordEntity selectById(@Param("recordId")Long recordId,@Param("tenantId")Long tenantId);
IPage<TenRecordEntity> findPageAll(Page page, @Param("cellIds")List<Long> cellIds, @Param("params") Map params);
List<TenRecordEntity> findAll(@Param("cellIds")List<Long> cellIds, @Param("params") Map params);
@ -30,7 +30,7 @@ public interface TenRecordDao{
IPage<TenRecordEntity> findPageRoomRecord(Page page,@Param("params") Map params);
String findLastRecordTime(@Param("personId")Long personId,@Param("cellId")Long cellId);
String findLastRecordTime(@Param("personId")Long personId,@Param("tenantId")Long tenantId);
}

View File

@ -110,7 +110,7 @@ import lombok.Data;
*
*/
@Data
//@TableName("ten_car")
@TableName("ten_car")
public class TenCarEntity implements Serializable {
private static final long serialVersionUID = 1L;

View File

@ -226,6 +226,8 @@ public class TenDeviceEntity extends BaseEntity implements Serializable {
private String scope;
// @TableField(exist=false)
// @ApiModelProperty("小区名称")
// private String cellName;

View File

@ -115,7 +115,7 @@ import lombok.Data;
*
*/
@Data
//@TableName("ten_pack_record")
@TableName("ten_pack_record")
public class TenPackRecordEntity implements Serializable {
private static final long serialVersionUID = 1L;

View File

@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
@ -20,7 +21,7 @@ import net.shapelight.common.base.BaseEntity;
* 人员表
*/
@Data
//@TableName("ten_person")
@TableName("ten_person")
public class TenPersonEntity extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@ -315,5 +316,14 @@ public class TenPersonEntity extends BaseEntity implements Serializable {
private String doorNumber;
@ApiModelProperty("提取失败log个数")
@TableField(exist = false)
private Integer extractCount;
@ApiModelProperty("提取失败log个数")
@TableField(exist = false)
private List<TenPersonExtractEntity> extractList;
}

View File

@ -7,6 +7,9 @@ import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
@ -51,6 +54,8 @@ public class TenPersonExtractEntity implements Serializable {
/**
* 运营商ID
*/
@ApiModelProperty("运营商ID")
@JsonSerialize(using = ToStringSerializer.class)
private Long tenantId;
}

View File

@ -0,0 +1,58 @@
package net.shapelight.modules.ten.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
*
*
*/
@Data
@TableName("ten_person_sync")
public class TenPersonSyncEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long personSyncId;
/**
* 设备id
*/
private Long deviceId;
/**
* 设备sn
*/
private String deviceSn;
/**
* 人员id
*/
private Long personId;
/**
* 0未同步4已同步1新增2修改3删除
*/
private Integer state;
/**
* 更新时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date lastUpdateTime;
/**
* 运营商ID
*/
@ApiModelProperty("运营商ID")
@JsonSerialize(using = ToStringSerializer.class)
private Long tenantId;
}

View File

@ -19,7 +19,7 @@ import lombok.Data;
*
*/
@Data
//@TableName("ten_record")
@TableName("ten_record")
public class TenRecordEntity implements Serializable {
private static final long serialVersionUID = 1L;

View File

@ -13,10 +13,10 @@ import net.shapelight.common.base.BaseEntity;
/**
* 户室表
*
*
*/
@Data
//@TableName("ten_room")
@TableName("ten_room")
public class TenRoomEntity extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;

View File

@ -25,7 +25,7 @@ public interface TenDeviceService extends IService<TenDeviceEntity> {
PageUtils queryPage(Map<String, Object> params);
List<TenDeviceVo> findByCellId(long cellId);
boolean remoteOpenDoor(String deviceSn,String personId,Integer memberId);
boolean remoteOpenDoor(String deviceSn,Long personId,Integer memberId);
TenDeviceEntity findBySn(String sn);
List<String> findAllSn();
List<TenPersonVo> findUpdatePerson(Long cellId,
@ -68,5 +68,7 @@ public interface TenDeviceService extends IService<TenDeviceEntity> {
void evictupdateById(TenDeviceEntity tenDevice);
}

View File

@ -29,7 +29,7 @@ public interface TenPersonService {
int save(TenPersonEntity entity);
boolean saveOtherRoom(TenPersonEntity entity);
boolean removeById(Long roomId,Long cellId);
// boolean removeById(Long roomId,Long cellId);
boolean removeByIdList(List<Map<String,String>> roomIdList);
@ -107,5 +107,9 @@ public interface TenPersonService {
int getAllCount(Map<String, Object> params);
List<TenPersonEntity> getAllExpireGuest();
}

View File

@ -0,0 +1,42 @@
package net.shapelight.modules.ten.service;
import com.baomidou.mybatisplus.extension.service.IService;
import net.shapelight.common.utils.PageUtils;
import net.shapelight.modules.ten.entity.TenPersonSyncEntity;
import net.shapelight.modules.vo.TenPersonIdUpdateAllVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
*
*
*/
public interface TenPersonSyncService {
List<TenPersonIdUpdateAllVo> getDeviceAllPersonIdUpdateTime(Long deviceId,Long tenantId);
int insert(TenPersonSyncEntity tenLicenseEntity);
int updateById(TenPersonSyncEntity entity);
void removeByDeviceId(Long deviceId, Long tenantId);
void removeByPersonSyncId(Long personSyncId, Long tenantId);
void removeAllDeletePersons(Long deviceId,Long tenantId);
TenPersonSyncEntity findByDeviceIdAndPersonId(Long deviceId, Long personId,Long tenantId);
List<TenPersonSyncEntity> findByPersonId(Long personId,Long tenantId);
List<Map<String,String>> findGroupDevicePersons(List<Long> personIds, Long tenantId);
List<TenPersonSyncEntity> findDeviceAllDeletePersons(Long deviceId, Long tenantId);
List<TenPersonSyncEntity> findDeviceAllAddPersons(Long deviceId, Long tenantId);
}

View File

@ -25,9 +25,9 @@ public interface TenRecordService {
boolean updateById(TenRecordEntity entity);
TenRecordEntity getById(Long id,Long cellId);
TenRecordEntity getById(Long id,Long tenantId);
String findLastRecordTime(Long personId,Long cellId);
String findLastRecordTime(Long personId,Long tenantId);
int getCount(Map<String, Object> params);
int getHourCount(Map<String, Object> params);

View File

@ -77,12 +77,15 @@ public class TenCellServiceImpl extends ServiceImpl<TenCellDao, TenCellEntity> i
@CacheEvict(value = "TenCell", allEntries = true)
public boolean save(TenCellEntity entity) {
String cellId = entity.getCellId().toString();
tenCellDao.createTenBuild(cellId);
tenCellDao.createTenRoom(cellId);
tenCellDao.createTenPerson(cellId);
tenCellDao.createTenRecord(cellId);
tenCellDao.createTenCar(cellId);
tenCellDao.createTenPackRecord(cellId);
String tenantId = entity.getTenantId().toString();
// tenCellDao.createTenBuild(cellId);
// tenCellDao.createTenRoom(cellId);
// tenCellDao.createTenPerson(tenantId);
tenCellDao.createTenRecord(tenantId);
// tenCellDao.createTenCar(cellId);
// tenCellDao.createTenPackRecord(cellId);
// tenCellDao.createTenPersonExtract(tenantId);
tenCellDao.createTenPersonSync(tenantId);
return super.save(entity);
}

View File

@ -1,14 +1,15 @@
package net.shapelight.modules.ten.service.impl;
import lombok.extern.slf4j.Slf4j;
import net.shapelight.common.utils.Constant;
import net.shapelight.common.utils.RedisUtils;
import net.shapelight.modules.dev.mqtt.CmdProcess;
import net.shapelight.modules.dev.mqtt.EmqHttpApi;
import net.shapelight.common.utils.*;
//import net.shapelight.modules.dev.mqtt.CmdProcess;
//import net.shapelight.modules.dev.mqtt.EmqHttpApi;
import net.shapelight.modules.nettyapi.service.DeviceApiService;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.ten.entity.*;
import net.shapelight.modules.ten.service.*;
import net.shapelight.modules.vo.TenDeviceVo;
import net.shapelight.modules.vo.TenPersonIdUpdateAllVo;
import net.shapelight.modules.vo.TenPersonIdUpdateVo;
import net.shapelight.modules.vo.TenPersonVo;
import org.apache.commons.beanutils.BeanUtils;
@ -26,8 +27,6 @@ import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.shapelight.common.utils.PageUtils;
import net.shapelight.common.utils.Query;
import net.shapelight.modules.ten.dao.TenDeviceDao;
import org.springframework.transaction.annotation.Transactional;
@ -51,12 +50,16 @@ public class TenDeviceServiceImpl extends ServiceImpl<TenDeviceDao, TenDeviceEnt
private TenPersonService tenPersonService;
@Autowired
private TenRecordService tenRecordService;
@Autowired
private EmqHttpApi emqHttpApi;
// @Autowired
// private EmqHttpApi emqHttpApi;
@Autowired
private TenDeviceAlertService tenDeviceAlertService;
@Autowired
private DeviceApiService deviceApiService;
@Autowired
private TenPersonSyncService tenPersonSyncService;
@Autowired
private ServerApiService serverApiService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
@ -131,8 +134,15 @@ public class TenDeviceServiceImpl extends ServiceImpl<TenDeviceDao, TenDeviceEnt
if(devList.size()>0){
for(TenDeviceEntity dev: devList){
boolean onlineFlag = emqHttpApi.getClient(dev.getSn());
if(onlineFlag){
// boolean onlineFlag = emqHttpApi.getClient(dev.getSn());
// if(onlineFlag){
// dev.setStatus(1);
// }else{
// dev.setStatus(0);
// }
Boolean flag = deviceApiService.isOnline(dev.getSn());
if (flag) {
dev.setStatus(1);
}else{
dev.setStatus(0);
@ -152,8 +162,16 @@ public class TenDeviceServiceImpl extends ServiceImpl<TenDeviceDao, TenDeviceEnt
}
@Override
public boolean remoteOpenDoor(String deviceSn,String personId,Integer memberId) {
CmdProcess.publishRemoteOpenDoor(deviceSn,memberId);
public boolean remoteOpenDoor(String deviceSn,Long personId,Integer memberId) {
// CmdProcess.publishRemoteOpenDoor(deviceSn,memberId);
//远程开门
int r = serverApiService.openDoor(deviceSn,personId);
// if(r == -1){
// return R.error("设备离线");
// }
// return R.ok();
Object open = null;
for(int i = 0;i<30;i++) {
try {
@ -290,7 +308,8 @@ public class TenDeviceServiceImpl extends ServiceImpl<TenDeviceDao, TenDeviceEnt
.in("cell_id",cellIds));
if (list.size()>=0) {
for(TenDeviceEntity dev: list){
boolean onlineFlag = emqHttpApi.getClient(dev.getSn());
// boolean onlineFlag = emqHttpApi.getClient(dev.getSn());
boolean onlineFlag = deviceApiService.isOnline(dev.getSn());
if(onlineFlag){
onlineCount++;
}
@ -303,8 +322,26 @@ public class TenDeviceServiceImpl extends ServiceImpl<TenDeviceDao, TenDeviceEnt
@Override
@CacheEvict(value="TenDevice",allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void evictSave(TenDeviceEntity deviceEntity) {
this.save(deviceEntity);
//在同步表中插入所有信息
List<TenPersonIdUpdateAllVo> list = tenPersonService.findAllPersonIdUpdateAll(deviceEntity.getCellId(),
deviceEntity.getBuildId(),
deviceEntity.getRoomId());
// List<TenPersonSyncEntity> sList = new ArrayList<>();
for(TenPersonIdUpdateAllVo vo:list){
TenPersonSyncEntity entity = new TenPersonSyncEntity();
entity.setDeviceId(deviceEntity.getDeviceId());
entity.setDeviceSn(deviceEntity.getSn());
entity.setLastUpdateTime(vo.getLast_update_stamp());
entity.setPersonId(vo.getUid());
entity.setState(0);
entity.setTenantId(deviceEntity.getTenantId());
// sList.add(entity);
tenPersonSyncService.insert(entity);
}
// tenPersonSyncService.saveBatch(sList);
}
@Override

View File

@ -26,4 +26,4 @@ public class TenPersonExtractServiceImpl extends ServiceImpl<TenPersonExtractDao
return new PageUtils(page);
}
}
}

View File

@ -15,15 +15,13 @@ import net.shapelight.modules.app.entity.AppUserEntity;
import net.shapelight.modules.app.entity.AppUserScopeEntity;
import net.shapelight.modules.app.service.AppUserScopeService;
import net.shapelight.modules.app.service.AppUserService;
import net.shapelight.modules.dev.mqtt.CmdProcess;
//import net.shapelight.modules.dev.mqtt.CmdProcess;
import net.shapelight.modules.excel.listener.PersonExcelListener;
import net.shapelight.modules.excel.model.PersonModel;
import net.shapelight.modules.nettyapi.service.ServerApiService;
import net.shapelight.modules.ten.entity.*;
import net.shapelight.modules.ten.service.*;
import net.shapelight.modules.vo.TenDeviceVo;
import net.shapelight.modules.vo.TenPersonIdUpdateAllVo;
import net.shapelight.modules.vo.TenPersonIdUpdateVo;
import net.shapelight.modules.vo.TenPersonVo;
import net.shapelight.modules.vo.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
@ -80,6 +78,12 @@ public class TenPersonServiceImpl implements TenPersonService {
private RedisUtils redisUtils;
@Autowired
private TenDoorCardService tenDoorCardService;
@Autowired
private ServerApiService serverApiService;
@Autowired
private TenPersonSyncService tenPersonSyncService;
@Autowired
private TenPersonExtractService tenPersonExtractService;
@Override
@ -117,6 +121,19 @@ public class TenPersonServiceImpl implements TenPersonService {
pageParam.setCurrent(Long.parseLong((String) params.get("page")));
pageParam.setSize(Long.parseLong((String) params.get("limit")));
IPage<TenPersonEntity> page = tenPersonDao.findPageAll(pageParam, cellIds, params);
for(TenPersonEntity personEntity: page.getRecords()){
List<TenPersonExtractEntity> extracts = tenPersonExtractService.list(
new QueryWrapper<TenPersonExtractEntity>()
.eq("person_id",personEntity.getPersonId())
);
if(extracts!=null){
personEntity.setExtractCount(extracts.size());
personEntity.setExtractList(extracts);
}else{
personEntity.setExtractCount(0);
personEntity.setExtractList(new ArrayList<>());
}
}
return new PageUtils(page);
}
@ -315,6 +332,9 @@ public class TenPersonServiceImpl implements TenPersonService {
}
String password = entity.getPassword();
entity.setPassword("");
Date now = new Date();
entity.setCreateTime(now);
entity.setLastUpdateTime(now);
////访客添加状态
// Date now = new Date();
@ -357,7 +377,7 @@ public class TenPersonServiceImpl implements TenPersonService {
card.setValidBegin(entity.getDoorCardEntity().getValidBegin());
card.setValidEnd(entity.getDoorCardEntity().getValidEnd());
Date now = new Date();
// Date now = new Date();
// card.setCreateBy(getUser().getUsername());
card.setCreateTime(now);
card.setLastUpdateTime(now);
@ -375,6 +395,7 @@ public class TenPersonServiceImpl implements TenPersonService {
// appUser.setSalt(salt);
appUser.setPassword(DigestUtils.sha256Hex(password));
appUser.setCreateTime(new Date());
appUser.setTenantId(entity.getTenantId());
appUserService.save(appUser);
@ -392,48 +413,28 @@ public class TenPersonServiceImpl implements TenPersonService {
//发送设备通知
List<TenDeviceVo> devList = tenDeviceService.findByCellId(entity.getCellId());
TenPersonEntity personDo = tenPersonDao.selectById(entity.getPersonId(),entity.getCellId());
for (TenDeviceVo dev : devList) {
TenPersonVo vo = new TenPersonVo();
BeanUtils.copyProperties(personDo,vo);
if (vo.getFaceImage() != null && !vo.getFaceImage().isEmpty()) {
String encode = "";
InputStream inStream = null;
ByteArrayOutputStream outStream = null;
try {
minioClient.statObject(minioConfig.getBucketName(), vo.getFaceImage());
inStream = minioClient.getObject(minioConfig.getBucketName(), vo.getFaceImage());
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, length);
}
encode = Base64.getEncoder().encodeToString(outStream.toByteArray());
vo.setFaceImageStr(encode);
} catch (Exception e) {
log.error("底库不存在:" + vo.getFaceImage());
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
log.debug("inputStream close IOException:" + e.getMessage());
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
log.debug("outStream close IOException:" + e.getMessage());
}
}
}
}
// CmdProcess.publishPersonChange(dev.getSn());
CmdProcess.publishAddPerson(dev.getSn(),vo);
//状态是0正常发送推送
if(entity.getStatus().intValue() == Constant.PESON_SUATUS_NOMOR){
for (TenDeviceVo dev : devList) {
//添加到同步表下发设备通知
TenPersonSyncEntity syncEntity = new TenPersonSyncEntity();
syncEntity.setPersonId(entity.getPersonId());
syncEntity.setTenantId(entity.getTenantId());
syncEntity.setDeviceSn(dev.getSn());
syncEntity.setDeviceId(dev.getDeviceId());
syncEntity.setState(1);
syncEntity.setLastUpdateTime(entity.getLastUpdateTime());
tenPersonSyncService.insert(syncEntity);
//下发通知
List<TenPersonOperationVo> list = new ArrayList<>();
TenPersonOperationVo vo = new TenPersonOperationVo();
vo.setUid(syncEntity.getPersonId());
vo.setOperation(1);
vo.setLast_update_stamp(syncEntity.getLastUpdateTime());
list.add(vo);
serverApiService.personOperation(dev.getSn(),list);
}
}
return 0;
}
@ -441,6 +442,7 @@ public class TenPersonServiceImpl implements TenPersonService {
}
//添加多个房产
@Override
@Transactional(rollbackFor = Exception.class)
public boolean saveOtherRoom(TenPersonEntity entity) {
@ -448,47 +450,6 @@ public class TenPersonServiceImpl implements TenPersonService {
entity.getCellId().toString() + "/" +
entity.getPersonId().toString() + "/";
try {
//保存原始图片
// String tempOrgImageFile = entity.getOrgImageTemp();
// String tempIdFrontImage = entity.getIdFrontImageTemp();
// String tempIdBackImage = entity.getIdBackImageTemp();
// if (tempOrgImageFile != null && !tempOrgImageFile.isEmpty()) {
// String orgImageFileName = userFileUrl + "o_" + UUIDUtil.uuid() + ".jpg";
// String faceImageFileName = userFileUrl + "s_" + UUIDUtil.uuid() + ".jpg";
//// MinioClient minioClient = MinioUtil.getMinioClient();
// try {
// // 调用statObject()来判断对象是否存在
// // 如果不存在, statObject()抛出异常,
// // 否则则代表对象存在
// minioClient.statObject(minioConfig.getBucketName(), tempOrgImageFile);
// minioClient.copyObject(
// minioConfig.getBucketName(),
// orgImageFileName,
// null,
// null,
// minioConfig.getBucketName(),
// tempOrgImageFile,
// null,
// null);
//
// minioClient.copyObject(
// minioConfig.getBucketName(),
// faceImageFileName,
// null,
// null,
// minioConfig.getBucketName(),
// tempOrgImageFile,
// null,
// null);
// entity.setOrgImage(orgImageFileName);
// entity.setFaceImage(faceImageFileName);
// } catch (Exception e) {
// entity.setOrgImage("");
// e.printStackTrace();
// }
// }
//保存原始图片
String tempOrgImageFile = entity.getOrgImageTemp();
String tempIdFrontImage = entity.getIdFrontImage();
@ -622,10 +583,12 @@ public class TenPersonServiceImpl implements TenPersonService {
}
// String password = entity.getPassword();
// entity.setPassword("");
entity.setStatus(Constant.PESON_SUATUS_NOMOR);
int flag = tenPersonDao.insert(entity);
if (flag == 1) {
//保存App用户
if (entity.getAppFlag() == Constant.APP_LOGIN_YES) {
//已经是app用户了不用添加app账户
// AppUserEntity appUser = new AppUserEntity();
// appUser.setUsername(entity.getUsername());
// appUser.setMobile(entity.getMobile());
@ -651,71 +614,47 @@ public class TenPersonServiceImpl implements TenPersonService {
//发送设备通知
List<TenDeviceVo> devList = tenDeviceService.findByCellId(entity.getCellId());
TenPersonEntity personDo = tenPersonDao.selectById(entity.getPersonId(),entity.getCellId());
for (TenDeviceVo dev : devList) {
TenPersonVo vo = new TenPersonVo();
BeanUtils.copyProperties(personDo,vo);
if (vo.getFaceImage() != null && !vo.getFaceImage().isEmpty()) {
String encode = "";
InputStream inStream = null;
ByteArrayOutputStream outStream = null;
try {
minioClient.statObject(minioConfig.getBucketName(), vo.getFaceImage());
inStream = minioClient.getObject(minioConfig.getBucketName(), vo.getFaceImage());
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, length);
}
encode = Base64.getEncoder().encodeToString(outStream.toByteArray());
vo.setFaceImageStr(encode);
} catch (Exception e) {
log.error("底库不存在:" + vo.getFaceImage());
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
log.debug("inputStream close IOException:" + e.getMessage());
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
log.debug("outStream close IOException:" + e.getMessage());
}
}
}
}
// CmdProcess.publishPersonChange(dev.getSn());
CmdProcess.publishAddPerson(dev.getSn(),vo);
}
// List<TenDeviceVo> devList = tenDeviceService.findByCellId(entity.getCellId());
// for (TenDeviceVo dev : devList) {
// CmdProcess.publishPersonChange(dev.getSn());
// }
//发送设备通知
List<TenDeviceVo> devList = tenDeviceService.findByCellId(entity.getCellId());
//状态是0正常发送推送
if(entity.getStatus().intValue() == Constant.PESON_SUATUS_NOMOR){
for (TenDeviceVo dev : devList) {
//添加到同步表下发设备通知
TenPersonSyncEntity syncEntity = new TenPersonSyncEntity();
syncEntity.setPersonId(entity.getPersonId());
syncEntity.setTenantId(entity.getTenantId());
syncEntity.setDeviceSn(dev.getSn());
syncEntity.setDeviceId(dev.getDeviceId());
syncEntity.setState(1);
syncEntity.setLastUpdateTime(entity.getLastUpdateTime());
tenPersonSyncService.insert(syncEntity);
//下发通知
List<TenPersonOperationVo> list = new ArrayList<>();
TenPersonOperationVo vo = new TenPersonOperationVo();
vo.setUid(syncEntity.getPersonId());
vo.setOperation(1);
vo.setLast_update_stamp(syncEntity.getLastUpdateTime());
list.add(vo);
serverApiService.personOperation(dev.getSn(),list);
}
}
return true;
}
return false;
}
@Override
@CacheEvict(value = "TenPerson", key = "#personId+'-'+#cellId")
public boolean removeById(Long personId, Long cellId) {
int flag = tenPersonDao.logicDeleteById(personId, cellId);
if (flag == 1) {
return true;
}
return false;
}
// @Override
// @CacheEvict(value = "TenPerson", key = "#personId+'-'+#cellId")
// public boolean removeById(Long personId, Long cellId) {
// int flag = tenPersonDao.logicDeleteById(personId, cellId);
// if (flag == 1) {
// return true;
// }
// return false;
// }
@Override
@Transactional(rollbackFor = Exception.class)
@ -723,6 +662,8 @@ public class TenPersonServiceImpl implements TenPersonService {
@CacheEvict(value = "TenPerson", allEntries = true)
public boolean removeByIdList(List<Map<String, String>> roomIdList) {
Long cellId = 0L;
List<Long> personIds = new ArrayList<>();
Long tenantId = 0l;
for (Map<String, String> param : roomIdList) {
Long personId = Long.parseLong(param.get("personId"));
cellId = Long.parseLong(param.get("cellId"));
@ -730,6 +671,7 @@ public class TenPersonServiceImpl implements TenPersonService {
entity.setLastUpdateTime(new Date());
entity.setFaceFailure(Constant.FACE_FAILURE_OK);
tenPersonDao.updateById(entity);
tenantId = entity.getTenantId();
//删除app用户
AppUserScopeEntity as = appUserScopeService.getOne(new QueryWrapper<AppUserScopeEntity>()
.eq("person_id", personId)
@ -751,12 +693,45 @@ public class TenPersonServiceImpl implements TenPersonService {
// }
//删除人员
tenPersonDao.logicDeleteById(personId, cellId);
}
List<TenDeviceVo> devList = tenDeviceService.findByCellId(cellId);
for (TenDeviceVo dev : devList) {
CmdProcess.publishPersonChange(dev.getSn());
//记录所有人员id
personIds.add(personId);
}
//配置同步信息并推送
List<Map<String,String>> snPersonsList = tenPersonSyncService.findGroupDevicePersons(personIds,tenantId);
for(Map<String,String> snPersons: snPersonsList){
String sn = snPersons.get("deviceSn");
TenDeviceEntity deviceEntity = tenDeviceService.findBySn(sn);
String[] persons = snPersons.get("plist").split(",");
List<TenPersonOperationVo> list = new ArrayList<>();
for(String personStr: persons){
String[] personInfoStr = personStr.split("_");
Long personId = Long.parseLong(personInfoStr[0]);
Date lastUpdateTime = DateUtils.stringToDate(personInfoStr[1],DateUtils.DATE_TIME_PATTERN);
TenPersonSyncEntity syncEntity = tenPersonSyncService.findByDeviceIdAndPersonId(deviceEntity.getDeviceId(),personId,tenantId);
syncEntity.setLastUpdateTime(lastUpdateTime);
syncEntity.setState(Constant.PERSON_SYNC_DELETE);
tenPersonSyncService.updateById(syncEntity);
}
//下发通知
List<TenPersonSyncEntity> allDelete = tenPersonSyncService.findDeviceAllDeletePersons(deviceEntity.getDeviceId(),deviceEntity.getTenantId());
for(TenPersonSyncEntity syncEntity: allDelete){
TenPersonOperationVo vo = new TenPersonOperationVo();
vo.setUid(syncEntity.getPersonId());
vo.setOperation(Constant.PERSON_SYNC_DELETE);
vo.setLast_update_stamp(syncEntity.getLastUpdateTime());
list.add(vo);
}
int flag = serverApiService.personOperation(sn,list);
if(flag == 0){
//下发成功删除状态为删除的同步人员
tenPersonSyncService.removeAllDeletePersons(deviceEntity.getDeviceId(),tenantId);
}
}
return true;
}
@ -772,12 +747,44 @@ public class TenPersonServiceImpl implements TenPersonService {
entity.setLastUpdateTime(new Date());
entity.setStatus(Constant.PESON_SUATUS_NOMOR);
tenPersonDao.updateById(entity);
//添加到同步表
List<TenDeviceVo> devList = tenDeviceService.findByCellId(cellId);
for (TenDeviceVo dev : devList) {
TenPersonSyncEntity syncEntity = new TenPersonSyncEntity();
syncEntity.setPersonId(entity.getPersonId());
syncEntity.setTenantId(entity.getTenantId());
syncEntity.setDeviceSn(dev.getSn());
syncEntity.setDeviceId(dev.getDeviceId());
syncEntity.setState(Constant.PERSON_SYNC_ADD);
syncEntity.setLastUpdateTime(entity.getLastUpdateTime());
tenPersonSyncService.insert(syncEntity);
}
}
//下发设备通知
List<TenDeviceVo> devList = tenDeviceService.findByCellId(cellId);
for (TenDeviceVo dev : devList) {
CmdProcess.publishPersonChange(dev.getSn());
for(TenDeviceVo deviceVo: devList){
List<TenPersonSyncEntity> operationList = tenPersonSyncService.findDeviceAllAddPersons(deviceVo.getDeviceId(),deviceVo.getTenantId());
List<TenPersonOperationVo> voList = new ArrayList<>();
for(TenPersonSyncEntity syncEntity: operationList){
TenPersonOperationVo vo = new TenPersonOperationVo();
vo.setUid(syncEntity.getPersonId());
vo.setOperation(syncEntity.getState());
vo.setLast_update_stamp(syncEntity.getLastUpdateTime());
voList.add(vo);
}
int flag = serverApiService.personOperation(deviceVo.getSn(),voList);
if(flag == 0){
//下发成功删除状态为删除的同步人员
// tenPersonSyncService.removeAllDeletePersons(deviceEntity.getDeviceId(),tenantId);
}
}
return true;
}
@ -1042,7 +1049,9 @@ public class TenPersonServiceImpl implements TenPersonService {
} else { //以前不支持app现在支持app登录
if (entity.getAppFlag() == Constant.APP_LOGIN_YES) {
//默认密码123456
entity.setPassword("123456");
if(entity.getPassword()==null || entity.getPassword().length()==0){
entity.setPassword("123456");
}
//1.验证用户名
AppUserEntity checkUser = appUserService.findByUsername(entity.getUsername());
// if (checkUser != null) {
@ -1058,10 +1067,14 @@ public class TenPersonServiceImpl implements TenPersonService {
appUser.setMobile(entity.getMobile());
//sha256加密
String salt = RandomStringUtils.randomAlphanumeric(20);
appUser.setPassword(new Sha256Hash(entity.getPassword(), salt).toHex());
appUser.setSalt(salt);
// String salt = RandomStringUtils.randomAlphanumeric(20);
// appUser.setPassword(new Sha256Hash(entity.getPassword(), salt).toHex());
// appUser.setSalt(salt);
appUser.setPassword(DigestUtils.sha256Hex(entity.getPassword()));
appUser.setCreateTime(new Date());
appUser.setTenantId(entity.getTenantId());
appUserService.save(appUser);
//保存房产信息
@ -1164,11 +1177,31 @@ public class TenPersonServiceImpl implements TenPersonService {
}
tenPersonDao.updateById(entity);
List<TenDeviceVo> devList = tenDeviceService.findByCellId(entity.getCellId());
for (TenDeviceVo dev : devList) {
CmdProcess.publishPersonChange(dev.getSn());
//配置同步数据
List<TenPersonSyncEntity> syncEntitys = tenPersonSyncService.findByPersonId(entity.getPersonId(),entity.getTenantId());
for(TenPersonSyncEntity syncEn: syncEntitys){
syncEn.setLastUpdateTime(entity.getLastUpdateTime());
syncEn.setState(2);
tenPersonSyncService.updateById(syncEn);
//下发通知
List<TenPersonOperationVo> list = new ArrayList<>();
TenPersonOperationVo vo = new TenPersonOperationVo();
vo.setUid(entity.getPersonId());
vo.setOperation(2);
vo.setLast_update_stamp(entity.getLastUpdateTime());
list.add(vo);
serverApiService.personOperation(syncEn.getDeviceSn(),list);
}
// List<TenDeviceVo> devList = tenDeviceService.findByCellId(entity.getCellId());
// for (TenDeviceVo dev : devList) {
// CmdProcess.publishPersonChange(dev.getSn());
// }
return "OK";
}
@ -1194,10 +1227,10 @@ public class TenPersonServiceImpl implements TenPersonService {
// }
// }
int flag = tenPersonDao.updateById(entity);
List<TenDeviceVo> devList = tenDeviceService.findByCellId(entity.getCellId());
for (TenDeviceVo dev : devList) {
CmdProcess.publishPersonChange(dev.getSn());
}
// List<TenDeviceVo> devList = tenDeviceService.findByCellId(entity.getCellId());
// for (TenDeviceVo dev : devList) {
// CmdProcess.publishPersonChange(dev.getSn());
// }
if (flag == 1) {
return true;
}
@ -1694,9 +1727,12 @@ public class TenPersonServiceImpl implements TenPersonService {
@Transactional(rollbackFor = Exception.class)
public void savePersonModelList(List<PersonModel> list) {
List<TenPersonEntity> addList = new ArrayList<>();
Long cellId = 0l;
for (PersonModel personModel : list) {
if (personModel.getStatus() == 1) {
TenPersonEntity tenPerson = new TenPersonEntity();
TenCellEntity cellEntity = findCellByCellName(personModel.getCellName(), personModel.getTenantId());
TenBuildEntity tenBuildEntity = findBuildByNameAndUnit(personModel.getBuildName(),
personModel.getBuildUnit().replace("单元", ""),
@ -1709,6 +1745,8 @@ public class TenPersonServiceImpl implements TenPersonService {
tenPerson.setBuildId(tenBuildEntity.getBuildId());
tenPerson.setRoomId(tenRoomEntity.getRoomId());
cellId = cellEntity.getCellId();
tenPerson.setName(personModel.getName());
if (personModel.getGender().equals("")) {
tenPerson.setGender(1);
@ -1725,7 +1763,9 @@ public class TenPersonServiceImpl implements TenPersonService {
tenPerson.setUuid(UUIDUtil.uuid());
tenPerson.setTenantId(Long.parseLong(personModel.getTenantId()));
// tenPerson.setCreateBy(getUser().getUsername());
tenPerson.setCreateTime(new Date());
Date now = new Date();
tenPerson.setCreateTime(now);
tenPerson.setLastUpdateTime(now);
tenPerson.setRegisterType(Constant.RESGISTER_TYPE_FILE);
String userFileUrl = globalValue.getImagesDir() + "/" +
@ -1763,19 +1803,56 @@ public class TenPersonServiceImpl implements TenPersonService {
}
String tempFaceFileName = UUIDUtil.uuid() + ".jpg";
String tempFaceFilePath = tempPath + tempFaceFileName;
int res = PicSDK.getFace(personModel.getOrgImage(), tempFaceFilePath);
if (res != 0) {
return;
} else {
//1. 保存人脸图片
InputStream inputStreamFace = new FileInputStream(tempFaceFilePath);
PutObjectOptions putObjectOptionsFace = new PutObjectOptions(inputStreamFace.available(), -1);
putObjectOptions.setContentType("image/jpg");
minioClient.putObject(
minioConfig.getBucketName(), faceImageFileName, inputStreamFace, putObjectOptionsFace);
inputStreamFace.close();
tenPerson.setFaceImage(faceImageFileName);
String osName = System.getProperty("os.name");//获取指定键即os.name的系统属性,Windows 7
if (!Pattern.matches("Windows.*", osName)) {
int res = PicSDK.getFace(personModel.getOrgImage(), tempFaceFilePath);
if (res != 0) {
return;
} else {
//1. 保存人脸图片
InputStream inputStreamFace = new FileInputStream(tempFaceFilePath);
PutObjectOptions putObjectOptionsFace = new PutObjectOptions(inputStreamFace.available(), -1);
putObjectOptions.setContentType("image/jpg");
minioClient.putObject(
minioConfig.getBucketName(), faceImageFileName, inputStreamFace, putObjectOptionsFace);
inputStreamFace.close();
tenPerson.setFaceImage(faceImageFileName);
}
}else{
//windows 保存原始头像
tenPerson.setFaceImage(orgImageFileName);
}
// int res = PicSDK.getFace(personModel.getOrgImage(), tempFaceFilePath);
// if (res != 0) {
// return;
// } else {
// //1. 保存人脸图片
// InputStream inputStreamFace = new FileInputStream(tempFaceFilePath);
// PutObjectOptions putObjectOptionsFace = new PutObjectOptions(inputStreamFace.available(), -1);
// putObjectOptions.setContentType("image/jpg");
// minioClient.putObject(
// minioConfig.getBucketName(), faceImageFileName, inputStreamFace, putObjectOptionsFace);
// inputStreamFace.close();
// tenPerson.setFaceImage(faceImageFileName);
// }
// //1. 保存人脸图片
// InputStream inputStreamFace = new FileInputStream(tempFaceFilePath);
// PutObjectOptions putObjectOptionsFace = new PutObjectOptions(inputStreamFace.available(), -1);
// putObjectOptions.setContentType("image/jpg");
// minioClient.putObject(
// minioConfig.getBucketName(), faceImageFileName, inputStreamFace, putObjectOptionsFace);
// inputStreamFace.close();
// tenPerson.setFaceImage(faceImageFileName);
// tenPerson.setFaceImage(orgImageFileName);
//--------------------------------------------------------------------
@ -1802,8 +1879,6 @@ public class TenPersonServiceImpl implements TenPersonService {
}
//--------------------------------处理图片大小------------------------------------------------------
} catch (Exception e) {
e.printStackTrace();
tenPerson.setStatus(0);
@ -1811,6 +1886,49 @@ public class TenPersonServiceImpl implements TenPersonService {
continue;
}
tenPersonDao.insert(tenPerson);
//门禁表
if(personModel.getDoorCard()!=null && personModel.getDoorCard().length()>0){
TenDoorCardEntity doorCardEntity = new TenDoorCardEntity();
doorCardEntity.setDoorCard(personModel.getDoorCard());
doorCardEntity.setCellId(tenPerson.getCellId());
doorCardEntity.setPersonId(tenPerson.getPersonId());
tenDoorCardService.save(doorCardEntity);
}
//添加到同步表
List<TenDeviceVo> devList = tenDeviceService.findByCellId(cellEntity.getCellId());
for (TenDeviceVo dev : devList) {
TenPersonSyncEntity syncEntity = new TenPersonSyncEntity();
syncEntity.setPersonId(tenPerson.getPersonId());
syncEntity.setTenantId(tenPerson.getTenantId());
syncEntity.setDeviceSn(dev.getSn());
syncEntity.setDeviceId(dev.getDeviceId());
syncEntity.setState(1);
syncEntity.setLastUpdateTime(tenPerson.getLastUpdateTime());
tenPersonSyncService.insert(syncEntity);
}
}
}
//下发设备通知
List<TenDeviceVo> devList = tenDeviceService.findByCellId(cellId);
for(TenDeviceVo deviceVo: devList){
List<TenPersonSyncEntity> operationList = tenPersonSyncService.findDeviceAllAddPersons(deviceVo.getDeviceId(),deviceVo.getTenantId());
List<TenPersonOperationVo> voList = new ArrayList<>();
for(TenPersonSyncEntity syncEntity: operationList){
TenPersonOperationVo vo = new TenPersonOperationVo();
vo.setUid(syncEntity.getPersonId());
vo.setOperation(syncEntity.getState());
vo.setLast_update_stamp(syncEntity.getLastUpdateTime());
voList.add(vo);
}
int flag = serverApiService.personOperation(deviceVo.getSn(),voList);
if(flag == 0){
//下发成功删除状态为删除的同步人员
// tenPersonSyncService.removeAllDeletePersons(deviceEntity.getDeviceId(),tenantId);
}
}
}
@ -1850,4 +1968,9 @@ public class TenPersonServiceImpl implements TenPersonService {
return c;
}
@Override
public List<TenPersonEntity> getAllExpireGuest() {
return tenPersonDao.getAllExpireGuest();
}
}

View File

@ -0,0 +1,80 @@
package net.shapelight.modules.ten.service.impl;
import net.shapelight.modules.vo.TenPersonIdUpdateAllVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.shapelight.common.utils.PageUtils;
import net.shapelight.common.utils.Query;
import net.shapelight.modules.ten.dao.TenPersonSyncDao;
import net.shapelight.modules.ten.entity.TenPersonSyncEntity;
import net.shapelight.modules.ten.service.TenPersonSyncService;
@Service("tenPersonSyncService")
public class TenPersonSyncServiceImpl implements TenPersonSyncService {
@Autowired
private TenPersonSyncDao tenPersonSyncDao;
@Override
public List<TenPersonIdUpdateAllVo> getDeviceAllPersonIdUpdateTime(Long deviceId,Long tenantId) {
return tenPersonSyncDao.getDeviceAllPersonIdUpdateTime(deviceId,tenantId);
}
@Override
public int insert(TenPersonSyncEntity tenLicenseEntity) {
return tenPersonSyncDao.insert(tenLicenseEntity);
}
@Override
public int updateById(TenPersonSyncEntity entity) {
return tenPersonSyncDao.updateById(entity);
}
@Override
public void removeByDeviceId(Long deviceId,Long tenantId) {
tenPersonSyncDao.removeByDeviceId(deviceId,tenantId);
}
@Override
public void removeByPersonSyncId(Long personSyncId, Long tenantId) {
tenPersonSyncDao.removePersonSyncId(personSyncId, tenantId);
}
@Override
public void removeAllDeletePersons(Long deviceId, Long tenantId) {
tenPersonSyncDao.removeAllDeletePersons(deviceId, tenantId);
}
@Override
public TenPersonSyncEntity findByDeviceIdAndPersonId(Long deviceId, Long personId, Long tenantId) {
return tenPersonSyncDao.findByDeviceIdAndPersonId(deviceId, personId, tenantId);
}
@Override
public List<TenPersonSyncEntity> findByPersonId(Long personId, Long tenantId) {
return tenPersonSyncDao.findByPersonId(personId, tenantId);
}
@Override
public List<Map<String, String>> findGroupDevicePersons(List<Long> personIds, Long tenantId) {
return tenPersonSyncDao.findGroupDevicePersons(personIds, tenantId);
}
@Override
public List<TenPersonSyncEntity> findDeviceAllDeletePersons(Long deviceId, Long tenantId) {
return tenPersonSyncDao.findDeviceAllDeletePersons(deviceId,tenantId);
}
@Override
public List<TenPersonSyncEntity> findDeviceAllAddPersons(Long deviceId, Long tenantId) {
return tenPersonSyncDao.findDeviceAllAddPersons(deviceId,tenantId);
}
}

View File

@ -6,8 +6,8 @@ import io.minio.PutObjectOptions;
import net.shapelight.common.config.GlobalValue;
import net.shapelight.common.config.MinioConfig;
import net.shapelight.common.utils.*;
import net.shapelight.modules.dev.mqtt.CmdProcess;
import net.shapelight.modules.dev.mqtt.EmqHttpApi;
//import net.shapelight.modules.dev.mqtt.CmdProcess;
//import net.shapelight.modules.dev.mqtt.EmqHttpApi;
import net.shapelight.modules.ten.dao.TenBuildDao;
import net.shapelight.modules.ten.entity.*;
import net.shapelight.modules.ten.service.*;
@ -53,8 +53,8 @@ public class TenRecordServiceImpl implements TenRecordService {
private TenRoomService tenRoomService;
@Autowired
private TenBuildService tenBuildService;
@Autowired
private EmqHttpApi emqHttpApi;
// @Autowired
// private EmqHttpApi emqHttpApi;
@Override
public PageUtils queryPage(Map<String, Object> params) {
@ -240,13 +240,13 @@ public class TenRecordServiceImpl implements TenRecordService {
}
@Override
public TenRecordEntity getById(Long id, Long cellId) {
return tenRecordDao.selectById(id, cellId);
public TenRecordEntity getById(Long id, Long tenantId) {
return tenRecordDao.selectById(id, tenantId);
}
@Override
public String findLastRecordTime(Long personId, Long cellId) {
return tenRecordDao.findLastRecordTime(personId, cellId);
public String findLastRecordTime(Long personId, Long tenantId) {
return tenRecordDao.findLastRecordTime(personId, tenantId);
}
@Override
@ -303,16 +303,16 @@ public class TenRecordServiceImpl implements TenRecordService {
vo.setAddress(p.getCellName()+p.getBuildName()+p.getRoomName());
}
}
List<Long> webClients = emqHttpApi.getWebClients();
if(webClients.size()>0){
for(Long sysUserId: webClients){
Set<Long> cellIds = tenCellService.findUserCellIdList(sysUserId);
if(cellIds.contains(entity.getCellId())){
//发布websocket消息
CmdProcess.publishUpRecord(sysUserId,vo);
}
}
}
// List<Long> webClients = emqHttpApi.getWebClients();
// if(webClients.size()>0){
// for(Long sysUserId: webClients){
// Set<Long> cellIds = tenCellService.findUserCellIdList(sysUserId);
// if(cellIds.contains(entity.getCellId())){
// //发布websocket消息
// CmdProcess.publishUpRecord(sysUserId,vo);
// }
// }
// }
}

View File

@ -149,6 +149,8 @@ public class TenUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> i
}
}
sysUserService.removeById(userId);
tenUserScopeService.remove(new QueryWrapper<TenUserScopeEntity>()
.eq("user_id",user.getUserId()));
}
}
}

View File

@ -23,18 +23,18 @@ public class TenDeviceConfig {
}
*/
private Integer work_mode;
private Integer recognize_interval;
private Integer relay_suck_time;
private Boolean support_liveness;
private Integer liveness_score;
private Integer recognize_score;
private Integer recognize_distance;
private Float alert_temp_threshold;
private Boolean upload_face_pic;
private Integer upload_pic_mode;
private String upload_http_url;
private Boolean support_stranger;
private Integer work_mode; //0表示门禁模式,1表示门禁+测温模式默认为0 health_code_flag
private Integer recognize_interval; //连续两次人脸识别时间间隔默认3s rec_space
private Integer relay_suck_time; //继电器吸合开锁持续时间,默认5s
private Boolean support_liveness; //是否支持活体检测,默认true liveness_flag
private Integer liveness_score; //活体检测超过此值则判断为活体,默认60 rgb_live_thd
private Integer recognize_score; //人脸比对分值超过此值则判断为同一个人,默认65 rec_thd
private Integer recognize_distance; //默认1m
private Float alert_temp_threshold; //人脸温度超过此值则报警,默认5s temperature_alert
private Boolean upload_face_pic; //默认true upload_image_flag
private Integer upload_pic_mode; //枚举值0表示人脸图base64编码和人脸识别记录同时上传, 1表示人脸图通过http协议post上传
private String upload_http_url; //人脸图通过http上传的url地址
private Boolean support_stranger; //是否支持陌生人抓拍 默认false stranger_flag
public TenDeviceConfig(){
this.work_mode = 0;

View File

@ -0,0 +1,26 @@
package net.shapelight.modules.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
@Data
public class TenPersonOperationVo {
private static final long serialVersionUID = 1L;
@ApiModelProperty("人员ID")
private Long uid;
/**
* 更新时间
*/
@ApiModelProperty("更新时间")
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
// @JSONField(format="yyyy-MM-dd HH:mm:ss")
private Date last_update_stamp;
private Integer operation;
}

View File

@ -54,7 +54,7 @@
</resultMap>
<insert id="insert" parameterType="net.shapelight.modules.ten.entity.TenBuildEntity">
insert into ten_build_${cellId}
insert into ten_build
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="buildId != null">
build_id,
@ -166,7 +166,7 @@
<update id="updateById" parameterType="net.shapelight.modules.ten.entity.TenBuildEntity">
update ten_build_${cellId}
update ten_build
<set>
<if test="buildId != null">
build_id = #{buildId,jdbcType=BIGINT},
@ -225,37 +225,37 @@
<delete id="logicDeleteById">
update ten_build_${cellId} set delete_flag = 1
update ten_build set delete_flag = 1
where build_id = #{buildId,jdbcType=BIGINT}
</delete>
<delete id="logicDeleteByCellId">
update ten_build_${cellId} set delete_flag = 1
update ten_build set delete_flag = 1
where cell_id = #{cellId,jdbcType=BIGINT}
</delete>
<delete id="deleteById">
delete from ten_build_${cellId}
delete from ten_build
where build_id = #{buildId,jdbcType=BIGINT}
</delete>
<select id="selectById" resultMap="tenBuildMap">
select * from ten_build_${cellId}
select * from ten_build
where build_id = #{buildId}
</select>
<select id="selectByCellId" resultMap="tenBuildMap">
select * from ten_build_${cellId}
select * from ten_build
where cell_id = #{cellId} and delete_flag = 0
</select>
<select id="getBuildName" resultType="string">
select name from ten_build_${cellId}
select name from ten_build
where build_id = #{buildId}
</select>
<select id="getBuildUnit" resultType="string">
select unit from ten_build_${cellId}
select unit from ten_build
where build_id = #{buildId}
</select>
@ -265,39 +265,69 @@
<!--</select>-->
<select id="queryByNumberAndUnit" resultMap="tenBuildMap">
select * from ten_build_${cellId} where delete_flag = 0
and number = #{number} and unit = #{unit}
select * from ten_build where delete_flag = 0
and number = #{number} and unit = #{unit} and cell_id = #{cellId}
</select>
<select id="queryByNameAndUnit" resultMap="tenBuildMap">
select * from ten_build_${cellId} where delete_flag = 0
and name = #{name} and unit = #{unit}
select * from ten_build where delete_flag = 0
and name = #{name} and unit = #{unit} and cell_id = #{cellId}
</select>
<select id="findPageAll" resultMap="tenBuildMap" >
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select * from ten_build_${item}
</foreach>
) alias where delete_flag = 0
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select * from ten_build_${item}-->
<!--</foreach>-->
<!--) alias where delete_flag = 0-->
<!--<if test="params.areaId != null and params.areaId!=''">-->
<!--and alias.area_id = #{params.areaId}-->
<!--</if>-->
<!--<if test="params.cellId != null and params.cellId!=''">-->
<!--and alias.cell_id = #{params.cellId}-->
<!--</if>-->
<!--<if test="params.name != null and params.name!=''">-->
<!--and `name` like CONCAT('%', '${params.name}', '%')-->
<!--</if>-->
select * from ten_build
where delete_flag = 0
<if test="params.areaId != null and params.areaId!=''">
and alias.area_id = #{params.areaId}
and area_id = #{params.areaId}
</if>
<if test="params.cellId != null and params.cellId!=''">
and alias.cell_id = #{params.cellId}
and cell_id = #{params.cellId}
</if>
<if test="params.name != null and params.name!=''">
and `name` like CONCAT('%', '${params.name}', '%')
</if>
<if test="cellIds != null">
and cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
</select>
<select id="findAll" resultMap="tenBuildMap" >
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select * from ten_build_${item}
</foreach>
) alias where delete_flag = 0
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select * from ten_build_${item}-->
<!--</foreach>-->
<!--) alias where delete_flag = 0-->
select * from ten_build
where delete_flag = 0
<if test="cellIds != null">
and cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
</select>

View File

@ -26,7 +26,7 @@
<insert id="insert" parameterType="net.shapelight.modules.ten.entity.TenCarEntity">
insert into ten_car_${cellId}
insert into ten_car
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="carId != null">
car_id,
@ -130,12 +130,12 @@
</insert>
<delete id="deleteById" parameterType="java.lang.Long">
delete from ten_car_${cellId}
delete from ten_car
where car_id = #{carId,jdbcType=BIGINT}
</delete>
<update id="updateById" parameterType="net.shapelight.modules.ten.entity.TenCarEntity">
update ten_car_${cellId}
update ten_car
<set>
<if test="carId != null">
car_id = #{carId,jdbcType=BIGINT},
@ -190,25 +190,41 @@
</update>
<select id="selectById" parameterType="java.lang.Long" resultMap="tenCarMap">
select * from ten_car_${cellId}
select * from ten_car
where car_id = #{carId,jdbcType=BIGINT}
and cellId = #{cellId}
</select>
<select id="selectByVlp" resultMap="tenCarMap">
select * from ten_car_${cellId}
select * from ten_car
where vlp = #{vlp}
and cellId = #{cellId}
</select>
<select id="findPageAll" resultMap="tenCarMap">
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select * from ten_car_${item}
</foreach>
) alias where 1 = 1
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select * from ten_car_${item}-->
<!--</foreach>-->
<!--) alias where 1 = 1-->
<!--<if test="params.plate != null and params.plate!=''">-->
<!--and vlp like CONCAT('%', '${params.plate}', '%')-->
<!--</if>-->
<!--order by alias.register_time desc-->
select * from ten_car
where 1 = 1
<if test="params.plate != null and params.plate!=''">
and vlp like CONCAT('%', '${params.plate}', '%')
</if>
order by alias.register_time desc
<if test="cellIds != null">
and cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
order by register_time desc
</select>

View File

@ -35,29 +35,37 @@
<update id="createTenBuild" parameterType="String">
create table if not exists `ten_build_${cellId}` like `ten_build_0`;
create table if not exists `ten_build_${tenantId}` like `ten_build_0`;
</update>
<update id="createTenRoom" parameterType="String">
create table if not exists `ten_room_${cellId}` like `ten_room_0`;
create table if not exists `ten_room_${tenantId}` like `ten_room_0`;
</update>
<update id="createTenPerson" parameterType="String">
create table if not exists `ten_person_${cellId}` like `ten_person_0`;
create table if not exists `ten_person_${tenantId}` like `ten_person_0`;
</update>
<update id="createTenRecord" parameterType="String">
create table if not exists `ten_record_${cellId}` like `ten_record_0`;
create table if not exists `ten_record_${tenantId}` like `ten_record_0`;
</update>
<update id="createTenCar" parameterType="String">
create table if not exists `ten_car_${cellId}` like `ten_car_0`;
create table if not exists `ten_car_${tenantId}` like `ten_car_0`;
</update>
<update id="createTenPackRecord" parameterType="String">
create table if not exists `ten_pack_record_${cellId}` like `ten_pack_record_0`;
create table if not exists `ten_pack_record_${tenantId}` like `ten_pack_record_0`;
</update>
<update id="createTenPersonExtract" parameterType="String">
create table if not exists `ten_person_extract_${tenantId}` like `ten_person_extract_0`;
</update>
<update id="createTenPersonSync" parameterType="String">
create table if not exists `ten_person_sync_${tenantId}` like `ten_person_sync_0`;
</update>
<select id="queryList" resultMap="tenCellMap">

View File

@ -30,7 +30,7 @@
<insert id="insert" parameterType="net.shapelight.modules.ten.entity.TenPackRecordEntity">
insert into ten_pack_record_${cellId}
insert into ten_pack_record
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="recordId != null">
record_id,
@ -163,7 +163,7 @@
<!--</delete>-->
<update id="updateById" parameterType="net.shapelight.modules.ten.entity.TenPackRecordEntity">
update ten_pack_record_${cellId}
update ten_pack_record
<set>
<if test="recordId != null">
record_id = #{recordId,jdbcType=VARCHAR},
@ -230,20 +230,34 @@
</update>
<select id="selectByRecordIdAndPackId" resultMap="tenPackRecordMap">
select * from ten_pack_record_${cellId}
select * from ten_pack_record
where record_id = #{recordId} and park_id = #{parkId}
and cellId = #{cellId}
</select>
<select id="findPageAll" resultMap="tenPackRecordMap">
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select * from ten_pack_record_${item}
</foreach>
) alias where 1 = 1
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select * from ten_pack_record_${item}-->
<!--</foreach>-->
<!--) alias where 1 = 1-->
<!--<if test="params.plate != null and params.plate!=''">-->
<!--and vlp like CONCAT('%', '${params.plate}', '%')-->
<!--</if>-->
<!--order by alias.in_time desc-->
select * from ten_pack_record
where 1 = 1
<if test="params.plate != null and params.plate!=''">
and vlp like CONCAT('%', '${params.plate}', '%')
</if>
order by alias.in_time desc
<if test="cellIds != null">
and cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
order by in_time desc
</select>

View File

@ -99,7 +99,7 @@
<insert id="insert" parameterType="net.shapelight.modules.ten.entity.TenPersonEntity">
insert into ten_person_${cellId}
insert into ten_person
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="personId != null">
person_id,
@ -342,7 +342,7 @@
<update id="updateById" parameterType="net.shapelight.modules.ten.entity.TenPersonEntity">
update ten_person_${cellId}
update ten_person
<set>
<if test="personId != null">
person_id = #{personId,jdbcType=BIGINT},
@ -467,26 +467,26 @@
<delete id="deleteById">
delete from ten_person_${cellId}
delete from ten_person
where person_id = #{personId,jdbcType=BIGINT}
</delete>
<delete id="logicDeleteById">
update ten_person_${cellId} set delete_flag = 1
update ten_person set delete_flag = 1
where person_id = #{personId}
</delete>
<select id="selectById" resultMap="BaseResultMap">
select p.*,r.layer,r.room_name from ten_person_${cellId} p left join ten_room_${cellId} r
select p.*,r.layer,r.room_name from ten_person p left join ten_room r
on p.room_id = r.room_id where person_id = #{personId}
</select>
<select id="selectByMemberId" resultMap="BaseResultMap">
select * from ten_person_${cellId} where member_id = #{memberId}
select * from ten_person where member_id = #{memberId}
</select>
<select id="selectByRoomId" resultMap="BaseResultMap">
select p.*,r.layer,r.room_name from ten_person_${cellId} p left join ten_room_${cellId} r
select p.*,r.layer,r.room_name from ten_person p left join ten_room r
on p.room_id = r.room_id where p.room_id = #{roomId} and p.delete_flag = 0
<if test="key != null and key!=''">
and (p.name like CONCAT('%', '${key}', '%')
@ -497,7 +497,7 @@
</select>
<select id="selectByRoomIdForGuest" resultMap="BaseResultMap">
select p.*,r.layer,r.room_name from ten_person_${cellId} p left join ten_room_${cellId} r
select p.*,r.layer,r.room_name from ten_person p left join ten_room r
on p.room_id = r.room_id where p.room_id = #{roomId} and p.delete_flag = 0
and p.person_type = 5005
<if test="key != null and key!=''">
@ -509,14 +509,15 @@
<select id="findByName" resultType="net.shapelight.modules.ten.entity.TenPersonEntity">
select * from ten_person_${cellId}
select * from ten_person
where room_id = #{roomId} and delete_flag = 0
and name = #{name} and (person_type = 5000 or person_type = 5001 or person_type = 5002)
</select>
<select id="selectByCellId" resultMap="BaseResultMap">
select p.*,r.layer,r.room_name from ten_person_${cellId} p left join ten_room_${cellId} r
select p.*,r.layer,r.room_name from ten_person p left join ten_room r
on p.room_id = r.room_id where p.delete_flag = 0
and p.cell_id = #{cellId}
<if test="key != null and key!=''">
and (p.name like CONCAT('%', '${key}', '%')
or p.mobile like CONCAT('%', '${key}', '%'))
@ -526,115 +527,224 @@
</select>
<select id="findPageAll" resultMap="BaseResultMap">
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select p.*,r.layer,r.room_name from ten_person_${item} p left join ten_room_${item} r
on p.room_id = r.room_id where p.delete_flag = 0
<if test="params.buildId != null and params.buildId!=''">
and r.build_id = #{params.buildId}
</if>
<if test="params.layer != null and params.layer!=''">
and r.layer = #{params.layer}
</if>
<if test="params.roomName != null and params.roomName!=''">
and r.room_name like CONCAT('%', '${params.roomName}', '%')
</if>
<if test="params.name != null and params.name!=''">
and p.name like CONCAT('%', '${params.name}', '%')
</if>
<if test="params.gender != null and params.gender!=''">
and p.gender = #{params.gender}
</if>
<if test="params.status != null and params.status!=''">
and p.status = #{params.status}
</if>
<if test="params.idCard != null and params.idCard!=''">
and p.id_card like CONCAT('%', '${params.idCard}', '%')
</if>
<if test="params.mobile != null and params.mobile!=''">
and p.mobile like CONCAT('%', '${params.mobile}', '%')
</if>
<if test="params.personType != null and params.personType!=''">
and p.person_type = #{params.personType}
</if>
<if test="params.faceFailure != null and params.faceFailure!=''">
and p.face_failure = #{params.faceFailure}
</if>
<if test="params.personTypeList != null">
and p.person_type in
<foreach item="personType" collection="params.personTypeList" open="(" separator="," close=")">
#{personType}
</foreach>
</if>
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select p.*,r.layer,r.room_name from ten_person_${item} p left join ten_room_${item} r-->
<!--on p.room_id = r.room_id where p.delete_flag = 0-->
<!--<if test="params.buildId != null and params.buildId!=''">-->
<!--and r.build_id = #{params.buildId}-->
<!--</if>-->
<!--<if test="params.layer != null and params.layer!=''">-->
<!--and r.layer = #{params.layer}-->
<!--</if>-->
<!--<if test="params.roomName != null and params.roomName!=''">-->
<!--and r.room_name like CONCAT('%', '${params.roomName}', '%')-->
<!--</if>-->
<!--<if test="params.name != null and params.name!=''">-->
<!--and p.name like CONCAT('%', '${params.name}', '%')-->
<!--</if>-->
<!--<if test="params.gender != null and params.gender!=''">-->
<!--and p.gender = #{params.gender}-->
<!--</if>-->
<!--<if test="params.status != null and params.status!=''">-->
<!--and p.status = #{params.status}-->
<!--</if>-->
<!--<if test="params.idCard != null and params.idCard!=''">-->
<!--and p.id_card like CONCAT('%', '${params.idCard}', '%')-->
<!--</if>-->
<!--<if test="params.mobile != null and params.mobile!=''">-->
<!--and p.mobile like CONCAT('%', '${params.mobile}', '%')-->
<!--</if>-->
<!--<if test="params.personType != null and params.personType!=''">-->
<!--and p.person_type = #{params.personType}-->
<!--</if>-->
<!--<if test="params.faceFailure != null and params.faceFailure!=''">-->
<!--and p.face_failure = #{params.faceFailure}-->
<!--</if>-->
<!--<if test="params.personTypeList != null">-->
<!--and p.person_type in-->
<!--<foreach item="personType" collection="params.personTypeList" open="(" separator="," close=")">-->
<!--#{personType}-->
<!--</foreach>-->
<!--</if>-->
</foreach>
) alias where 1 = 1 order by alias.person_id desc
<!--</foreach>-->
<!--) alias where 1 = 1 order by alias.person_id desc-->
select p.*,r.layer,r.room_name from ten_person p left join ten_room r
on p.room_id = r.room_id where p.delete_flag = 0
<if test="params.buildId != null and params.buildId!=''">
and r.build_id = #{params.buildId}
</if>
<if test="params.layer != null and params.layer!=''">
and r.layer = #{params.layer}
</if>
<if test="params.roomName != null and params.roomName!=''">
and r.room_name like CONCAT('%', '${params.roomName}', '%')
</if>
<if test="params.name != null and params.name!=''">
and p.name like CONCAT('%', '${params.name}', '%')
</if>
<if test="params.gender != null and params.gender!=''">
and p.gender = #{params.gender}
</if>
<if test="params.status != null and params.status!=''">
and p.status = #{params.status}
</if>
<if test="params.idCard != null and params.idCard!=''">
and p.id_card like CONCAT('%', '${params.idCard}', '%')
</if>
<if test="params.mobile != null and params.mobile!=''">
and p.mobile like CONCAT('%', '${params.mobile}', '%')
</if>
<if test="params.personType != null and params.personType!=''">
and p.person_type = #{params.personType}
</if>
<if test="params.faceFailure != null and params.faceFailure!=''">
and p.face_failure = #{params.faceFailure}
</if>
<if test="params.personTypeList != null">
and p.person_type in
<foreach item="personType" collection="params.personTypeList" open="(" separator="," close=")">
#{personType}
</foreach>
</if>
<if test="cellIds != null">
and p.cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
order by p.create_time desc
</select>
<select id="findAllCount" resultType="int">
SELECT count(*) from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select person_id from ten_person_${item} where delete_flag = 0
<if test="params.status != null and params.status!=''">
and status = #{params.status}
</if>
<if test="params.personType != null and params.personType!=''">
and person_type = #{params.personType}
</if>
<if test="params.personTypeList != null">
and person_type in
<foreach item="personType" collection="params.personTypeList" open="(" separator="," close=")">
#{personType}
</foreach>
</if>
</foreach>
) alias where 1 = 1 order by alias.person_id desc
<!--SELECT count(*) from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select person_id from ten_person_${item} where delete_flag = 0-->
<!--<if test="params.status != null and params.status!=''">-->
<!--and status = #{params.status}-->
<!--</if>-->
<!--<if test="params.personType != null and params.personType!=''">-->
<!--and person_type = #{params.personType}-->
<!--</if>-->
<!--<if test="params.personTypeList != null">-->
<!--and person_type in-->
<!--<foreach item="personType" collection="params.personTypeList" open="(" separator="," close=")">-->
<!--#{personType}-->
<!--</foreach>-->
<!--</if>-->
<!--</foreach>-->
<!--) alias where 1 = 1 order by alias.person_id desc-->
select count(*) from ten_person where delete_flag = 0
<if test="params.status != null and params.status!=''">
and status = #{params.status}
</if>
<if test="params.personType != null and params.personType!=''">
and person_type = #{params.personType}
</if>
<if test="params.personTypeList != null">
and person_type in
<foreach item="personType" collection="params.personTypeList" open="(" separator="," close=")">
#{personType}
</foreach>
</if>
<if test="cellIds != null">
and cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
</select>
<select id="findVerifyPageAll" resultMap="BaseResultMap">
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select p.*,r.layer,r.room_name from ten_person_${item} p left join ten_room_${item} r
on p.room_id = r.room_id where p.delete_flag = 0 and p.status != 0
<if test="params.name != null and params.name!=''">
and p.name like CONCAT('%', '${params.name}', '%')
</if>
<if test="params.gender != null and params.gender!=''">
and p.gender = #{params.gender}
</if>
<if test="params.idCard != null and params.idCard!=''">
and p.id_card like CONCAT('%', '${params.idCard}', '%')
</if>
<if test="params.mobile != null and params.mobile!=''">
and p.mobile = #{params.mobile}
</if>
</foreach>
) alias where 1 = 1 order by alias.person_id desc
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select p.*,r.layer,r.room_name from ten_person_${item} p left join ten_room_${item} r-->
<!--on p.room_id = r.room_id where p.delete_flag = 0 and p.status != 0-->
<!--<if test="params.name != null and params.name!=''">-->
<!--and p.name like CONCAT('%', '${params.name}', '%')-->
<!--</if>-->
<!--<if test="params.gender != null and params.gender!=''">-->
<!--and p.gender = #{params.gender}-->
<!--</if>-->
<!--<if test="params.idCard != null and params.idCard!=''">-->
<!--and p.id_card like CONCAT('%', '${params.idCard}', '%')-->
<!--</if>-->
<!--<if test="params.mobile != null and params.mobile!=''">-->
<!--and p.mobile = #{params.mobile}-->
<!--</if>-->
<!--</foreach>-->
<!--) alias where 1 = 1 order by alias.person_id desc-->
select p.*,r.layer,r.room_name from ten_person p left join ten_room r
on p.room_id = r.room_id where p.delete_flag = 0 and p.status != 0
<if test="params.name != null and params.name!=''">
and p.name like CONCAT('%', '${params.name}', '%')
</if>
<if test="params.gender != null and params.gender!=''">
and p.gender = #{params.gender}
</if>
<if test="params.idCard != null and params.idCard!=''">
and p.id_card like CONCAT('%', '${params.idCard}', '%')
</if>
<if test="params.mobile != null and params.mobile!=''">
and p.mobile = #{params.mobile}
</if>
<if test="cellIds != null">
and p.cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
order by p.create_time desc
</select>
<select id="globalSearchPageAll" resultMap="BaseResultMap">
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select p.* from ten_person_${item} p
where p.delete_flag = 0
<if test="params.key != null and params.key!=''">
and (p.name like CONCAT('%', '${params.key}', '%')
or p.id_card like CONCAT('%', '${params.key}', '%')
or p.mobile like CONCAT('%', '${params.key}', '%'))
</if>
</foreach>
) alias where 1 = 1
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select p.* from ten_person_${item} p-->
<!--where p.delete_flag = 0-->
<!--<if test="params.key != null and params.key!=''">-->
<!--and (p.name like CONCAT('%', '${params.key}', '%')-->
<!--or p.id_card like CONCAT('%', '${params.key}', '%')-->
<!--or p.mobile like CONCAT('%', '${params.key}', '%'))-->
<!--</if>-->
<!--</foreach>-->
<!--) alias where 1 = 1-->
select * from ten_person
where delete_flag = 0
<if test="params.key != null and params.key!=''">
and (name like CONCAT('%', '${params.key}', '%')
or id_card like CONCAT('%', '${params.key}', '%')
or mobile like CONCAT('%', '${params.key}', '%'))
</if>
<if test="cellIds != null">
and cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
</select>
<select id="findUpdatePerson" resultMap="updateMap">
select * from ten_person_${cellId}
select * from ten_person
where 1=1
<if test="cellId != null and cellId!=''">
and cell_id = #{cellId}
@ -655,7 +765,7 @@
<select id="findAllPersonIdUpdate" resultType="net.shapelight.modules.vo.TenPersonIdUpdateVo">
select member_id,last_update_time from ten_person_${cellId}
select member_id,last_update_time from ten_person
where 1=1
<if test="cellId != null and cellId!=''">
and cell_id = #{cellId}
@ -670,8 +780,8 @@
<select id="findAllPersonIdUpdateAll" resultMap="idupdateMap">
select person_id,last_update_time from ten_person_${cellId}
where 1=1
select person_id,last_update_time from ten_person
where delete_flag = 0 and status = 0
<if test="cellId != null and cellId!=''">
and cell_id = #{cellId}
</if>
@ -685,7 +795,7 @@
<select id="findByLastUpdatePerson" resultMap="updateMap">
select * from ten_person_${cellId}
select * from ten_person
where 1=1
<if test="cellId != null and cellId!=''">
and cell_id = #{cellId}
@ -702,11 +812,12 @@
</select>
<select id="findAllByCellId" resultMap="updateMap">
select * from ten_person_${cellId}
select * from ten_person
where cell_id = #{cellId}
</select>
<select id="findRoomCount" resultType="int">
select count(*) from ten_person_${cellId}
select count(*) from ten_person
where delete_flag = 0
<if test="cellId != null and cellId!=''">
and cell_id = #{cellId}
@ -717,7 +828,7 @@
</select>
<select id="findBuildCount" resultType="int">
select count(*) from ten_person_${cellId}
select count(*) from ten_person
where delete_flag = 0
<if test="cellId != null and cellId!=''">
and cell_id = #{cellId}
@ -728,20 +839,34 @@
</select>
<select id="findCellCount" resultType="int">
select count(*) from ten_person_${cellId}
select count(*) from ten_person
where delete_flag = 0
and cell_id = #{cellId}
</select>
<select id="findCellOwnerCount" resultType="int">
select count(*) from ten_person_${cellId}
select count(*) from ten_person
where delete_flag = 0
and person_type in(5000,5001,5002)
and cell_id = #{cellId}
<!--<if test="cellId != null and cellId!=''">-->
<!--and cell_id = #{cellId}-->
<!--</if>-->
</select>
<select id="findLabelCount" resultType="int">
select count(*) from ten_person_${cellId}
select count(*) from ten_person
where delete_flag = 0
and label_id = #{labelId}
where cell_id = #{cellId}
</select>
<select id="getAllExpireGuest" resultType="net.shapelight.modules.ten.entity.TenPersonEntity">
SELECT * FROM ten_person
where person_type = 5005
and live_end &lt; NOW()
and delete_flag = 0
</select>
</mapper>

View File

@ -0,0 +1,167 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.shapelight.modules.ten.dao.TenPersonSyncDao">
<!-- 可根据自己的需求,是否要使用 -->
<resultMap type="net.shapelight.modules.ten.entity.TenPersonSyncEntity" id="tenPersonSyncMap">
<result property="personSyncId" column="person_sync_id"/>
<result property="deviceId" column="device_id"/>
<result property="deviceSn" column="device_sn"/>
<result property="personId" column="person_id"/>
<result property="state" column="state"/>
<result property="lastUpdateTime" column="last_update_time"/>
<result property="tenantId" column="tenant_id"/>
</resultMap>
<resultMap id="idupdatetime" type="net.shapelight.modules.vo.TenPersonIdUpdateAllVo">
<result column="person_id" jdbcType="BIGINT" property="uid"/>
<result column="last_update_time" jdbcType="TIMESTAMP" property="last_update_stamp"/>
</resultMap>
<insert id="insert" parameterType="net.shapelight.modules.ten.entity.TenPersonSyncEntity">
insert into ten_person_sync_${tenantId}
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="personSyncId != null">
person_sync_id,
</if>
<if test="deviceId != null">
device_id,
</if>
<if test="deviceSn != null">
device_sn,
</if>
<if test="personId != null">
person_id,
</if>
<if test="state != null">
state,
</if>
<if test="lastUpdateTime != null">
last_update_time,
</if>
<if test="tenantId != null">
tenant_id
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="personSyncId != null">
#{personSyncId,jdbcType=BIGINT},
</if>
<if test="deviceId != null">
#{deviceId,jdbcType=BIGINT},
</if>
<if test="deviceSn != null">
#{deviceSn},
</if>
<if test="personId != null">
#{personId,jdbcType=BIGINT},
</if>
<if test="state != null">
#{state,jdbcType=TINYINT},
</if>
<if test="lastUpdateTime != null">
#{lastUpdateTime,jdbcType=TIMESTAMP},
</if>
<if test="tenantId != null">
#{tenantId,jdbcType=BIGINT},
</if>
</trim>
</insert>
<update id="updateById" parameterType="net.shapelight.modules.ten.entity.TenPersonSyncEntity">
update ten_person_sync_${tenantId}
<set>
<if test="personSyncId != null">
person_sync_id = #{personSyncId,jdbcType=BIGINT},
</if>
<if test="deviceId != null">
device_id = #{deviceId,jdbcType=BIGINT},
</if>
<if test="deviceSn != null">
device_sn = #{deviceSn},
</if>
<if test="personId != null">
person_id = #{personId,jdbcType=BIGINT},
</if>
<if test="state != null">
state = #{state,jdbcType=TINYINT},
</if>
<if test="lastUpdateTime != null">
last_update_time = #{lastUpdateTime,jdbcType=TIMESTAMP},
</if>
<if test="tenantId != null">
tenant_id = #{tenantId,jdbcType=TIMESTAMP},
</if>
</set>
where person_sync_id = #{personSyncId,jdbcType=BIGINT}
</update>
<select id="getDeviceAllPersonIdUpdateTime" resultMap="idupdatetime">
select person_id,last_update_time from ten_person_sync_${tenantId}
where 1=1
<if test="deviceId != null and deviceId!=''">
and device_id = #{deviceId}
</if>
and state &lt;&gt; 3
</select>
<delete id="removeAllDeletePersons">
delete from ten_person_sync_${tenantId}
where device_id = #{deviceId}
and state = 3
</delete>
<delete id="removeByDeviceId">
delete from ten_person_sync_${tenantId}
where device_id = #{deviceId}
</delete>
<delete id="removePersonSyncId">
delete from ten_person_sync_${tenantId}
where person_sync_id = #{personSyncId}
</delete>
<select id="findByDeviceIdAndPersonId" resultType="net.shapelight.modules.ten.entity.TenPersonSyncEntity">
select * from ten_person_sync_${tenantId}
where device_id = #{deviceId}
and person_id = #{personId}
</select>
<select id="findByPersonId" resultType="net.shapelight.modules.ten.entity.TenPersonSyncEntity">
select * from ten_person_sync_${tenantId}
where person_id = #{personId}
</select>
<select id="findGroupDevicePersons" resultType="map">
select device_sn as deviceSn,group_concat(person_id,"_",last_update_time separator ",") as plist
from ten_person_sync_${tenantId} where 1= 1
<if test="personIds != null">
and person_id in
<foreach item="personId" collection="personIds" open="(" separator="," close=")">
#{personId}
</foreach>
</if>
GROUP BY device_sn
</select>
<select id="findDeviceAllDeletePersons" resultType="net.shapelight.modules.ten.entity.TenPersonSyncEntity">
select * from ten_person_sync_${tenantId}
where device_id = #{deviceId}
and state = 3
</select>
<select id="findDeviceAllAddPersons" resultType="net.shapelight.modules.ten.entity.TenPersonSyncEntity">
select * from ten_person_sync_${tenantId}
where device_id = #{deviceId}
and state = 1
</select>
</mapper>

View File

@ -21,7 +21,7 @@
<insert id="insert" parameterType="net.shapelight.modules.ten.entity.TenRecordEntity">
insert into ten_record_${cellId}
insert into ten_record_${tenantId}
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="recordId != null">
record_id,
@ -102,7 +102,7 @@
<update id="updateById" parameterType="net.shapelight.modules.ten.entity.TenRecordEntity">
update ten_record_${cellId}
update ten_record_${tenantId}
<set>
<if test="recordId != null">
record_id = #{recordId,jdbcType=BIGINT},
@ -146,24 +146,40 @@
<delete id="deleteById" parameterType="java.lang.Long">
delete from ten_record_${cellId}
delete from ten_record_${tenantId}
where record_id = #{recordId,jdbcType=BIGINT}
</delete>
<select id="selectById" parameterType="java.lang.Long" resultMap="tenRecordMap">
select * from ten_record_${cellId}
select * from ten_record_${tenantId}
where record_id = #{recordId,jdbcType=BIGINT}
</select>
<select id="findPageAll" resultMap="tenRecordMap">
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select r.*,t.name from ten_record_${item} r left join ten_person_${item} t on r.person_id = t.person_id
</foreach>
) alias where 1=1
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select r.*,t.name from ten_record_${item} r left join ten_person_${item} t on r.person_id = t.person_id-->
<!--</foreach>-->
<!--) alias where 1=1-->
<!--<if test="params.cellId != null and params.cellId!=''">-->
<!--and alias.cell_id = #{params.cellId}-->
<!--</if>-->
<!--<if test="params.name != null and params.name!=''">-->
<!--and `name` like CONCAT('%', '${params.name}', '%')-->
<!--</if>-->
<!--<if test="params.recordTimeStart != null and params.recordTimeStart!=''">-->
<!--and `record_time` &gt;= #{params.recordTimeStart}-->
<!--</if>-->
<!--<if test="params.recordTimeEnd != null and params.recordTimeStart!=''">-->
<!--and `record_time` &lt; #{params.recordTimeEnd}-->
<!--</if>-->
<!--order by record_time desc-->
select r.*,t.name from ten_record_${params.tenantId} r left join ten_person t on r.person_id = t.person_id
<if test="params.cellId != null and params.cellId!=''">
and alias.cell_id = #{params.cellId}
and r.cell_id = #{params.cellId}
</if>
<if test="params.name != null and params.name!=''">
and `name` like CONCAT('%', '${params.name}', '%')
@ -174,17 +190,41 @@
<if test="params.recordTimeEnd != null and params.recordTimeStart!=''">
and `record_time` &lt; #{params.recordTimeEnd}
</if>
<if test="cellIds != null">
and r.cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
order by record_time desc
</select>
<select id="findAll" resultMap="tenRecordMap">
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select r.*,t.name from ten_record_${item} r left join ten_person_${item} t on r.person_id = t.person_id
</foreach>
) alias where 1=1
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select r.*,t.name from ten_record_${item} r left join ten_person_${item} t on r.person_id = t.person_id-->
<!--</foreach>-->
<!--) alias where 1=1-->
<!--<if test="params.cellId != null and params.cellId!=''">-->
<!--and alias.cell_id = #{params.cellId}-->
<!--</if>-->
<!--<if test="params.name != null and params.name!=''">-->
<!--and `name` like CONCAT('%', '${params.name}', '%')-->
<!--</if>-->
<!--<if test="params.recordTimeStart != null and params.recordTimeStart!=''">-->
<!--and `record_time` &gt;= #{params.recordTimeStart}-->
<!--</if>-->
<!--<if test="params.recordTimeEnd != null and params.recordTimeStart!=''">-->
<!--and `record_time` &lt; #{params.recordTimeEnd}-->
<!--</if>-->
<!--order by record_time desc-->
select r.*,t.name from ten_record_${params.tenantId} r left join ten_person t on r.person_id = t.person_id
<if test="params.cellId != null and params.cellId!=''">
and alias.cell_id = #{params.cellId}
and r.cell_id = #{params.cellId}
</if>
<if test="params.name != null and params.name!=''">
and `name` like CONCAT('%', '${params.name}', '%')
@ -195,18 +235,37 @@
<if test="params.recordTimeEnd != null and params.recordTimeStart!=''">
and `record_time` &lt; #{params.recordTimeEnd}
</if>
<if test="cellIds != null">
and r.cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
order by record_time desc
</select>
<select id="findHourAll" resultType="int">
SELECT count(*) from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select record_id,cell_id,record_time from ten_record_${item}
</foreach>
) alias where 1=1
<!--SELECT count(*) from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select record_id,cell_id,record_time from ten_record_${item}-->
<!--</foreach>-->
<!--) alias where 1=1-->
<!--<if test="params.cellId != null and params.cellId!=''">-->
<!--and alias.cell_id = #{params.cellId}-->
<!--</if>-->
<!--<if test="params.recordTimeStart != null and params.recordTimeStart!=''">-->
<!--and `record_time` &gt;= #{params.recordTimeStart}-->
<!--</if>-->
<!--<if test="params.recordTimeEnd != null and params.recordTimeStart!=''">-->
<!--and `record_time` &lt; #{params.recordTimeEnd}-->
<!--</if>-->
<!--order by record_time desc-->
select count(*) from ten_record_${params.tenantId} where 1 = 1
<if test="params.cellId != null and params.cellId!=''">
and alias.cell_id = #{params.cellId}
and cell_id = #{params.cellId}
</if>
<if test="params.recordTimeStart != null and params.recordTimeStart!=''">
and `record_time` &gt;= #{params.recordTimeStart}
@ -214,40 +273,94 @@
<if test="params.recordTimeEnd != null and params.recordTimeStart!=''">
and `record_time` &lt; #{params.recordTimeEnd}
</if>
order by record_time desc
<if test="cellIds != null">
and cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
</select>
<select id="findPageBlackRecord" resultMap="tenRecordMap">
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select r.*,t.name from ten_record_${item} r
left join ten_person_${item} t on r.person_id = t.person_id
where t.delete_flag = 0
and t.person_type = 5008
</foreach>
) alias where 1=1
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select r.*,t.name from ten_record_${item} r-->
<!--left join ten_person_${item} t on r.person_id = t.person_id-->
<!--where t.delete_flag = 0-->
<!--and t.person_type = 5008-->
<!--</foreach>-->
<!--) alias where 1=1-->
<!--<if test="params.cellId != null and params.cellId!=''">-->
<!--and alias.cell_id = #{params.cellId}-->
<!--</if>-->
<!--<if test="params.name != null and params.name!=''">-->
<!--and `name` like CONCAT('%', '${params.name}', '%')-->
<!--</if>-->
<!--<if test="params.recordTimeStart != null and params.recordTimeStart!=''">-->
<!--and `record_time` &gt;= #{params.recordTimeStart}-->
<!--</if>-->
<!--<if test="params.recordTimeEnd != null and params.recordTimeStart!=''">-->
<!--and `record_time` &lt; #{params.recordTimeEnd}-->
<!--</if>-->
<!--order by record_time desc-->
select r.*,t.name from ten_record_${params.tenantId} r
left join ten_person t on r.person_id = t.person_id
where t.delete_flag = 0
and t.person_type = 5008
<if test="params.cellId != null and params.cellId!=''">
and alias.cell_id = #{params.cellId}
and r.cell_id = #{params.cellId}
</if>
<if test="params.name != null and params.name!=''">
and `name` like CONCAT('%', '${params.name}', '%')
and t.`name` like CONCAT('%', '${params.name}', '%')
</if>
<if test="params.recordTimeStart != null and params.recordTimeStart!=''">
and `record_time` &gt;= #{params.recordTimeStart}
and r.`record_time` &gt;= #{params.recordTimeStart}
</if>
<if test="params.recordTimeEnd != null and params.recordTimeStart!=''">
and `record_time` &lt; #{params.recordTimeEnd}
and r.`record_time` &lt; #{params.recordTimeEnd}
</if>
order by record_time desc
<if test="cellIds != null">
and r.cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
order by r.record_time desc
</select>
<select id="findPageRoomRecord" resultMap="tenRecordMap">
select r.*,t.name from ten_record_${params.cellId} r
left join ten_person_${params.cellId} t on r.person_id = t.person_id
<!--select r.*,t.name from ten_record_${params.cellId} r-->
<!--left join ten_person_${params.cellId} t on r.person_id = t.person_id-->
<!--where 1=1-->
<!--<if test="params.cellId != null and params.cellId!=''">-->
<!--and t.cell_id = #{params.cellId}-->
<!--</if>-->
<!--<if test="params.roomId != null and params.roomId!=''">-->
<!--and t.room_id = #{params.roomId}-->
<!--</if>-->
<!--<if test="params.name != null and params.name!=''">-->
<!--and `name` like CONCAT('%', '${params.name}', '%')-->
<!--</if>-->
<!--<if test="params.recordTimeStart != null and params.recordTimeStart!=''">-->
<!--and `record_time` &gt;= #{params.recordTimeStart}-->
<!--</if>-->
<!--<if test="params.recordTimeEnd != null and params.recordTimeStart!=''">-->
<!--and `record_time` &lt; #{params.recordTimeEnd}-->
<!--</if>-->
<!--order by record_time desc-->
select r.*,t.name from ten_record_${params.tenantId} r
left join ten_person t on r.person_id = t.person_id
where 1=1
<if test="params.cellId != null and params.cellId!=''">
and t.cell_id = #{params.cellId}
and r.cell_id = #{params.cellId}
</if>
<if test="params.roomId != null and params.roomId!=''">
and t.room_id = #{params.roomId}
@ -266,8 +379,9 @@
<select id="findLastRecordTime" resultType="string">
select record_time from ten_record_${cellId}
where person_id = #{personId} order by record_time desc limit 1
select record_time from ten_record_${tenantId}
where person_id = #{personId}
order by record_time desc limit 1
</select>

View File

@ -42,7 +42,7 @@
</resultMap>
<insert id="insert" parameterType="net.shapelight.modules.ten.entity.TenRoomEntity">
insert into ten_room_${cellId}
insert into ten_room
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="roomId != null">
room_id,
@ -190,7 +190,7 @@
<update id="updateById" parameterType="net.shapelight.modules.ten.entity.TenRoomEntity">
update ten_room_${cellId}
update ten_room
<set>
<if test="roomId != null">
room_id = #{roomId,jdbcType=BIGINT},
@ -266,27 +266,27 @@
</update>
<select id="selectById" parameterType="java.lang.Long" resultMap="BaseResultMap">
select * from ten_room_${cellId}
select * from ten_room
where room_id = #{roomId,jdbcType=BIGINT}
</select>
<delete id="deleteById">
delete from ten_room_${cellId}
delete from ten_room
where room_id = #{roomId,jdbcType=BIGINT}
</delete>
<delete id="logicDeleteById">
update ten_room_${cellId} set delete_flag = 1
update ten_room_$ set delete_flag = 1
where room_id = #{roomId,jdbcType=BIGINT}
</delete>
<delete id="logicDeleteByBuildId">
update ten_room_${cellId} set delete_flag = 1
update ten_room set delete_flag = 1
where build_id = #{buildId,jdbcType=BIGINT}
</delete>
<delete id="logicDeleteByCellId">
update ten_room_${cellId} set delete_flag = 1
update ten_room set delete_flag = 1
where cell_id = #{cellId,jdbcType=BIGINT}
</delete>
@ -295,16 +295,30 @@
<!--</select>-->
<select id="findPageAll" resultMap="BaseResultMap" >
SELECT alias.* from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select * from ten_room_${item}
</foreach>
) alias where delete_flag = 0
<!--SELECT alias.* from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select * from ten_room_${item}-->
<!--</foreach>-->
<!--) alias where delete_flag = 0-->
<!--<if test="params.buildId != null and params.buildId!=''">-->
<!--and alias.build_id = #{params.buildId}-->
<!--</if>-->
<!--<if test="params.layer != null and params.layer!=''">-->
<!--and alias.layer = #{params.layer}-->
<!--</if>-->
<!--<if test="params.roomName != null and params.roomName!=''">-->
<!--and room_name like CONCAT('%', '${params.roomName}', '%')-->
<!--</if>-->
<!--<if test="params.roomNumber != null and params.roomNumber!=''">-->
<!--and room_number = #{params.roomNumber}-->
<!--</if>-->
select * from ten_room where delete_flag = 0
<if test="params.buildId != null and params.buildId!=''">
and alias.build_id = #{params.buildId}
and build_id = #{params.buildId}
</if>
<if test="params.layer != null and params.layer!=''">
and alias.layer = #{params.layer}
and layer = #{params.layer}
</if>
<if test="params.roomName != null and params.roomName!=''">
and room_name like CONCAT('%', '${params.roomName}', '%')
@ -312,39 +326,60 @@
<if test="params.roomNumber != null and params.roomNumber!=''">
and room_number = #{params.roomNumber}
</if>
<if test="cellIds != null">
and cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
</select>
<select id="getAllCount" resultType="int" >
SELECT count(*) from (
<foreach collection="cellIds" item="item" index="index" separator="union all">
select room_id from ten_room_${item} where delete_flag = 0
<if test="params.type != null and params.type!=''">
and type = #{params.type}
</if>
<!--SELECT count(*) from (-->
<!--<foreach collection="cellIds" item="item" index="index" separator="union all">-->
<!--select room_id from ten_room_${item} where delete_flag = 0-->
<!--<if test="params.type != null and params.type!=''">-->
<!--and type = #{params.type}-->
<!--</if>-->
<!--</foreach>-->
<!--) alias-->
select count(*) from ten_room where 1 = 1
<if test="params.type != null and params.type!=''">
and type = #{params.type}
</if>
<if test="cellIds != null">
and cell_id in
<foreach item="cellId" collection="cellIds" open="(" separator="," close=")">
#{cellId}
</foreach>
</if>
</foreach>
) alias
</select>
<select id="queryByNumberAndLayer" resultMap="BaseResultMap">
select * from ten_room_${cellId} where delete_flag = 0
select * from ten_room where delete_flag = 0
and room_number = #{roomNumber} and layer = #{layer}
and build_id = #{buildId}
</select>
<select id="findByRoomName" resultMap="BaseResultMap">
select * from ten_room_${cellId} where delete_flag = 0
select * from ten_room where delete_flag = 0
and room_name = #{roomName}
and build_id = #{buildId}
</select>
<select id="getLayerRooms" resultType="net.shapelight.modules.ten.entity.TenRoomEntity">
select * from ten_room_${cellId} where delete_flag = 0
select * from ten_room where delete_flag = 0
and build_id = #{buildId} and layer = #{layer}
</select>
<select id="getRoomName" resultType="string">
select room_name from ten_room_${cellId}
select room_name from ten_room
where room_id = #{roomId,jdbcType=BIGINT}
</select>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,42 @@
package gb;
import net.coobird.thumbnailator.Thumbnails;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
public class ImageTest {
public static void main(String args[]){
try {
File picture = new File("d:\\temp\\101.png");
BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));
int w = sourceImg.getWidth();
int h = sourceImg.getHeight();
if (w > 1080 || h > 1080) {
Thumbnails.of("d:\\temp\\101.png")
.size(1080, 1080)
.toFile("d:\\temp\\33.png");
}
}catch (Exception e){
}
try {
File picture = new File("d:\\temp\\11.jpg");
BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));
int w = sourceImg.getWidth();
int h = sourceImg.getHeight();
if (w > 1080 || h > 1080) {
Thumbnails.of("d:\\temp\\11.jpg")
.size(1080, 1080)
.toFile("d:\\temp\\11.jpg");
}
}catch (Exception e){
}
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,167 @@
package net;
import gb.RandomValue;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MyTest {
/**
* 修改文件名
*
* @param oldFilePath 原文件路径
* @param newFileName 新文件名称
* @param overriding 判断标志(如果存在相同名的文件是否覆盖)
* @return
*/
public static boolean renameFile(String oldFilePath, String newFileName, boolean overriding) {
File oldfile = new File(oldFilePath);
if (!oldfile.exists()) {
return false;
}
String newFilepath = oldfile.getParent() + File.separator + newFileName;
File newFile = new File(newFilepath);
if (!newFile.exists()) {
return oldfile.renameTo(newFile);
} else {
if (overriding) {
newFile.delete();
return oldfile.renameTo(newFile);
} else {
return false;
}
}
}
public static boolean renameFile(File oldFile, String newFileName, boolean overriding) {
String newFilepath = oldFile.getParent() + File.separator + newFileName;
File newFile = new File(newFilepath);
if (!newFile.exists()) {
return oldFile.renameTo(newFile);
} else {
if (overriding) {
newFile.delete();
return oldFile.renameTo(newFile);
} else {
return false;
}
}
}
public static void main(String args[]) {
//----------------------------- 重命名文件开始 --------------------------------------//
// String baseDir = "D:\\facestore\\cface\\f10_2000";
// File faceDir = new File(baseDir);
// File[] iamges = faceDir.listFiles();
// for(File file: iamges){
// String id = RandomValue.getIdNo(true);
// renameFile(file,id+".jpg",true);
// }
//----------------------------- 重命名文件结束 --------------------------------------//
//----------------------------- 随机生成姓名性别手机号 --------------------------------------//
// String baseDir = "D:\\facestore\\cface\\f10_2000";
// String idFile = "D:\\facestore\\cface\\f1_100\\id.txt";
String baseDir = "D:\\facestore\\2020博士统考照片";
String idFile = baseDir+"\\id.txt";
File faceDir = new File(baseDir);
File[] iamges = faceDir.listFiles();
File outFile = new File(idFile);
if (!outFile.exists()) {
try {
outFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
StringBuffer idBuffer = new StringBuffer();
for (File file : iamges) {
String fileName = file.getName();
String id = fileName.substring(0, fileName.lastIndexOf("."));
//1.姓名
idBuffer.append(RandomValue.getChineseName()+"\t");
//2.性别
String sex=Math.random()>0.5?"":"";
idBuffer.append(sex+"\t");
//3.手机号
idBuffer.append(RandomValue.getTel()+"\t");
//4.身份证号
idBuffer.append(id);
idBuffer.append("\r\n");
System.out.println(idBuffer.toString());
}
FileWriter outWriter = null;
try {
outWriter = new FileWriter(idFile, true);
outWriter.write(idBuffer.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outWriter.flush();
outWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//----------------------------- 随机生成姓名性别手机号 结束 --------------------------------------//
// String n = String.format("%02d%s",Integer.parseInt("4"),"1002室");
// System.out.println(n);
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// Calendar cal = Calendar.getInstance();
// //设置一个星期的第一天按中国的习惯一个星期的第一天是星期一
// cal.setFirstDayOfWeek(Calendar.MONDAY);
// //获得当前日期是一个星期的第几天
// int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
// if(dayWeek==1){
// dayWeek = 8;
// }
//
// // 根据日历的规则给当前日期减去星期几与一个星期第一天的差值
// cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);
// Date mondayDate = cal.getTime();
// String weekBegin = sdf.format(mondayDate);
// System.out.println("所在周星期一的日期:" + weekBegin);
//
//
// cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
// Date sundayDate = cal.getTime();
// String weekEnd = sdf.format(sundayDate);
// System.out.println("所在周星期日的日期:" + weekEnd);
//
//
//
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(new Date());
// calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
// System.out.println("所在周星期日的日期:" + sdf.format(calendar.getTime()));
//
//
// Calendar calendar2 = Calendar.getInstance();
// calendar2.setTime(new Date());
// calendar2.set(Calendar.DAY_OF_MONTH, calendar2.getActualMaximum(Calendar.DAY_OF_MONTH));
// System.out.println("所在周星期日的日期:" + sdf.format(calendar2.getTime()));
}
}

View File

@ -0,0 +1,34 @@
package net;
import net.shapelight.modules.ten.entity.TenRecordEntity;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProcessImages {
@Test
public void test() {
// String baseDir = "D:\\facestore\\site\\member_org";
String baseDir = "D:\\facestore\\test";
File faceDir = new File(baseDir);
File[] iamges = faceDir.listFiles();
for(File file: iamges){
String fileName = file.getName();
String id = fileName.substring(fileName.lastIndexOf("\\"),fileName.lastIndexOf("."));
}
}
}

View File

@ -0,0 +1,68 @@
package net.shapelight;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class BasicTest {
public static void main(String args[]) {
String host = "192.168.1.111";
int port = 8081;
String URI = "/api/v4/clients";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 设置BasicAuth
CredentialsProvider provider = new BasicCredentialsProvider();
// Create the authentication scope
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// Create credential pair在此处填写用户名和密码
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("11f6a78ee6922", "MjkzODM4Mzc2NTMyNjIzOTg3NTI5MDMwMzU3NjMwOTc2MDA");
// Inject the credentials
provider.setCredentials(scope, credentials);
// Set the default credentials provider
httpClientBuilder.setDefaultCredentialsProvider(provider);
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
String result = "";
HttpGet httpGet = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
httpGet = new HttpGet("http://"+host+":"+port+URI);
try {
httpResponse = closeableHttpClient.execute(httpGet);
entity = httpResponse.getEntity();
if( entity != null ){
result = EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 关闭连接
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
//
System.out.println(result);
}
}

View File

@ -0,0 +1,30 @@
package net.shapelight;
import net.shapelight.common.utils.RedisUtils;
import net.shapelight.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
private RedisUtils redisUtils;
@Test
public void contextLoads() {
SysUserEntity user = new SysUserEntity();
user.setEmail("123456@qq.com");
redisUtils.set("user", user);
SysUserEntity ss = (SysUserEntity) redisUtils.get("user");
System.out.println(ss.getEmail());
// System.out.println(ToStringBuilder.reflectionToString(redisUtils.get("user", SysUserEntity.class)));
}
}

View File

@ -0,0 +1,123 @@
package net.shapelight;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import java.nio.file.Paths;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SwaggerTo {
/**
* 生成AsciiDocs格式文档
* @throws Exception
*/
@Test
public void generateAsciiDocs() throws Exception {
// 输出Ascii格式
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8018/cell/v2/api-docs"))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/asciidoc/generated"));
}
/**
* 生成Markdown格式文档
* @throws Exception
*/
@Test
public void generateMarkdownDocs() throws Exception {
// 输出Markdown格式
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.MARKDOWN)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8018/cell/v2/api-docs"))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/markdown/generated"));
}
// /**
// * 生成Confluence格式文档
// * @throws Exception
// */
// @Test
// public void generateConfluenceDocs() throws Exception {
// // 输出Confluence使用的格式
// Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
// .withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)
// .withOutputLanguage(Language.ZH)
// .withPathsGroupedBy(GroupBy.TAGS)
// .withGeneratedExamples()
// .withoutInlineSchema()
// .build();
//
// Swagger2MarkupConverter.from(new URL("http://localhost:8016/v2/api-docs"))
// .withConfig(config)
// .build()
// .toFolder(Paths.get("./docs/confluence/generated"));
// }
/**
* 生成AsciiDocs格式文档,并汇总成一个文件
* @throws Exception
*/
@Test
public void generateAsciiDocsToFile() throws Exception {
// 输出Ascii到单文件
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8018/cell/v2/api-docs"))
.withConfig(config)
.build()
.toFile(Paths.get("./docs/asciidoc/generated/all"));
}
/**
* 生成Markdown格式文档,并汇总成一个文件
* @throws Exception
*/
@Test
public void generateMarkdownDocsToFile() throws Exception {
// 输出Markdown到单文件
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.MARKDOWN)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8018/cell/v2/api-docs"))
.withConfig(config)
.build()
.toFile(Paths.get("./docs/markdown/generated/all"));
}
}