对接海康超脑

public abstract class HKBaseCallback extends FMSGCallBack {
    public static HCNetSDK hCNetSDK = null;
    public HCNetSDK.NET_DVR_USER_LOGIN_INFO m_strLoginInfo = null;
    public HCNetSDK.NET_DVR_DEVICEINFO_V40 m_strDeviceInfo = null;

//    private static String host = PropertiesUtils.getProperty("addHKSDK");
//    static HCNetSDK hCNetSDK = "true".equals(host)?HCNetSDK.INSTANCE:null;
//    HCNetSDK.NET_DVR_USER_LOGIN_INFO m_strLoginInfo ="true".equals(host)?new HCNetSDK.NET_DVR_USER_LOGIN_INFO():null;//设备登录信息
//    HCNetSDK.NET_DVR_DEVICEINFO_V40 m_strDeviceInfo ="true".equals(host)?new HCNetSDK.NET_DVR_DEVICEINFO_V40():null;//设备信息

    String m_sDeviceIP;//已登录设备的IP地址
    String m_sUsername;//设备用户名
    String m_sPassword;//设备密码
    public String m_FDID; // 人脸库ID
    public int m_lUploadHandle;
    public int m_UploadStatus;
    public String m_picID;
    int lUserID;//用户句柄
    Map<Integer,Object> userMap = new HashMap<>();
    public static Map<String,Integer> userIDMap = new HashMap<>();
    public static Map<String,Map<String,Object>> deviceMap= new HashMap<>();
    int lAlarmHandle;//报警布防句柄
    int lListenHandle;//报警监听句柄
    public boolean m_isSupportFDLib; // 是否支持人脸功能
    HCNetSDK.FMSGCallBack fMSFCallBack;//报警回调函数实现
    HCNetSDK.FMSGCallBack_V31 fMSFCallBack_V31;//报警回调函数实现
    int numberLimit;//人数限制
    protected static BaseApi baseApi = new BaseApiImpl();

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    protected abstract HKBaseCallback getInstance();

    public void statDll(HKBaseCallback instance) {
        if (getAddHKSDK()) {
            boolean b = baseApi.initialize();
            boolean c = baseApi.callBackInitialize(instance);
            if (b && c) {
                logger.info("初始化成功");
                //获取海康设备列表
                List<Map<String,Object>> deviceList = getHkConfigure();
                if(deviceList.size()>0){
                    deviceList.stream().forEach(item ->{
                        //登录
                        int lUserID = jButtonLoginActionPerformed(item);
                        deviceMap.put(item.get("host").toString(),item);
                        userIDMap.put(item.get("host").toString(),lUserID);
                    });
                    for (Map.Entry<Integer,Object> entry : userMap.entrySet()){
                        //查询是否支持人脸库
                        if (baseApi.getFaceCapabilities(entry.getKey())) {
                            m_isSupportFDLib = true;
//                            //删除原有人脸库
                            String m_fdid = jedisTemplate.get("m_FDID");
//                            String m_fdid = redisOper("m_FDID",null,"1");
//                            if (StringUtils.isNotBlank(m_fdid)) {
//                                DeleteFDLib(m_fdid,entry.getKey());
//                            }
//                            CreateFDLib("人脸库",entry.getKey());
                            // todo 判断有无人脸库
                        } else {
                            m_isSupportFDLib = false;
                        }
                        baseApi.setAlarmChan(entry.getKey());
                        SetupAlarmChan(entry.getKey());
                    }
                    //监听报警
//                StartAlarmListen();
                }
                //获取格林token
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("userName",dllConfig.username);
//                jsonObject.put("password",dllConfig.password);
//                String result = HttpUtils.sendJsonHttpPost("http://" + dllConfig.host + "/api/login", jsonObject.toJSONString());
//                if(StringUtils.isNotBlank(result) && !"false".equals(result)){
//                    JSONObject resultJson = JSON.parseObject(result);
//                    JSONObject data = resultJson.getJSONObject("data");
//                    String token = data.getString("token");
//                    if(StringUtils.isNotBlank(token)){
//                        jedisTemplate.set("gl_token",token);
//                    }
//                }
//                //获取金税token
//                lockerUtils.getHeader();
//                //修改格林设备http请求ip
//                try {
//                    InetAddress addr = InetAddress.getLocalHost();
//                    Map<String,Object> map = new HashMap<>();
//                    map.put("enabled",true);
//                    map.put("server","http://"+addr.getHostAddress()+":8060/base-app/api");
//                    map.put("userName","haomuL");
//                    map.put("password","abc@Dgsh");
//                    map.put("isDefault",false);
//                    HttpUtils.doPut("http://" + dllConfig.host + "/api/system/config/eventupload",jedisTemplate.get("gl_token"),JSONObject.toJSONString(map));
//                } catch (UnknownHostException e) {
//                    e.printStackTrace();
//                }
            } else {
                logger.info("初始化失败");
            }
        } else {
            logger.info("配置未加载海康网络摄像头");
        }
    }



    public abstract boolean getAddHKSDK();

    public abstract List<Map<String, Object>> getHkConfigure();

    public abstract void getAlarmer(HCNetSDK.NET_DVR_ALARMER pAlarmer, String deviceNumber, String alarm_type, String alarm_pic_path,int alarmNumber);

    public abstract Response<ParamsModel> getParamsInfoByKindAndName();

    public abstract Response<List<ParamsModel>> findParamsListByKind();

    public abstract BulletEqpDeviceModel getDeptByDeviceId(Map<String, Object> device);

    public abstract void creatDevice(Map<String, Object> device,HCNetSDK.NET_DVR_CID_ALARM strCIDAlarm,HCNetSDK.NET_DVR_ALARMER pAlarmer);

    public abstract String redisOper(String str,String strNew,String state);//state为1是get,0是set

    public abstract boolean populationDensityAlarm(PopulationDensityAlarmResp resp);//区域人数统计 1.单人入库
    public void SetupAlarmChan(int userId) {
        /*if (lUserID == -1) {
            logger.info("请先注册");
            return;
        }*/
        if (fMSFCallBack_V31 == null) {
            fMSFCallBack_V31 = new FMSGCallBack_V31();
            Pointer pUser = null;
            if (!hCNetSDK.NET_DVR_SetDVRMessageCallBack_V31(fMSFCallBack_V31, pUser)) {
                logger.info("设置回调函数失败!");
            }
        }
        NET_DVR_SETUPALARM_PARAM m_strAlarmInfo = new NET_DVR_SETUPALARM_PARAM();
        m_strAlarmInfo.dwSize = m_strAlarmInfo.size();
        m_strAlarmInfo.byLevel = 1;//智能交通布防优先级:0- 一等级(高),1- 二等级(中),2- 三等级(低)
        m_strAlarmInfo.byAlarmInfoType = 1;//智能交通报警信息上传类型:0- 老报警信息(NET_DVR_PLATE_RESULT),1- 新报警信息(NET_ITS_PLATE_RESULT)
        m_strAlarmInfo.byDeployType = 1; //布防类型(仅针对门禁主机、人证设备):0-客户端布防(会断网续传),1-实时布防(只上传实时数据)
        m_strAlarmInfo.write();
        lAlarmHandle = hCNetSDK.NET_DVR_SetupAlarmChan_V41(userId, m_strAlarmInfo);
        if (lAlarmHandle == -1) {
            logger.info("布防失败,错误号:" + hCNetSDK.NET_DVR_GetLastError());
        } else {
            logger.info("布防成功");
        }
    }


