MyScheduledTask.java 13.4 KB
package com.example.dahua.async;

import com.example.dahua.MyTask;
import com.example.dahua.bean.SendRecordBean;
import com.example.dahua.bean.StudentBean;
import com.example.dahua.bean.UserInfoBean;
import com.example.dahua.bean.WGBean;
import com.example.dahua.dao.UserDao;
import com.example.dahua.lib.Utils;
import com.example.dahua.mqtt.MqttManager;
import com.example.dahua.service.UserOperateService;
import com.example.dahua.utils.DateFormatUtil;
import com.example.dahua.utils.DateUtils;
import com.example.dahua.utils.FileUtils;
import com.example.dahua.xiananDao.SearchMapper;
import com.example.dahua.xiananDao.SendRecordDao;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Component
public class MyScheduledTask {


    @Autowired
    SendRecordDao sendRecordDao;

    @Autowired
    UserDao userDao;

    @Autowired
    SendUserInfoTask sendUserInfoTask;

    @Autowired
    MyTask myTasks;

//    @Value("${haikangpic}")
//    private String haikangpic;

    public static boolean isSendHaikang = false;

    public static boolean isSendWeigeng = false;

    public static boolean isSendDahua = false;

    private boolean isClose = true, isCloseYT = true;//判断是否关机

    private String deleteDate = "";//删除一周前的图片用的

    private String imgFilPath = "C:\\EhomePicServer";//抓拍图片路径

    @Scheduled(fixedRate = 5000)
    private void deleteFace() throws InterruptedException {
        //删除抓拍人脸
        deleteFaceImg();

//        /**
//         * 目前分三个时间段(9:00-10:00) (13:00-14:00)(22:00-5:00)进行补发操作
//         */
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH");
//        int hour = Integer.parseInt(simpleDateFormat.format(new Date()));
//
//       if (hour >= 9 && hour < 11) {
//            dealData();
//        } else if (hour >= 13 && hour < 14) {
//            dealData();
//        } else if (hour >= 20 || hour < 5) {
//            dealData();
//        }

    }

    /**
     * 订阅任务 20秒执行一次
     */
    @Scheduled(fixedDelay= 10000)
    protected synchronized void reloadPic2(){
        //登录
        if (myTasks.isHasNewDevice) {
            myTasks.login();
        }
        if (myTasks.isFirstAutoRegister) {
            myTasks.DisLogin();
        }
    }

    @Autowired
    private UserOperateService userOperateService;
    @Autowired
    private SearchMapper searchMapper;
//    /**
//     * 订阅任务 20秒执行一次
//     */
//    @Scheduled(cron = "0 51 18 * * ?")
//    protected synchronized void task(){
//        log.info("开始执行----- 晚上到寝");
//        //男
//        Integer schoolId=27;
//        Integer roomId =12226;
//        Integer type = 7;
//        Integer outof = 1;
//        String clintId="253169192";
//        String timeIds = "2021-01-08,2021-01-11,2021-01-12,2021-01-13,2021-01-14,2021-01-15,2021-01-18,2021-01-19,2021-01-20,2021-01-21,2021-01-22";
//        String[] deviceArr = timeIds.split(",");
//        List<String> deviceList= new ArrayList<>(Arrays.asList(deviceArr));
//        //启用多线程执行
//        CountDownLatch begin = new CountDownLatch(1);
//        CountDownLatch end = new CountDownLatch(deviceList.size());
//        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-sendFace-runner-%d").build();
//        ExecutorService exe = new ThreadPoolExecutor(4,8,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),namedThreadFactory);
//        for(String s : deviceList){
//            String intime = s + " 20:26:14";
//            String startTime= s + " 00:00:00";
//            String endTime = s+" 23:59:59";
//            exe.execute(new SendFaceBatchTask100(userDao,sendRecordDao,searchMapper,schoolId,roomId,type,outof,intime,clintId,startTime,endTime,begin,end));
//        }
//        begin.countDown();
//        try {
//            end.await();
//        }catch (Exception e){
//            log.error("失败"+e);
//        }
//        exe.shutdown();
//        log.info("统计100服务器总共有"+deviceList.size()+"个设备,处理完毕");
//    }
//
//    //    @Scheduled(cron = "0 50 15 * * ?")
//    @Scheduled(cron = "0 09 21 * * ?")
//    protected synchronized void task2(){
//        log.info("开始执行----- 晚上到寝");
//        //男
//        Integer schoolId=27;
//        Integer roomId =12226;
//        Integer type = 4;
//        Integer outof = 1;
//        String clintId="253169212";
//        String timeIds = "2021-01-08,2021-01-11,2021-01-12,2021-01-13,2021-01-14,2021-01-15,2021-01-18,2021-01-19,2021-01-20,2021-01-21,2021-01-22";
//        String[] deviceArr = timeIds.split(",");
//        List<String> deviceList= new ArrayList<>(Arrays.asList(deviceArr));
//        //启用多线程执行
//        CountDownLatch begin = new CountDownLatch(1);
//        CountDownLatch end = new CountDownLatch(deviceList.size());
//        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-sendFace-runner-%d").build();
//        ExecutorService exe = new ThreadPoolExecutor(8,16,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),namedThreadFactory);
//        for(String s : deviceList){
////            String intime = s + " 06:03:39";
////            String startTime= s + " 00:00:00";
////            String endTime = s+" 23:59:59";
//            String intime = s + " 17:14:39";
//            String startTime= s + " 00:00:00";
//            String endTime = s+" 23:59:59";
//            exe.execute(new SendFaceBatchTask2(userDao,sendRecordDao,searchMapper,schoolId,roomId,type,outof,intime,clintId,startTime,endTime,begin,end));
//        }
//        begin.countDown();
//        try {
//            end.await();
//        }catch (Exception e){
//            log.error("失败"+e);
//        }
//        exe.shutdown();
//        log.info("统计100服务器总共有"+deviceList.size()+"个设备,处理完毕");
//    }

    /**
     * 定期删除人脸抓拍图片
     */
    private void deleteFaceImg() {

        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        System.out.println("deleteDate:" + deleteDate);
        if (!deleteDate.equals(date)) {
            deleteDate = date;
            File file = new File(imgFilPath);
            File[] files = file.listFiles();
            Date currentDate = new Date();
            if (null != files)
                for (int i = 0; i < files.length; i++) {
                    File imgFile = files[i];
                    String name = imgFile.getName().split("\\.")[0];
                    String time = name.substring(32);
                    if (time.length() > 8 && !time.contains("-")) time = time.substring(0, 8);

                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
                    try {
                        Date date1 = null;
                        if (time.contains("-")) date1 = simpleDateFormat.parse(time);
                        else date1 = simpleDateFormat1.parse(time);

                        long timecj = currentDate.getTime() - date1.getTime();
                        if (timecj > (7 * 24 * 60 * 60 * 1000)) {//大于七天的删除
                            System.out.println("imgFile:" + imgFile.getAbsolutePath() + imgFile.exists());
                            imgFile.delete();
                        }

                    } catch (ParseException e) {
                        imgFile.delete();
//                    e.printStackTrace();
                    }

                }

        }

    }

    private synchronized void dealData() {

        String ip = new Utils().getHostAddress();
        System.out.println("ip:" + ip);
        if (ip.startsWith("192") || ip.contains("172.16.247.64"))
            return;

        /**
         * 微耕
         */
//System.out.println("isSendWeigeng:"+isSendWeigeng+"isSendHaikang:"+isSendHaikang+"isSendDahua:"+isSendDahua);
        if (!isSendWeigeng) {
            isSendWeigeng = true;
            sendUserInfoTask.addWeiGen();
        }

        /**
         * 海康
         */
        if (!isSendHaikang) {
            isSendHaikang = true;
            sendUserInfoTask.addHaikangface();
        }

        /**
         * 大华人脸
         */
        if (!isSendDahua) {
            isSendDahua = true;
            sendUserInfoTask.addDahuaFace();
        }

    }