    public int jButtonLoginActionPerformed(Map<String,Object> params) {

        //注册之前先注销已注册的用户,预览情况下不可注销
       /* if (lUserID > -1) {
            //先注销
            hCNetSDK.NET_DVR_Logout(lUserID);
            lUserID = -1;
        }*/

        //注册
        m_sDeviceIP = params.get("host").toString();//设备ip地址
        m_strLoginInfo.sDeviceAddress = new byte[HCNetSDK.NET_DVR_DEV_ADDRESS_MAX_LEN];
        System.arraycopy(m_sDeviceIP.getBytes(), 0, m_strLoginInfo.sDeviceAddress, 0, m_sDeviceIP.length());

        m_sUsername = params.get("user_name").toString();//设备用户名
        m_strLoginInfo.sUserName = new byte[HCNetSDK.NET_DVR_LOGIN_USERNAME_MAX_LEN];
        System.arraycopy(m_sUsername.getBytes(), 0, m_strLoginInfo.sUserName, 0, m_sUsername.length());

        m_sPassword = params.get("password").toString();//设备密码
        m_strLoginInfo.sPassword = new byte[HCNetSDK.NET_DVR_LOGIN_PASSWD_MAX_LEN];
        System.arraycopy(m_sPassword.getBytes(), 0, m_strLoginInfo.sPassword, 0, m_sPassword.length());

        m_strLoginInfo.wPort = 8000;

        m_strLoginInfo.bUseAsynLogin = false; //是否异步登录:0- 否,1- 是

        m_strLoginInfo.write();

        LoginParam loginParam = new LoginParam();
        loginParam.setUsername(m_sUsername);
        loginParam.setPassword(m_sPassword);
        loginParam.setHost(m_sDeviceIP);
        loginParam.setPort(m_strLoginInfo.wPort);

//        int lUserID = hCNetSDK.NET_DVR_Login_V40(m_strLoginInfo, m_strDeviceInfo);
        int lUserID = baseApi.deviceRegister(loginParam);
        if (lUserID == -1) {
            logger.info("注册失败,错误号:" + hCNetSDK.NET_DVR_GetLastError());
        } else {
            logger.info("注册成功,用户ID为:"+lUserID);
            userMap.put(lUserID,String.valueOf(lUserID));
        }
        return lUserID;
    }

    public class FMSGCallBack_V31 implements HCNetSDK.FMSGCallBack_V31 {
        //报警信息回调函数

        @Override
        public boolean invoke(int lCommand, HCNetSDK.NET_DVR_ALARMER pAlarmer, Pointer pAlarmInfo, int dwBufLen, Pointer pUser) {
            AlarmDataHandle(lCommand, pAlarmer, pAlarmInfo, dwBufLen, pUser);
            return true;
        }
    }

    public void AlarmDataHandle(int lCommand, HCNetSDK.NET_DVR_ALARMER pAlarmer, Pointer pAlarmInfo, int dwBufLen, Pointer pUser) {
        String sAlarmType = new String();
        String[] newRow = new String[3];
        Map<String, Object> device = deviceMap.get(b2s(pAlarmer.sDeviceIP));
        System.out.println("报警的设备"+device);//1.单人入库-报警设备ip
        //报警时间
        Date today = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String[] sIP = new String[2];
        sAlarmType = new String("0x") + Integer.toHexString(lCommand);
        //lCommand是传的报警类型
        switch (lCommand) {
            //3.单人入库报警-开始
            case HCNetSDK.COMM_ISAPI_ALARM: //ISAPI协议报警信息
                System.out.println(new String(pAlarmer.byMacAddr).split("\0",2)[0]);
                System.out.println(new String(pAlarmer.sDeviceIP).split("\0",2)[0]);
                HCNetSDK.NET_DVR_ALARM_ISAPI_INFO struEventISAPI = new HCNetSDK.NET_DVR_ALARM_ISAPI_INFO();
                struEventISAPI.write();
                Pointer pEventISAPI = struEventISAPI.getPointer();
                pEventISAPI.write(0, pAlarmInfo.getByteArray(0, struEventISAPI.size()), 0, struEventISAPI.size());
                struEventISAPI.read();
                logger.info("----------------------他还在执行");
                ByteBuffer jsonbuffers = struEventISAPI.pAlarmData.getByteBuffer(0, struEventISAPI.dwAlarmDataLen);
                byte [] jsonbytes = new byte[struEventISAPI.dwAlarmDataLen];
                jsonbuffers.rewind();
                jsonbuffers.get(jsonbytes);
                String body = JSONArray.toJSONString(jsonbytes); // 先转换成Json String
                byte[] json = JSONObject.parseObject(body, byte[].class);//转json byte
                String convent = new String(json); // byte数组转换成String
                PopulationDensityAlarmResp jsonObject = JSON.parseObject(convent,PopulationDensityAlarmResp.class);
                logger.info("----------------------第二次还在执行他还在执行");
                List<PopulationDensityAlarmResp.PicData> list = new ArrayList<>();
                for(int i=0;i<struEventISAPI.byPicturesNumber;i++) {
                    com.beitai.device.sdk.HCNetSDK.NET_DVR_ALARM_ISAPI_PICDATA struPicData = new com.beitai.device.sdk.HCNetSDK.NET_DVR_ALARM_ISAPI_PICDATA();
                    struPicData.write();
                    Pointer pPicData = struPicData.getPointer();
                    pPicData.write(0, struEventISAPI.pPicPackData.getByteArray((long) i *struPicData.size(), struPicData.size()), 0, struPicData.size());
                    struPicData.read();

                    ByteBuffer buffers = struPicData.pPicData.getByteBuffer(0, struPicData.dwPicLen);
                    byte [] bytes = new byte[struPicData.dwPicLen];
                    buffers.rewind();
                    buffers.get(bytes);
                    PopulationDensityAlarmResp.PicData picData = new PopulationDensityAlarmResp.PicData();
                    picData.setPic(bytes);
                    list.add(picData);
                }
                logger.info("----------------------第三次还在执行他还在执行,要进行保存了");

                jsonObject.setToday(jsonObject.getDateTime());
                jsonObject.setAlarmType(AlarmTypeEnum.COMM_POPULATION_ALARM);
                jsonObject.setPicDataList(list);
                populationDensityAlarm(jsonObject);
                break;//结束3.单人入库报警-结束
/*
            case HCNetSDK.COMM_VCA_ALARM:
                byte[] byteArray = pAlarmInfo.getByteArray(0, Integer.MAX_VALUE);
                String s = b2s(byteArray);
                String framesPeopleCounting_number = s.substring(s.indexOf("framesPeopleCounting_number"));
                String[] split = framesPeopleCounting_number.split(",");
                String s1 = split[0];
                String[] split1 = s1.split(":");
                int num = Integer.parseInt(split1[1].trim());
                logger.info("智能检测通用报警{人员数量:"+split1[1]+"}");
                break;

            case HCNetSDK.COMM_ALARM_PDC:
                logger.info("客流量统计报警上传");
                HCNetSDK.NET_DVR_PDC_ALRAM_INFO strPDCResult = new HCNetSDK.NET_DVR_PDC_ALRAM_INFO();
                strPDCResult.write();
                Pointer pPDCInfo = strPDCResult.getPointer();
                pPDCInfo.write(0, pAlarmInfo.getByteArray(0, strPDCResult.size()), 0, strPDCResult.size());
                strPDCResult.read();
                if (strPDCResult.byMode == 0) {
                    strPDCResult.uStatModeParam.setType(HCNetSDK.NET_DVR_STATFRAME.class);
                    sAlarmType = sAlarmType + ":客流量统计,进入人数:" + strPDCResult.dwEnterNum + ",离开人数:" + strPDCResult.dwLeaveNum +
                            ", byMode:" + strPDCResult.byMode + ", dwRelativeTime:" + strPDCResult.uStatModeParam.struStatFrame.dwRelativeTime +
                            ", dwAbsTime:" + strPDCResult.uStatModeParam.struStatFrame.dwAbsTime;
                }
                if (strPDCResult.byMode == 1) {
                    strPDCResult.uStatModeParam.setType(HCNetSDK.NET_DVR_STATTIME.class);
                    String strtmStart = "" + String.format("%04d", strPDCResult.uStatModeParam.struStatTime.tmStart.dwYear) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmStart.dwMonth) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmStart.dwDay) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmStart.dwHour) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmStart.dwMinute) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmStart.dwSecond);
                    String strtmEnd = "" + String.format("%04d", strPDCResult.uStatModeParam.struStatTime.tmEnd.dwYear) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmEnd.dwMonth) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmEnd.dwDay) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmEnd.dwHour) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmEnd.dwMinute) +
                            String.format("%02d", strPDCResult.uStatModeParam.struStatTime.tmEnd.dwSecond);
                    sAlarmType = sAlarmType + ":客流量统计,进入人数:" + strPDCResult.dwEnterNum + ",离开人数:" + strPDCResult.dwLeaveNum +
                            ", byMode:" + strPDCResult.byMode + ", tmStart:" + strtmStart + ",tmEnd :" + strtmEnd;
                }

                newRow[0] = dateFormat.format(today);
                //报警类型
                newRow[1] = sAlarmType;
                //报警设备IP地址
                sIP = new String(strPDCResult.struDevInfo.struDevIP.sIpV4).split("\0", 2);
                newRow[2] = sIP[0];
                //生成设备
                if(strPDCResult.byMode == 1){
                    //人员限制查询
                    Response<ParamsModel> response=getParamsInfoByKindAndName();
                    numberLimit = Integer.parseInt(response.getData().getValue());
                    if(strPDCResult.dwEnterNum > numberLimit){
                        String deviceNumber = device.get("device_number").toString();
                        getAlarmer(pAlarmer, deviceNumber, "210", null,0);
                    }
                }
                logger.info(sAlarmType);
                break;
            case HCNetSDK.COMM_UPLOAD_FACESNAP_RESULT://人脸识别结果信息
                //实时人脸抓拍上传
                HCNetSDK.NET_VCA_FACESNAP_RESULT strFaceSnapInfo = new HCNetSDK.NET_VCA_FACESNAP_RESULT();
                strFaceSnapInfo.write();
                Pointer pFaceSnapInfo = strFaceSnapInfo.getPointer();
                pFaceSnapInfo.write(0, pAlarmInfo.getByteArray(0, strFaceSnapInfo.size()), 0, strFaceSnapInfo.size());
                strFaceSnapInfo.read();
                sAlarmType = sAlarmType + ":人脸抓拍上传,人脸评分:" + strFaceSnapInfo.dwFaceScore + ",年龄段:" + strFaceSnapInfo.struFeature.byAgeGroup + ",性别:" + strFaceSnapInfo.struFeature.bySex;
                logger.info(sAlarmType);
                newRow[0] = dateFormat.format(today);
                //报警类型
                newRow[1] = sAlarmType;
                //报警设备IP地址
                sIP = new String(strFaceSnapInfo.struDevInfo.struDevIP.sIpV4).split("\0", 2);
                newRow[2] = sIP[0];
                String basePicPath = "C:/sykean/file-app";
                //人脸图片写文件
                if (strFaceSnapInfo.dwFacePicLen > 0) {
                    String fn_image = null;
                    Response<List<ParamsModel>> fileUrl = findParamsListByKind();
                    try {
                        fn_image = FileUtil.fileUpload(strFaceSnapInfo.pBuffer1.getByteArray(0, strFaceSnapInfo.dwFacePicLen),
                                fileUrl.getData().get(0).getValue(), "face");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    logger.info("人脸抓拍图片地址-------------------------------" + fn_image);
                    BulletEqpDeviceModel data1 = getDeptByDeviceId(device);
                    if(data1!=null){
                        boolean userStatus = false;
                        boolean dutyStatus = false;
                        //非本单位人员报警
//                        deptAlarm(pAlarmer, device, basePicPath, fn_image, data1, userStatus);
                        //非值班人员报警  根据组织机构ID+当前时间查询当前值班人
//                        dutyAlarm(pAlarmer, device, basePicPath, fn_image, data1, dutyStatus);
                    }
                }
                break;*/
            case HCNetSDK.COMM_SNAP_MATCH_ALARM:
                //人脸黑名单比对报警
                HCNetSDK.NET_VCA_FACESNAP_MATCH_ALARM strFaceSnapMatch = new HCNetSDK.NET_VCA_FACESNAP_MATCH_ALARM();
                String SnapPicUrl="";
                byte[] buffer = new byte[4096];
                strFaceSnapMatch.write();
                Pointer pFaceSnapMatch = strFaceSnapMatch.getPointer();
                pFaceSnapMatch.write(0, pAlarmInfo.getByteArray(0, strFaceSnapMatch.size()), 0, strFaceSnapMatch.size());
                strFaceSnapMatch.read();
                String fn_image = null;
                if(strFaceSnapMatch.struSnapInfo.pBuffer1!=null) {//开始-单人入库
                    if ((strFaceSnapMatch.struSnapInfo.dwSnapFacePicLen > 0)) {
                        Response<List<ParamsModel>> fileUrl = findParamsListByKind();
                        long offset = 0;
                        ByteBuffer buffers = strFaceSnapMatch.struSnapInfo.pBuffer1.getByteBuffer(offset, strFaceSnapMatch.struSnapInfo.dwSnapFacePicLen);
                        byte[] bytes = new byte[strFaceSnapMatch.struSnapInfo.dwSnapFacePicLen];
                        buffers.rewind();
                        buffers.get(bytes);
                        SnapPicUrl = new String(bytes);
                        System.out.println("抓拍人脸子图URL:" + SnapPicUrl);
                        try {
                            buffer = downloadUrl(SnapPicUrl);
                            fn_image = FileUtil.fileUpload(buffer, fileUrl.getData().get(0).getValue(), "face");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        logger.info("黑名单抓拍图片地址-------------------------------" + fn_image);
                    }

                    try {
                        sAlarmType = sAlarmType + ":人脸黑名单比对报警,相识度:" + strFaceSnapMatch.fSimilarity + ":人脸比对结果:" + strFaceSnapMatch.byContrastStatus + ",黑名单姓名:" + new String(strFaceSnapMatch.struBlackListInfo.struBlackListInfo.struAttribute.byName, "GBK").trim() + ",\n黑名单证件信息:" + new String(strFaceSnapMatch.struBlackListInfo.struBlackListInfo.struAttribute.byCertificateNumber).trim();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    logger.info(sAlarmType);
                    String deviceNumber1 = device.get("device_number").toString();
                    //public byte byContrastStatus;      //比对结果,0-保留,1-比对成功,2-比对失败
                    logger.info("11111111" + strFaceSnapMatch.byContrastStatus);
                    if (strFaceSnapMatch.byContrastStatus == 2) {
                        logger.info("对比失败进入报警日志,会修改设备的ip要注意 陌生人报警");
                        getAlarmer(pAlarmer, deviceNumber1, "207", fn_image, 0);
                    }
                }//结束
                break;
            /*case HCNetSDK.COMM_FACECAPTURE_STATISTICS_RESULT://人脸抓拍人员统计信息
                HCNetSDK.NET_DVR_FACECAPTURE_STATISTICS_RESULT faceCaptureStatisticsResult = new HCNetSDK.NET_DVR_FACECAPTURE_STATISTICS_RESULT();
                faceCaptureStatisticsResult.write();
                int dwPeopleNum = faceCaptureStatisticsResult.dwPeopleNum;//人员数量
                logger.info("人脸抓拍人员统计信息{人员数量:" + dwPeopleNum + "}");
                break;
            case HCNetSDK.COMM_ALARMHOST_CID_ALARM:
                HCNetSDK.NET_DVR_CID_ALARM strCIDAlarm = new HCNetSDK.NET_DVR_CID_ALARM();
                strCIDAlarm.write();
                Pointer pCIDAlarm = strCIDAlarm.getPointer();
                pCIDAlarm.write(0, pAlarmInfo.getByteArray(0, strCIDAlarm.size()), 0, strCIDAlarm.size());
                strCIDAlarm.read();//从结构体里读取下您需要的信息即可
                int i = strCIDAlarm.dwIOTChannelNo;//通道号
                logger.info("通道号"+i);
                String srt3="";
                try {
                    srt3=new String(strCIDAlarm.sCIDDescribe ,"GBK");
                    sAlarmType = sAlarmType + ",CID事件号:"+strCIDAlarm.sCIDCode + ",CID事件名 :"+ srt3 + ",报告类型" + strCIDAlarm.byReportType + ",防区号"+strCIDAlarm.wDefenceNo;
                    logger.info(sAlarmType);
                    logger.info(sAlarmType);
                }catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
                newRow[0] = dateFormat.format(today);
                //报警类型
                newRow[1] = sAlarmType;
                //报警设备IP地址
                sIP = new String(pAlarmer.sDeviceIP).split("0", 2);
                newRow[2] = sIP[0];
//                alarmTableModel.insertRow(0, newRow);
                if(!srt3.contains("恢复")){
                    creatDevice(device,strCIDAlarm,pAlarmer);
                }
                break;*/
        }
        logger.info("报警信息结束");
    }

    /**
     * 4-单人入库-下载图片
     * @param urlString
     * @return
     * @throws IOException
     */
    public static byte[] downloadUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try (InputStream inputStream = connection.getInputStream()) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        } finally {
            connection.disconnect();
        }
    }