    boolean isSendMQ = false;

    boolean isInitMQ = false;

    int readLineNum = -1;

    Map<String, Integer> readLineMap = new HashMap<>();

    MqttManager mqttManager = new MqttManager();


    @Scheduled(fixedRate = 1000)
    public void sendMq() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");

        if (!isInitMQ) initMQ();
        if (!isSendMQ) {
            isSendMQ = true;
            String fileName = simpleDateFormat.format(new Date());
            String filePath = "D:\\wg_log\\info\\kaoInfo\\" + fileName + ".log";
            if (!readLineMap.containsKey(fileName)) readLineNum = -1;//更新文件后从头开始
            File file = new File(filePath);
            try {
                if (!file.exists()) {
                    return;
                }
                FileInputStream fileInputStream = new FileInputStream(file);
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream, "GB2312"));

                String content = null;

                int indexLineNum = 0;//当前文件的行
                while ((content = bufferedReader.readLine()) != null) {
                    indexLineNum++;
                    if (indexLineNum >= readLineNum) {
                        readLineNum++;
                        sendMQMess(content);
                    }
                }
                readLineMap.put(fileName, readLineNum);
                fileInputStream.close();
                bufferedReader.close();

            } catch (FileNotFoundException e) {
                System.out.println("文件不存在:" + e.toString());
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("IO异常:" + e.toString());
                e.printStackTrace();
            }
        } else {
            isSendMQ = false;
        }


    }

    private void initMQ() {

        if (null != mqttManager) mqttManager.init();
        isInitMQ = true;

    }
    
    public void sendMQMess(String content) {
        String cardNum = content.substring(content.indexOf("卡号") + 3, content.indexOf("卡号") + 11);

        String inOrOut = content.substring(content.indexOf("方向:") + 3, content.indexOf("方向:") + 5).endsWith("进门") ? "0" : "1";

        String qiandaoDevId = content.substring(content.indexOf("设备") + 3, content.indexOf("设备") + 12);

        String schoolId = userDao.getSchoolIdWidthCardNum(cardNum);
        if(StringUtils.isEmpty(schoolId)){
            log.info("此卡号未对应所属学校,考勤卡号:{}",cardNum);
            return;
        }
        //获取寝室关联的场景id
        String placeId = userDao.getPlaceIdWithKaoqinDevid(qiandaoDevId);
        //关联的显示看板设备
        List<String> kanbanIds = new ArrayList<>();
        if(!StringUtils.isEmpty(placeId)) {
            log.info("关联场景ID: {},考勤设备ID:{}",placeId,qiandaoDevId);
            kanbanIds = userDao.getKanBanIdWithPlaceId(placeId);
        }else{
            List<String> kBIds = userDao.getClintIds(schoolId);
            if(CollectionUtils.isNotEmpty(kBIds)){
                for(String kbId : kBIds){
                    String roomId = userDao.getPlaceIdWithKanBanDevid(kbId);
                    if(StringUtils.isEmpty(roomId)){
                        kanbanIds.add(kbId);
                    }
                }
            }
        }
        if(CollectionUtils.isNotEmpty(kanbanIds)){
            for (int i = 0; i < kanbanIds.size(); i++) {
                String clintId = kanbanIds.get(i);
                String data = "{\"cmd\":\"" + 34 + "\",\"clientId\":\"" + clintId + "\",\"data\":{\"cardNum\":\"" + cardNum + "\",\"inOrOut\":\"" + inOrOut + "\"}}";
                mqttManager.sendMqQD(clintId, data);
                log.info("发送微耕考勤消息:学校ID: {},设备ID: {},关联看板room: {},",schoolId,clintId,placeId);
            }
        }
    }
}