    //人脸能力集获取
    public boolean GetFaceCapabilities(int userId) {
        HCNetSDK.NET_DVR_XML_CONFIG_INPUT inBuf = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
        inBuf.dwSize = inBuf.size();
        String url = "GET /ISAPI/Intelligent/FDLib/capabilities\r\n";
        HCNetSDK.BYTE_ARRAY ptrUrl = new HCNetSDK.BYTE_ARRAY(url.length());
        System.arraycopy(url.getBytes(), 0, ptrUrl.byValue, 0, url.length());
        ptrUrl.write();
        inBuf.lpRequestUrl = ptrUrl.getPointer();
        inBuf.dwRequestUrlLen = url.length();
        HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT outBuf = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
        outBuf.dwSize = outBuf.size();
        HCNetSDK.BYTE_ARRAY ptrOutByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_DATA_LEN);
        outBuf.lpOutBuffer = ptrOutByte.getPointer();
        outBuf.dwOutBufferSize = HCNetSDK.ISAPI_DATA_LEN;
        outBuf.write();
        if (hCNetSDK.NET_DVR_STDXMLConfig(userId, inBuf, outBuf)) {
            return true;
        } else {
            logger.info("获取人脸能力集失败");
            return false;
        }
    }

    //根据id删除人脸库
    public boolean DeleteFDLib(String m_fdid,int userId) {
        HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
        struInput.dwSize = struInput.size();
//        int index = FDLibComboBox.getSelectedIndex();
//        String id = m_FDLibList.get(index).szFDID;
        String str = "DELETE /ISAPI/Intelligent/FDLib/" + m_fdid;
        HCNetSDK.BYTE_ARRAY ptrUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
        System.arraycopy(str.getBytes(), 0, ptrUrl.byValue, 0, str.length());
        ptrUrl.write();
        struInput.lpRequestUrl = ptrUrl.getPointer();
        struInput.dwRequestUrlLen = str.length();
        HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
        struOutput.dwSize = struOutput.size();
        struOutput.write();
        if (hCNetSDK.NET_DVR_STDXMLConfig(userId, struInput, struOutput)) {
            logger.info("删除人脸库成功");
            return true;
        } else {
            int code = hCNetSDK.NET_DVR_GetLastError();
            logger.info("删除人脸库失败" + code);
            return false;
        }
    }

    //根据id删除人脸照片
    public void DeleteFaceAppendData(String faceId) {
        String str = "DELETE /ISAPI/Intelligent/FDLib/" + m_FDID + "/picture/" + faceId;
        HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
        struInput.dwSize = struInput.size();
        HCNetSDK.BYTE_ARRAY ptrDeleteFaceLibUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
        System.arraycopy(str.getBytes(), 0, ptrDeleteFaceLibUrl.byValue, 0, str.length());
        ptrDeleteFaceLibUrl.write();
        struInput.lpRequestUrl = ptrDeleteFaceLibUrl.getPointer();
        struInput.dwRequestUrlLen = str.length();
        struInput.lpInBuffer = null;
        struInput.dwInBufferSize = 0;
        struInput.write();
        HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
        struOutput.dwSize = struOutput.size();
        struOutput.lpOutBuffer = null;
        struOutput.dwOutBufferSize = 0;
        HCNetSDK.BYTE_ARRAY ptrStatusByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_STATUS_LEN);
        struOutput.lpStatusBuffer = ptrStatusByte.getPointer();
        struOutput.dwStatusSize = HCNetSDK.ISAPI_STATUS_LEN;
        struOutput.write();
        if (!hCNetSDK.NET_DVR_STDXMLConfig(lUserID, struInput, struOutput)) {
            logger.info("lpRequestUrl:" + str);
            logger.info("NET_DVR_STDXMLConfig DELETE failed with:" + " " + hCNetSDK.NET_DVR_GetLastError());
        } else {
            logger.info("lpRequestUrl:" + str);
            logger.info("图片删除成功 PID:"+faceId);
        }
    }

    //创建人脸库
    public boolean CreateFDLib(String FDLibName,int userId) {
        try {
            if (m_isSupportFDLib) {
                //返回true,说明支持人脸
                HCNetSDK.NET_DVR_XML_CONFIG_INPUT struInput = new HCNetSDK.NET_DVR_XML_CONFIG_INPUT();
                struInput.dwSize = struInput.size();
                String str = "POST /ISAPI/Intelligent/FDLib\r\n";
                HCNetSDK.BYTE_ARRAY ptrUrl = new HCNetSDK.BYTE_ARRAY(HCNetSDK.BYTE_ARRAY_LEN);
                System.arraycopy(str.getBytes(), 0, ptrUrl.byValue, 0, str.length());
                ptrUrl.write();
                struInput.lpRequestUrl = ptrUrl.getPointer();
                struInput.dwRequestUrlLen = str.length();
                byte[] byFDLibName = new byte[0];
                try {
                    byFDLibName = FDLibName.getBytes("UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String strInBuffer1 = new String("<CreateFDLibList><CreateFDLib><id>1</id><name>");
                String strInBuffer2 = new String("</name><thresholdValue>1</thresholdValue><customInfo /></CreateFDLib></CreateFDLibList>");
                int iStringSize = byFDLibName.length + strInBuffer1.length() + strInBuffer2.length();
                HCNetSDK.BYTE_ARRAY ptrByte = new HCNetSDK.BYTE_ARRAY(iStringSize);
                System.arraycopy(strInBuffer1.getBytes(), 0, ptrByte.byValue, 0, strInBuffer1.length());
                System.arraycopy(byFDLibName, 0, ptrByte.byValue, strInBuffer1.length(), byFDLibName.length);
                System.arraycopy(strInBuffer2.getBytes(), 0, ptrByte.byValue, strInBuffer1.length() + byFDLibName.length, strInBuffer2.length());
                ptrByte.write();
                struInput.lpInBuffer = ptrByte.getPointer();
                struInput.dwInBufferSize = ptrByte.byValue.length;
                struInput.write();
                HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT struOutput = new HCNetSDK.NET_DVR_XML_CONFIG_OUTPUT();
                struOutput.dwSize = struOutput.size();
                HCNetSDK.BYTE_ARRAY ptrOutByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_DATA_LEN);
                struOutput.lpOutBuffer = ptrOutByte.getPointer();
                struOutput.dwOutBufferSize = HCNetSDK.ISAPI_DATA_LEN;
                HCNetSDK.BYTE_ARRAY ptrStatusByte = new HCNetSDK.BYTE_ARRAY(HCNetSDK.ISAPI_STATUS_LEN);
                struOutput.lpStatusBuffer = ptrStatusByte.getPointer();
                struOutput.dwStatusSize = HCNetSDK.ISAPI_STATUS_LEN;
                struOutput.write();
                if (hCNetSDK.NET_DVR_STDXMLConfig(userId, struInput, struOutput)) {
                    String xmlStr = struOutput.lpOutBuffer.getString(0);
                    //dom4j解析xml
                    Document document = DocumentHelper.parseText(xmlStr);
                    //获取根节点元素对象
                    Element FDLibInfoList = document.getRootElement();
                    //同时迭代当前节点下面的所有子节点
                    Iterator<Element> iterator = FDLibInfoList.elementIterator();
                    Element FDLibInfo = iterator.next();
                    Iterator<Element> iterator2 = FDLibInfo.elementIterator();
                    while (iterator2.hasNext()) {
                        Element e = iterator2.next();
                        if (e.getName().equals("id")) {
                            m_FDID = e.getText();
                        }
                        if ("id".equals(e.getName())) {
                            redisOper("m_FDID",e.getText(),"2");
//                            jedisTemplate.set("m_FDID", e.getText());
                        }
                        logger.info(e.getName() + ":" + e.getText());
                    }
                } else {
                    int code = hCNetSDK.NET_DVR_GetLastError();
                    logger.info("创建人脸库失败:" + code);
                    return false;
                }
            } else {
                return false;
            }
        } catch (DocumentException ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    //建立人脸数据长连接
    public void FDLibUploadFileButtonClick(String img) {
        if (m_lUploadHandle != -1) {
            if (hCNetSDK.NET_DVR_UploadClose(m_lUploadHandle)) {
                logger.info("NET_DVR_UploadClose success");
            } else {
                logger.info("NET_DVR_UploadClose fail,error=" + hCNetSDK.NET_DVR_GetLastError());
            }
        }
        UploadFile();
        Thread thread = new Thread() {
            public void run() {
                UploadSend(img);
                while (true) {
                    if (-1 == m_lUploadHandle) {
                        return;
                    }
                    m_UploadStatus = getUploadState();
                    if (m_UploadStatus == 1) {
                        HCNetSDK.NET_DVR_UPLOAD_FILE_RET struPicRet = new HCNetSDK.NET_DVR_UPLOAD_FILE_RET();
                        struPicRet.write();
                        Pointer lpPic = struPicRet.getPointer();
                        boolean bRet = hCNetSDK.NET_DVR_GetUploadResult(m_lUploadHandle, lpPic, struPicRet.size());
                        if (!bRet) {
                            logger.info("NET_DVR_GetUploadResult failed with:" + hCNetSDK.NET_DVR_GetLastError());
                        } else {
                            logger.info("NET_DVR_GetUploadResult succ");
                            struPicRet.read();
                            m_picID = new String(struPicRet.sUrl);
                            logger.info("图片上传成功PicID:" + m_picID);
//                            JOptionPane.showMessageDialog(null, "图片上传成功 PID:" + m_picID);
                        }
                        if (hCNetSDK.NET_DVR_UploadClose(m_lUploadHandle)) {
                            m_lUploadHandle = -1;
                        } else if (m_UploadStatus >= 3 || m_UploadStatus == -1) {
                            logger.info("m_UploadStatus = " + m_UploadStatus);
                            hCNetSDK.NET_DVR_UploadClose(m_lUploadHandle);
                            m_lUploadHandle = -1;
                            break;
                        }
                    }
                }
            }
        };
        thread.start();
    }

    public int getUploadState() {
        IntByReference pInt = new IntByReference(0);
        m_UploadStatus = hCNetSDK.NET_DVR_GetUploadState(m_lUploadHandle, pInt);
        if (m_UploadStatus == -1) {
            logger.info("NET_DVR_GetUploadState fail,error=" + hCNetSDK.NET_DVR_GetLastError());
        } else if (m_UploadStatus == 2) {
            logger.info("is uploading!!!!  progress = " + pInt.getValue());
        } else if (m_UploadStatus == 1) {
            logger.info("progress = " + pInt.getValue());
            logger.info("Uploading Succ!!!!!");
        } else {
            logger.info("NET_DVR_GetUploadState fail  m_UploadStatus=" + m_UploadStatus);
            logger.info("NET_DVR_GetUploadState fail,error=" + hCNetSDK.NET_DVR_GetLastError());
        }
        return m_UploadStatus;
    }

    public void UploadSend(String img) {
        FileInputStream picfile = null;
        String xmlfile = "<FaceAppendData><name>111</name><bornTime>2000-01-01</bornTime><sex></sex><province/><certificateType/><certificateNumber/></FaceAppendData>";
        int picdataLength = 0;
        String imgName="";
        try {
            String[] split1 = img.split("/");
            imgName = split1[6];
            imgName = "C:\\sykean\\file-app\\face\\" + imgName;
            picfile = new FileInputStream(new File(imgName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            picdataLength = picfile.available();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        HCNetSDK.BYTE_ARRAY ptrpicByte = new HCNetSDK.BYTE_ARRAY(picdataLength);
        HCNetSDK.BYTE_ARRAY ptrxmlByte = new HCNetSDK.BYTE_ARRAY(10 * 1024);
        ptrxmlByte.byValue = xmlfile.getBytes();
        ptrxmlByte.write();
        try {
            picfile.read(ptrpicByte.byValue);
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        ptrpicByte.write();
        HCNetSDK.NET_DVR_SEND_PARAM_IN struSendParam = new HCNetSDK.NET_DVR_SEND_PARAM_IN();
        struSendParam.pSendData = ptrpicByte.getPointer();
        struSendParam.dwSendDataLen = picdataLength;
        struSendParam.pSendAppendData = ptrxmlByte.getPointer();
        struSendParam.dwSendAppendDataLen = xmlfile.length();
        if (struSendParam.pSendData == null || struSendParam.pSendAppendData == null || struSendParam.dwSendDataLen == 0 || struSendParam.dwSendAppendDataLen == 0) {
            logger.info("input file/xml data err");
            return;
        }
        if(imgName.endsWith(".jpg")){
            struSendParam.byPicType = 1;//图片格式jpg
        }else{
            struSendParam.byPicType = 3;//图片格式png
        }
        struSendParam.dwPicMangeNo = 0;//图片管理号
        byte[] bname = new byte[HCNetSDK.NAME_LEN];
        byte[] btmp;
        try {
            btmp = "人脸库1".getBytes("GBK");
            for (int i = 0; i < btmp.length; i++) {
                bname[i] = btmp[i];
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        struSendParam.sPicName = bname;
        struSendParam.write();
        int iRet = hCNetSDK.NET_DVR_UploadSend(m_lUploadHandle, struSendParam.getPointer(), null);
        logger.info("iRet=" + iRet);
        if (iRet < 0) {
            logger.info("NET_DVR_UploadSend fail,error=" + hCNetSDK.NET_DVR_GetLastError());
        } else {
            logger.info("NET_DVR_UploadSend success");
            logger.info("dwSendDataLen =" + struSendParam.dwSendDataLen);
            logger.info("dwSendAppendDataLen =" + struSendParam.dwSendAppendDataLen);
        }
        try {
            picfile.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void UploadFile() {
        if (m_isSupportFDLib) {
            HCNetSDK.NET_DVR_FACELIB_COND struInput = new HCNetSDK.NET_DVR_FACELIB_COND();
            struInput.dwSize = struInput.size();
            struInput.szFDID = m_FDID.getBytes();
            struInput.byConcurrent = 0;
            struInput.byCover = 1;
            struInput.byCustomFaceLibID = 0;
            struInput.write();
            Pointer lpInput = struInput.getPointer();
            int ret = hCNetSDK.NET_DVR_UploadFile_V40(lUserID, HCNetSDK.IMPORT_DATA_TO_FACELIB, lpInput, struInput.size(), null, null, 0);
            if (ret == -1) {
                int code = hCNetSDK.NET_DVR_GetLastError();
                logger.info("上传图片文件失败:" + code);
            } else {
                m_lUploadHandle = ret;
                logger.info("上传图片文件成功");
            }
        }
    }

    /**
     * 远程防区布防
     * @param i  防区号
     * @param userId 用户id对应device_sort
     */
    public void bufang(int i,int userId){
        HCNetSDK.NET_DVR_ALARMIN_SETUP alarmSetUp = new HCNetSDK.NET_DVR_ALARMIN_SETUP();
        alarmSetUp.byAssiciateAlarmIn[i-1]=1;
        alarmSetUp.write();
        boolean b = hCNetSDK.NET_DVR_AlarmHostSetupAlarmChan(Integer.valueOf(userMap.get(userId).toString()), alarmSetUp);
        if(b){
            logger.info("布防结果输出"+b);
        }else{
            logger.info("防区布防失败,错误号:" + hCNetSDK.NET_DVR_GetLastError());
        }
    }
    /**
     * 远程防区撤防
     * @param i  防区号
     * @param userId 用户id对应device_sort
     */
    public void chefang(int i,int userId){
        HCNetSDK.NET_DVR_ALARMIN_SETUP alarmSetUp = new HCNetSDK.NET_DVR_ALARMIN_SETUP();
        alarmSetUp.byAssiciateAlarmIn[i-1]=1;
        alarmSetUp.write();
        boolean b = hCNetSDK.NET_DVR_AlarmHostCloseAlarmChan(Integer.valueOf(userMap.get(userId).toString()), alarmSetUp);
        if(b){
            logger.info("撤防结果输出"+b);
        }else{
            logger.info("防区撤防失败,错误号:" + hCNetSDK.NET_DVR_GetLastError());
        }
    }

    /**
     * 以下为工具类
     */
    protected static String b2s(byte b[]) {
        int len = 0;
        while (b.length > len && b[len] != 0) {
            len++;
        }
        try {
            String sendString = new String(b, "gb2312");
            return new String(b, "gb2312").trim();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "转码失败";
    }

//    @Override
//    public void onApplicationEvent(ApplicationEvent event) {
//        if(event instanceof ApplicationReadyEvent){
//            try {
//                statDll();
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }
//    }
}
public class HKCallback_New extends HKBaseCallback{

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    DllConfig dllConfig;
    @Reference
    ParamsFacade paramsFacade;
    @Autowired
    private JedisTemplate jedisTemplate;
    @Reference
    BulletEqpDeviceFacade bulletEqpDeviceFacade;
    @Autowired
    BulletEqpDeviceInfoDetailSDKFacade bulletEqpDeviceInfoDetailSDKFacade;
    @Autowired
    BulletDutyManageFacade bulletDutyManageFacade;
    @Reference
    BulletLogAlarmFacade bulletLogAlarmFacade;
    @Reference
    UserFacade userFacade;

    @Autowired
    private BulletEqpDeviceService bulletEqpDeviceService;
    @Autowired
    ApplyDialogMsgManage applyDialogMsgManage;
    @Autowired
    ApplySendMsgManage applySendMsgManage;
    @Autowired
    private GroupHouseFacade groupHouseFacade;
    @Value("${beitai.HKConfig}")
    boolean HKConfig;
    @Value("${sms.roles}")
    private String roles;

    public static Map<String, DeviceInfo> ipMap = new HashMap<>();


    public static Map<String, LinkedList<SnapMatchInfoVO>> groupHouseMap = new HashMap<>(4);

    @Override
    protected HKBaseCallback getInstance() {
        return null;
    }

    @Override
    public boolean getAddHKSDK() {
        return HKConfig;
    }

    @Override
    public List<Map<String, Object>> getHkConfigure() {
        List<Map<String, Object>> hkConfigure = userFacade.getHkConfigure();
        return hkConfigure;
    }

    @Override
    public void getAlarmer(HCNetSDK.NET_DVR_ALARMER pAlarmer, String deviceNumber, String alarm_type, String alarm_pic_path,int alarmNumber) {
        String data = bulletEqpDeviceInfoDetailSDKFacade.getDeviceIdBypDeviceID(deviceNumber).getData();
        BulletEqpDeviceModel bulletEqpDeviceModel = new BulletEqpDeviceModel();
        bulletEqpDeviceModel.setId(data == null ? SysUtil.GetUUID() : data);
        bulletEqpDeviceModel.setState("1");//在线
        bulletEqpDeviceModel.setDevtype("5");//报警主机
        bulletEqpDeviceModel.setDeviceVersion("V1.0");//版本
        bulletEqpDeviceModel.setDeviceNumber(deviceNumber);//编号
        bulletEqpDeviceModel.setDeviceIp(dllConfig.host);//ip
        bulletEqpDeviceFacade.existUpdate(bulletEqpDeviceModel);
        //报警日志插入记录
        Map<String, Object> params = new HashMap<>();
        String uuid = SysUtil.GetUUID();
        params.put("id", uuid);
        params.put("alarm_device_id", deviceNumber);//设备编号
        params.put("alarm_type", alarm_type);// 报警类型
        Date date = new Date();
        params.put("alarm_time", date);
        params.put("alarm_pic_path", alarm_pic_path);//照片
        bulletEqpDeviceInfoDetailSDKFacade.saveAlarmLog(params);
        applyDialogMsgManage.hkAlarmer(params);
    }

    public String saveAlarm(String deviceNumber, String alarm_type, String alarm_pic_path,int alarmNumber,Date date) {
        logger.info("act=saveAlarm deviceNumber={},alarm_type={}", deviceNumber, alarm_type);
        //报警日志插入记录
        Map<String, Object> params = new HashMap<>();
        String uuid = SysUtil.GetUUID();
        params.put("id", uuid);
        params.put("alarm_device_id", deviceNumber);//设备编号
        params.put("alarm_type", alarm_type);// 报警类型
        params.put("alarm_time", date);
        params.put("alarm_pic_path", alarm_pic_path);//照片
        params.put("content", AlarmTypeEnum.indexOf(alarm_type));
        logger.info("class=HKCallback_New act=saveAlarm params={}",JsonMapper.toJson(params));
        bulletEqpDeviceInfoDetailSDKFacade.saveAlarmLog(params);
        return uuid;
    }

    @Override
    public Response<ParamsModel> getParamsInfoByKindAndName() {
        return paramsFacade.getParamsInfoByKindAndName("hk_pt","hk_numberLimit");
    }

    @Override
    public Response<List<ParamsModel>> findParamsListByKind() {
        return paramsFacade.findParamsListByKind("file_app");
    }

    @Override
    public BulletEqpDeviceModel getDeptByDeviceId(Map<String, Object> device) {
        return bulletEqpDeviceFacade.getDeptByDeviceId(device.get("device_number").toString()).getData();
    }

    @Override
    public void creatDevice(Map<String, Object> device, HCNetSDK.NET_DVR_CID_ALARM strCIDAlarm,HCNetSDK.NET_DVR_ALARMER pAlarmer) {

            //生成设备
            String deviceNumber = device.get("device_number").toString();
            jedisTemplate.set("channel@"+deviceNumber,String.valueOf(strCIDAlarm.dwIOTChannelNo));
            String data = bulletEqpDeviceFacade.getDeviceIdBypDeviceID(deviceNumber).getData();
            BulletEqpDeviceModel bulletEqpDeviceModel = new BulletEqpDeviceModel();
            bulletEqpDeviceModel.setId(data==null? SysUtil.GetUUID():data);
            bulletEqpDeviceModel.setState("1");//在线
            bulletEqpDeviceModel.setDevtype("5");//报警主机
            bulletEqpDeviceModel.setDeviceVersion("V1.0");//版本
            bulletEqpDeviceModel.setDeviceNumber(deviceNumber);//编号
            bulletEqpDeviceModel.setDeviceIp(b2s(pAlarmer.sDeviceIP));//ip
            bulletEqpDeviceFacade.existUpdate(bulletEqpDeviceModel);
            //报警日志插入记录
            Map<String, Object> params=new HashMap<>();
            params.put("id",SysUtil.GetUUID());
            params.put("alarm_device_id", deviceNumber);//设备编号
            params.put("areaCode", String.valueOf(strCIDAlarm.wDefenceNo));//设备编号
            Map<String, Object> alarm_map = bulletEqpDeviceFacade.getAlarmTypeByMap(params);
            if(alarm_map!=null && alarm_map.containsKey("alarmType")){
                System.out.println("报警主机设备编号打印======================"+alarm_map.get("device_number").toString());
                params.put("alarm_device_id", alarm_map.get("device_number").toString());//设备编号
                params.put("alarm_type", alarm_map.get("alarmType").toString());// 报警类型
            }
            params.put("alarm_time",new Date());
            params.put("alarm_pic_path",null);//照片
            if(params.containsKey("alarm_type") && StringUtils.isNotBlank(params.get("alarm_type").toString())){
                params.put("content",AlarmTypeEnum.indexOf(params.get("alarm_type").toString()));
                params.put("alarm_type","125");
                bulletLogAlarmFacade.saveAlarmLog(params);
                //报警推流(推送本机领导)

                try {

                    Map map=new HashMap();
                    map.put("alarmCount",params.get("content").toString());
                    map.put("deptName","");
                    map.put("alarmName",params.get("content").toString());
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    map.put("alarmTime",simpleDateFormat.format(new Date()));
                    map.put("cType",alarm_map.get("alarmType").toString());
                    map.put("alarmId",params.get("id").toString());
                    map.put("houseName","");
                    map.put("deviceIp","null");
                    map.put("voice",params.get("content").toString());
                    applyDialogMsgManage.sendDeviceAlarmCallBack(map);
                }catch (Exception e){
                    logger.error("报警主机推流异常====="+e.getMessage());
                    e.printStackTrace();
                }

                //通过设备id获取所属单位id
                BulletEqpDeviceModel data1 = bulletEqpDeviceFacade.getDeptByDeviceId(deviceNumber).getData();
                if(data1!=null){
                    //获取对应防区号摄像头IP
                    Map<String,Object> map = new HashMap<>();
                    map.put("parent_id",data1.getId());
                    map.put("devtype","6");
                    map.put("bullet_type",strCIDAlarm.wDefenceNo);
                    Map<String,Object> deviceMap = bulletEqpDeviceFacade.getDeviceInFoByMap(map);
                    if(deviceMap!=null){
                        applyDialogMsgManage.hkCreateDeviceAlarm(deviceMap.get("device_channel").toString(),data1.getDeptId(),params.get("alarm_type").toString());
                    }
                }
            }

    }

    @Override
    public String redisOper(String str, String strNew,String type) {

        if (JedisStateEnum.GET.ofType().equals(type)){
            return jedisTemplate.get(str);
        }else if (JedisStateEnum.SET.ofType().equals(type)){
            jedisTemplate.set(str,strNew);
            return null;
        }else {
            return "eroor";
        }
    }


    /**
     * 人脸识别
     * @param snapMatchAlarmResp
     * @return
     */
    @Override
    public boolean snapMatchAlarm(SnapMatchAlarmResp snapMatchAlarmResp) {
        logger.info("method=snapMatchAlarm act=snapMatchAlarm params={}", JsonMapper.toJson(snapMatchAlarmResp));
        SnapMatchAlarmResp.MatchPic matchPic = snapMatchAlarmResp.getMatchPic();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        // 根据报警信息传递的摄像头IP反查对应设备
        DeviceInfo device = bulletEqpDeviceService.getCameraDeviceInfoByIp(snapMatchAlarmResp.getSourceIp());
        // 设备id
        String deviceNumber = device.getDeviceNumber();
        if (snapMatchAlarmResp.getByContrastStatus() == CommonConstant.MATCH_FAIL) {
            // 陌生人
            String uid = saveAlarm(deviceNumber, AlarmTypeEnum.type207.getType(), matchPic.getDwSnapFacePicUrl(), 0,snapMatchAlarmResp.getToday());
//            sendMsg("33", uid, deviceNumber, AlarmTypeEnum.type207.getType(), matchPic.getDwSnapFacePicUrl(), snapMatchAlarmResp.getToday(), "陌生人", device.getDevicename());
            SnapMatchInfoVO snapMatchInfoVO = buildMatchInfoVO(deviceNumber, matchPic.getDwSnapFacePicUrl(), "陌生人", AlarmTypeEnum.type207.getType(), snapMatchAlarmResp.getToday(),device.getDevicename());
            saveSnapDynamic(snapMatchInfoVO);

            // 发送短信
            String[] split = roles.split(",");
            List<String> objects = Arrays.asList(split);
            Response<List<UserModel>> userInfo = userFacade.findUserInfoByDeptIdAndRole(device.getDeptId(),objects);
            for (UserModel datum : userInfo.getData()) {
                applySendMsgManage.sendMsg("有陌生人入库,请及时处理",datum.getMobile());
            }

        } else {
            //  区分是否为值班人员
            SnapMatchAlarmResp.MatchInfo matchINfo = snapMatchAlarmResp.getMatchINfo();
            String byName = matchINfo.getByName();
            BulletDutyManageModel model = new BulletDutyManageModel();
            String s = DateUtil.dateTo0String(new Date());
            model.setStartTime(s);
            Response<List<BulletDutyManageModel>> userByToday = bulletDutyManageFacade.getUserByToday(model);
            List<BulletDutyManageModel> todayUserList = userByToday.getData();
            boolean contains = false;
            if (todayUserList != null && todayUserList.size() != 0) {
                Set<String> idSet = new HashSet<>();
                todayUserList.forEach(item -> {
                    idSet.addAll(item.getUserIds());
                });
                Response<List<UserModel>> listByIds = userFacade.findListByIds(idSet);
                List<UserModel> data = listByIds.getData();
                Set<String> collect = data.stream().map(UserModel::getName).collect(Collectors.toSet());
                contains = collect.contains(byName);
            }
            // 非值班人员
            if (!contains) {
                String uid = saveAlarm(deviceNumber, AlarmTypeEnum.type206.getType(), matchPic.getDwSnapFacePicUrl(), 0, snapMatchAlarmResp.getToday());
                SnapMatchInfoVO snapMatchInfoVO = buildMatchInfoVO(deviceNumber, matchPic.getDwSnapFacePicUrl(), "非值班人员:" + byName, AlarmTypeEnum.type206.getType(), snapMatchAlarmResp.getToday(),device.getDevicename());
                saveSnapDynamic(snapMatchInfoVO);
            } else {
                // 枚举中没有值班人员,这里暂时设置218为值班人员报警类型
                SnapMatchInfoVO snapMatchInfoVO = buildMatchInfoVO(deviceNumber, matchPic.getDwSnapFacePicUrl(), "值班人员:" + byName, "218", snapMatchAlarmResp.getToday(),device.getDevicename());
                saveSnapDynamic(snapMatchInfoVO);
            }
        }
        return true;
    }

    public SnapMatchInfoVO buildMatchInfoVO(String deviceNumber, String snapUrl, String value, String type, Date alarmTime, String deviceName) {
        SnapMatchInfoVO res = new SnapMatchInfoVO();
        res.setDeviceName(deviceName);
        try {
            logger.info("method=buildMatchInfoVO deviceNumber={}", deviceNumber);
            List<DeviceInfo> listByDeviceNumbers = bulletEqpDeviceService.getListByDeviceNumbers(Sets.newHashSet(deviceNumber));
            if (!CollectionUtils.isEmpty(listByDeviceNumbers)) {
                String houseId = listByDeviceNumbers.get(0).getHouseId();
                res.setGroupHouseId(houseId);
            }
        } catch (BusinessException e) {
            logger.error("method=buildMatchInfoVO act=getGroupHouseId error deviceNumber={}", deviceNumber, e);
        }

        res.setValue(value);
        res.setType(type);
        res.setAlarmTime(alarmTime);
        res.setAlarmPicPath(snapUrl);
        return res;
    }

    private void saveSnapDynamic(SnapMatchInfoVO snapMatchInfoVO){
        logger.info("method=saveSnapDynamic params={}", JsonMapper.toJson(snapMatchInfoVO));
        String groupHouseId = snapMatchInfoVO.getGroupHouseId();
        LinkedList<SnapMatchInfoVO> snapMatchInfoVOS = groupHouseMap.get(groupHouseId);
        if (ObjectUtils.isEmpty(snapMatchInfoVOS)){
            LinkedList<SnapMatchInfoVO> res = new LinkedList<>();
            res.add(snapMatchInfoVO);
            groupHouseMap.put(groupHouseId, res);
            return;
        }

        if (snapMatchInfoVOS.size() >= 10) {
            snapMatchInfoVOS.removeLast();
        }

        snapMatchInfoVOS.addFirst(snapMatchInfoVO);
    }

    public PopulationDensityAlarmResp alarmResp =null; //2. 公共部分-获取报警信息

    /**
     * 3. 单人入库-启动定时任务,每分钟进行监测
     */
    @Scheduled(fixedRate = 60000) // 每 60000 毫秒(1 分钟)执行一次
    public void performTask() {
        if(alarmResp !=null) {
            // 这里是你想要每分钟执行的任务
            System.out.println("定时任务执行中: " + System.currentTimeMillis());
            String ipAddress = alarmResp.getIpAddress();
            Integer lUserID = userIDMap.get(ipAddress);
            int channelID = alarmResp.getChannelID();
            try {
                com.beitai.device.param.DeviceInfo deviceInfoByChannel = baseApi.getDeviceInfoByChannel(lUserID, channelID);
                String ip = deviceInfoByChannel.getIp();
                // 根据海康传过来的摄像头IP反查对应摄像头设备
                DeviceInfo device = bulletEqpDeviceService.getCameraDeviceInfoByIp(ip);
                String deviceNumber = device.getDeviceNumber();
                PopulationDensityAlarmResp.FramesPeopleCounting framesPeopleCounting = alarmResp.getFramesPeopleCounting();
                int framesPeopleCountingNum = framesPeopleCounting.getFramesPeopleCountingNum();
                // 单人入库报警
                if (framesPeopleCountingNum == 1) {
                    logger.info("act=populationDensityAlarm framesPeopleCountingNum = 1");
                    String resourcesContent = alarmResp.getFramesPeopleCounting().getBackgroundImage().getResourcesContent();
                    Response<List<ParamsModel>> fileUrl = findParamsListByKind();
                    String fn_image = null;
                    try {
                        byte[] buffer = downloadUrl(resourcesContent);
                        fn_image = FileUtil.fileUpload(buffer, fileUrl.getData().get(0).getValue(), "face");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    saveAlarm(deviceNumber, AlarmTypeEnum.type208.getType(), fn_image, 0, alarmResp.getToday());
                }
                //清空局部变量
                alarmResp = null;
            } catch (UnsupportedEncodingException e) {
                logger.info("act=populationDensityAlarm getDeviceInfo error params={}",e);
            }
        }
    }

    /**
     * 区域人数统计
     * 4. 单人入库-获取报警信息
     * @param resp
     * @return
     */
    @Override
    public boolean populationDensityAlarm(PopulationDensityAlarmResp resp) {
        alarmResp=resp;
        return true;
    }

    /**
     * 客流量统计
     * @param pdcAlarmResp
     * @return
     */
    @Override
    public boolean pdcAlarm(PdcAlarmResp pdcAlarmResp) {
        logger.info("act=pdcAlarm params={}", JsonMapper.toJson(pdcAlarmResp));
        DeviceInfo device = bulletEqpDeviceService.getCameraDeviceInfoByIp(pdcAlarmResp.getSourceIp());
        String deviceNumber = device.getDeviceNumber();
        Integer lUserID = userIDMap.get(pdcAlarmResp.getPrevIp());
        //人员限制查询
        List<DeviceInfo> response= null;
        try {
            logger.info("act=pdcAlarm getDevice deviceNumber={}", deviceNumber);
            response = bulletEqpDeviceService.getListByDeviceNumbers(Sets.newHashSet(deviceNumber));
        } catch (BusinessException e) {
            logger.error("act=pdcAlarm response is null params={}",JsonMapper.toJson(pdcAlarmResp),e);
        }

        if (response == null){
            return false;
        }

        String houseId = response.get(0).getHouseId();
        Response<GroupHouseModel> resp = groupHouseFacade.selectGroupHouseById(houseId);
        logger.info("act=pdcAlarm getGroupHouse resp={}",JsonMapper.toJson(resp));
        GroupHouseModel data = resp.getData();
        Integer numberLimit = data.getMaxCountLimit();
        byte[] pictureNew = baseApi.getPictureNew(lUserID, (pdcAlarmResp.getByChannel() & 0xFF));

        // 最小时间段
        if (pdcAlarmResp.getByMode() == 1) {
            // 单人入库
            if(pdcAlarmResp.getDwEnterNum() == 1 && numberLimit>1){
                // 抓图
                String fn_image = uploadPic(pictureNew,"pdc");
                saveAlarm(deviceNumber, AlarmTypeEnum.type208.getType(), fn_image,0, pdcAlarmResp.getToday());
            }
            // 入库超额
            if(pdcAlarmResp.getDwEnterNum() > numberLimit){
                String fn_image = uploadPic(pictureNew,"pdc");
                saveAlarm(deviceNumber, AlarmTypeEnum.type219.getType(), fn_image,0, pdcAlarmResp.getToday());
            }
        }

        return true;
    }

    private String uploadPic(byte[] pictureNew,String uploadChildPath){
        // 抓图
        String fn_image = null;
        Response<List<ParamsModel>> fileUrl = findParamsListByKind();
        System.out.println(fileUrl.getData().get(0));
        try {
            fn_image = FileUtil.fileUpload(pictureNew,
                    fileUrl.getData().get(0).getValue(), uploadChildPath);
        } catch (Exception e) {
            logger.error("act=populationDensityAlarm upload pic error",e);
        }

        return fn_image;
    }

    private boolean creatDevice(CidAlarmResp cidAlarmResp) {
        try {
            Map<String, Object> device = deviceMap.get(cidAlarmResp.getSourceIp().trim());
            //生成设备
            String deviceNumber = device.get("device_number").toString();
            jedisTemplate.set("channel@"+deviceNumber,String.valueOf(cidAlarmResp.getDwIOTChannelNo()));
            String data = bulletEqpDeviceFacade.getDeviceIdBypDeviceID(deviceNumber).getData();
            BulletEqpDeviceModel bulletEqpDeviceModel = new BulletEqpDeviceModel();
            bulletEqpDeviceModel.setId(data==null? SysUtil.GetUUID():data);
            bulletEqpDeviceModel.setState("1");//在线
            bulletEqpDeviceModel.setDevtype("5");//报警主机
            bulletEqpDeviceModel.setDeviceVersion("V1.0");//版本
            bulletEqpDeviceModel.setDeviceNumber(deviceNumber);//编号
            bulletEqpDeviceModel.setDeviceIp(cidAlarmResp.getSourceIp().trim());//ip
            bulletEqpDeviceFacade.existUpdate(bulletEqpDeviceModel);
            //报警日志插入记录
            Map<String, Object> params=new HashMap<>();
            params.put("id",SysUtil.GetUUID());
            params.put("alarm_device_id", deviceNumber);//设备编号
            params.put("areaCode", String.valueOf(cidAlarmResp.getWDefenceNo()));//设备编号
            Map<String, Object> alarm_map = bulletEqpDeviceFacade.getAlarmTypeByMap(params);
            if(alarm_map!=null && alarm_map.containsKey("alarmType")){
                System.out.println("报警主机设备编号打印======================"+alarm_map.get("device_number").toString());
                params.put("alarm_device_id", alarm_map.get("device_number").toString());//设备编号
                params.put("alarm_type", alarm_map.get("alarmType").toString());// 报警类型
            }

            params.put("alarm_time",new Date());
            params.put("alarm_pic_path",null);//照片
            if(params.containsKey("alarm_type") && StringUtils.isNotBlank(params.get("alarm_type").toString())){
                bulletLogAlarmFacade.saveAlarmLog(params);
                applyDialogMsgManage.hkCreateDeviceAlarm();
            }
        }catch (Exception e){
            logger.error("class=HKCallback act=creatDevice error param={}",cidAlarmResp,e);
            return false;
        }
        return true;
    }

    /**
     * @param cidAlarmResp
     * @return
     */
    @Override
    public boolean cidAlarm(CidAlarmResp cidAlarmResp) {
        System.out.println("通道号"+cidAlarmResp.getDwIOTChannelNo());
        String srt3="";
        try {
            srt3=new String(cidAlarmResp.getSCIDDescribe() ,"GBK");
        }catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        if(!srt3.contains("恢复")){
            return creatDevice(cidAlarmResp);
        }
        return true;
    }
}
### Python对接海康摄像头/SDK教程 #### 准备工作 对于希望利用Python与海康设备或平台进行对接的情况,开发者需先依据自身的操作系统下载对应的海康SDK版本[^1]。此过程不仅涉及获取必要的库文件和支持材料,还可能需要查阅官方提供的API文档来理解各个函数的作用及其参数定义。 #### 接口调用准备 要成功调用海康SDK中的功能,在Python环境中通常会借助`ctypes`或其他类似的C扩展模块加载动态链接库(.dll/.so),从而使得能够访问由C/C++编写的原生方法。这一步骤至关重要,因为大部分情况下海康所提供的SDK是以C语言为基础构建而成的[^3]。 #### 实现业务逻辑所需参考资料 实现具体的业务需求时,除了上述提到的基础准备工作外,还需要深入研究海康提供的技术手册以及样例程序。特别是当涉及到特定应用场景下的高级特性(比如人脸识别),则应参考类似Java对接过程中积累的经验教训和技术细节[^2]。 #### 参数传递方式 关于如何将参数正确地传递给SDK内部的方法,一般而言可以通过构造结构体(structure)的方式来进行映射;而对于简单的输入输出,则可以直接指定基本数据类型的变量作为实参。值得注意的是,某些复杂的配置项或是枚举型的数据往往被封装成了宏定义的形式存在于头文件之中,因此了解并熟悉这些预处理器指令同样重要。 #### 示例代码展示 下面给出了一段简化版的Python脚本用于演示连接到一台支持ONVIF协议的网络摄像机,并尝试读取其基本信息: ```python import ctypes from ctypes import c_char_p, Structure, POINTER class NET_DVR_DEVICEINFO_V40(Structure): _fields_ = [ ("sSerialNumber", (c_char * 48)), # ...其他字段... ] HCNetSDK = ctypes.CDLL('./libhcnetsdk.so') # 加载Linux下共享对象文件 # 初始化SDK环境 HCNetSDK.NET_DVR_Init() device_info = NET_DVR_DEVICEINFO_V40() user_id = HCNetSDK.NET_DVR_Login_V40( b'IP地址', # 设备IP地址 8000, # 端口号 b'admin', # 用户名 b'password', # 密码 None, device_info) if user_id >= 0: print('Login Success') else: error_code = HCNetSDK.NET_DVR_GetLastError() print(f'Error Code:{error_code}') # 清理资源 HCNetSDK.NET_DVR_Cleanup() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值