海清智元-设备下发人员信息和人脸

	public static final Integer TIMEOUT = 10000;
	//登录
    private static String getAuth(IotCameraParam camera) {
        return "Basic " + Base64.encode(camera.getUsername() + ":" + camera.getPassword());
    }
	// 拼接登录url
    private static String getHost(IotCameraParam camera) {
        return String.format("http://%s:%s", camera.getIp(), camera.getPort());
    }

发送数据

    private IotHqvtResult getHttpPostData(String url, String body, IotCameraParam camera) {
        IotHqvtResult hqvtResult = new IotHqvtResult();
        try {
            HttpResponse httpResponse = HttpUtil.createPost(url).header(Header.CONTENT_TYPE.getValue(), MediaType.APPLICATION_JSON_VALUE)
                    .header(Header.AUTHORIZATION, getAuth(camera))
                    .header(Header.CONTENT_LENGTH.getValue(), String.valueOf(body.length()))
                    .timeout(TIMEOUT)
                    .body(body)
                    .execute();
                   if(ObjectUtil.isNull(httpResponse) || StrUtil.isEmpty(httpResponse.body())){
                       hqvtResult.setCode(IotHqvtExceptionEnum.NO_RETURN_VALUE.getCode());
                   }
            hqvtResult = JSONUtil.toBean(httpResponse.body(), IotHqvtResult.class);
        } catch (Exception e) {
            hqvtResult.setCode(IotHqvtExceptionEnum.EXECUTION_EXCEPTION.getCode());
        }
        return hqvtResult;
    }

获取设备信息

    /**
     * 获取设备信息
     */
    public static IotHqvtDeviceInfoResult getDeviceInfo(IotCameraParam camera) {

        HttpResponse response = HttpUtil.createPost(getHost(camera) + "/action/GetSysParam").header(Header.CONTENT_TYPE.getValue(), MediaType.TEXT_PLAIN_VALUE)
                .header(Header.AUTHORIZATION, getAuth(camera))
                .timeout(TIMEOUT)
                .execute();
        String responBody = response.body();
        if (StrUtil.isEmpty(responBody)) {
            return null;
        }
        return JSONUtil.toBean(responBody, IotHqvtDeviceInfoResult.class);
    }

下发人员信息和人脸

    @Override
    public void send(IotCommonMsgBodyParam msgBody) {
        IotReplyMsgBodyResult bodyResult;
        try {
            IotCameraParam cameraParam = JSONUtil.toBean(msgBody.getAccount(), IotCameraParam.class);
            List<IotAddFaceParam> faceParamList = JSONUtil.toList(msgBody.getBody(), IotAddFaceParam.class);
            log.info("HQVT addFace size:{}", faceParamList.size());
            if (CollUtil.isEmpty(faceParamList) || faceParamList.size() < 1) {
                redisMessageProducer.doSendMessage(IotRedisTopicConstant.REDIS_INSTRUCT_RESPONSE_TOPIC, JSONUtil.toJsonStr(msgBody.toResult("指令下发失败:参数为空")));
                return;
            }
            //先删除
            List<Long> userIds = faceParamList.stream().map(IotAddFaceParam::getUserId).collect(Collectors.toList());
            iotHqvtDeviceApiService.deleteFace(cameraParam, userIds);

            List<IotCommDataResult> commDataResults = iotHqvtDeviceApiService.addFace(cameraParam, faceParamList);

            log.info("HQVT addFace  commDataResults:{}", JSONUtil.toJsonStr(commDataResults));
            if (CollUtil.isNotEmpty(commDataResults) && commDataResults.size() > 0) {
                List<IotUserFaceResult> userResults = new ArrayList<>();
                for (IotCommDataResult result : commDataResults) {
                    IotUserFaceResult userResult = new IotUserFaceResult();
                    userResult.setUserId(result.getId());
                    userResult.setCode(result.getCode());
                    userResult.setMsg(result.getMsg());
                    userResults.add(userResult);
                }
                bodyResult = msgBody.toResult(JSONUtil.toJsonStr(userResults));
            } else {
                bodyResult = msgBody.toResult("指令下发成功:未获取到返回信息");
            }
            log.info("HQVT addFace  bodyResult:{}", JSONUtil.toJsonStr(bodyResult));
        } catch (Exception e) {
            bodyResult = msgBody.toResult("指令下发失败:" + e.getMessage());
            log.error("HQVT addFace msg: {}, e", JSONUtil.toJsonStr(msgBody), e);
        }
        redisMessageProducer.doSendMessage(IotRedisTopicConstant.REDIS_INSTRUCT_RESPONSE_TOPIC, JSONUtil.toJsonStr(bodyResult));
    }

添加人员信息和人脸

    public List<IotCommDataResult> addFace(IotCameraParam camera, List<IotAddFaceParam> faceList) {

        Map<String, String> emWitLogin = getEmWitLogin(camera);

        List<IotCommDataResult> results = new ArrayList<>();
//        for (IotAddFaceParam param : faceList) {
//
//            List<IotCommDataResult> commDataResults = addUserFace(camera, param, emWitLogin);
//            results.addAll(commDataResults);
//            ThreadUtil.sleep(500);
//        }
        List<IotCommDataResult> commDataResults = addBatchFace(camera, faceList, emWitLogin);
        results.addAll(commDataResults);

        //登出
        getEmWitLoginOut(camera, emWitLogin);
        return results;
    }

批量添加人员信息和人脸

    private List<IotCommDataResult> addBatchFace(IotCameraParam camera, List<IotAddFaceParam> faceList, Map<String, String> emWitLogin) {
        List<IotCommDataResult> results = new ArrayList<>();

        List<List<IotAddFaceParam>> addFaceList = Lists.partition(faceList, 10);
        for (List<IotAddFaceParam> faceParams : addFaceList) {
            try {
                IotEmWitParam emWitParam = new IotEmWitParam();
                emWitParam.setCh(1);
                emWitParam.setType(0);
                emWitParam.setCommand("frmFacePicture");

                IotEmWitAddFaceParam addFaceParam = new IotEmWitAddFaceParam();
                addFaceParam.setTargetName(TARGET_NAME);

                List<IotEmWitUserFaceParam> userFaces = new ArrayList<>();
                for (IotAddFaceParam param : faceParams) {

                    if (CollUtil.isEmpty(emWitLogin)) {
                        IotCommDataResult result = new IotCommDataResult();
                        result.setId(param.getUserId());
                        result.setCode(IotEmWitExceptionEnum.LOGIN_FAILED.getCode());
                        result.setMsg(IotEmWitExceptionEnum.LOGIN_FAILED.getMessage());
                        results.add(result);
                    }

                    IotEmWitUserFaceParam userFace = new IotEmWitUserFaceParam();
                    userFace.setFaceId(String.valueOf(param.getUserId()));
                    userFace.setName(param.getUserName());
                    userFace.setEnable(1);
                    userFace.setScheduleType(1);
                    userFace.setWiegandAssignType(0);
                    userFace.setWieganId("0");
                    userFace.setFaceData(ImageBase64Format.replaceAl(param.getFaceImage()));
                    userFaces.add(userFace);
                }
                addFaceParam.setList(userFaces);

                emWitParam.setData(addFaceParam);
                EmResponse emResponse = HttpRequestUtils.doPostDigest(this.getHost(camera) + "/digest/frmFacePicture", camera.getUsername(), camera.getPassword(), JSONUtil.toJsonStr(emWitParam), emWitLogin);
                ThreadUtil.sleep(800);
                log.error("emResponse:{}", JSONUtil.toJsonStr(emResponse));
                if (ObjectUtil.isNull(emResponse) || StrUtil.isEmpty(emResponse.getResult())) {
                    for (IotAddFaceParam param : faceParams) {
                        IotCommDataResult result = new IotCommDataResult();
                        result.setId(param.getUserId());
                        result.setCode(IotEmWitExceptionEnum.ERRY_RESPONSE.getCode());
                        result.setMsg(IotEmWitExceptionEnum.ERRY_RESPONSE.getMessage());
                        results.add(result);
                    }

                } else {
                    IotEmWitAddResult witResult = JSONUtil.toBean(emResponse.getResult(), IotEmWitAddResult.class);
                    if (ObjectUtil.isNull(witResult) || CollUtil.isEmpty(witResult.getData().getResultList())) {
                        for (IotAddFaceParam param : faceParams) {
                            IotCommDataResult result = new IotCommDataResult();
                            result.setId(param.getUserId());
                            result.setCode(IotEmWitExceptionEnum.NO_CORRESPONDING_OBTAINED.getCode());
                            result.setMsg(IotEmWitExceptionEnum.NO_CORRESPONDING_OBTAINED.getMessage());
                            results.add(result);
                        }
                    }
                    List<IotEmWitUserInfoResult> resultList = witResult.getData().getResultList();
                    for (IotEmWitUserInfoResult param : resultList) {
                        IotCommDataResult result = new IotCommDataResult();
                        result.setId(Long.parseLong(param.getFaceId()));
                        result.setCode(param.getResult());
                        result.setMsg(IotEmWitExceptionEnum.getMsg(param.getResult()));
                        results.add(result);
                    }
                }
            } catch (Exception e) {
                for (IotAddFaceParam param : faceParams) {
                    IotCommDataResult result = new IotCommDataResult();
                    result.setId(param.getUserId());
                    result.setCode(IotEmWitExceptionEnum.OPERATE_ERRY.getCode());
                    result.setMsg(IotEmWitExceptionEnum.OPERATE_ERRY.getMessage());
                    results.add(result);
                }
                log.error("添加失败", e);
            }
        }
        return results;
    }
    private IotCommDataResult addPersonFace(Integer deviceId,IotAddFaceParam param,IotCameraParam camera){
        IotCommDataResult result = new IotCommDataResult();
        result.setId(param.getUserId());
        IotHqvtAddPersonInfo infoParam = new IotHqvtAddPersonInfo();
        infoParam.setName(param.getUserName());
        infoParam.setIdCard(param.getIdCard());
        infoParam.setIdType(2);
        infoParam.setPersonType(0);
        infoParam.setPersonUUID(String.valueOf(param.getUserId()));
        if("male".equals(param.getSex())){
            infoParam.setGender(0);
        }
        if("female".equals(param.getSex())){
            infoParam.setGender(1);
        }
        infoParam.setDeviceID(deviceId);
        IotHqvtAddParam hqvtParam = new IotHqvtAddParam();
        hqvtParam.setOperator("AddPerson");
        hqvtParam.setPicinfo(param.getFaceImage());
        hqvtParam.setInfo(infoParam);
        IotHqvtResult hqvtResult = this.getHttpPostData(getHost(camera) + "/action/AddPerson", JSONUtil.toJsonStr(hqvtParam), camera);
        result.setCode(hqvtResult.getCode());
        result.setMsg(IotHqvtExceptionEnum.getMsg(hqvtResult.getCode()));
        return result;
    }

添加用户信息

    @Override
    public List<IotCommDataResult> addFace(IotCameraParam camera, IotAddFaceParam param) {

        Map<String, String> emWitLogin = getEmWitLogin(camera);
        //删除
//        deleteUserFace(camera, param.getUserId(),emWitLogin);
        List<IotCommDataResult> results = new ArrayList<>();
        if (CollUtil.isEmpty(emWitLogin)) {
            IotCommDataResult result = new IotCommDataResult();
            result.setCode(IotEmWitExceptionEnum.LOGIN_FAILED.getCode());
            result.setMsg(IotEmWitExceptionEnum.LOGIN_FAILED.getMessage());
            results.add(result);
            return results;
        }
        List<IotCommDataResult> commDataResults = addUserFace(camera, param, emWitLogin);
        results.addAll(commDataResults);
        //登出
        getEmWitLoginOut(camera, emWitLogin);
        return results;
    }

添加用户人脸

 private List<IotCommDataResult> addUserFace(IotCameraParam camera, IotAddFaceParam param, Map<String, String> emWitLogin) {
        log.info("TARGET_NAME:{}", TARGET_NAME);
        List<IotCommDataResult> results = new ArrayList<>();
        IotCommDataResult result = new IotCommDataResult();
        result.setId(param.getUserId());
        try {

            IotEmWitUserFaceParam userFace = new IotEmWitUserFaceParam();
            userFace.setFaceId(String.valueOf(param.getUserId()));
            userFace.setName(param.getUserName());
            userFace.setEnable(1);
            userFace.setScheduleType(1);
            userFace.setWiegandAssignType(0);
            userFace.setWieganId("123456");
            userFace.setFaceData(ImageBase64Format.replaceAl(param.getFaceImage()));

            IotEmWitAddFaceParam addFaceParam = new IotEmWitAddFaceParam();
            addFaceParam.setList(Collections.singletonList(userFace));
            addFaceParam.setTargetName(TARGET_NAME);

            IotEmWitParam emWitParam = new IotEmWitParam();
            emWitParam.setCh(1);
            emWitParam.setType(0);
            emWitParam.setCommand("frmFacePicture");
            emWitParam.setData(addFaceParam);

            EmResponse emResponse = HttpRequestUtils.doPostDigest(this.getHost(camera) + "/digest/frmFacePicture", camera.getUsername(), camera.getPassword(), JSONUtil.toJsonStr(emWitParam), emWitLogin);

            if (StrUtil.isEmpty(emResponse.getResult())) {
                result.setCode(IotEmWitExceptionEnum.ERRY_RESPONSE.getCode());
                result.setMsg(IotEmWitExceptionEnum.ERRY_RESPONSE.getMessage());
                results.add(result);
            } else {
                IotEmWitAddResult witResult = JSONUtil.toBean(emResponse.getResult(), IotEmWitAddResult.class);
                if (ObjectUtil.isNull(witResult) || CollUtil.isEmpty(witResult.getData().getResultList())) {
                    result.setCode(IotEmWitExceptionEnum.NO_CORRESPONDING_OBTAINED.getCode());
                    result.setMsg(IotEmWitExceptionEnum.NO_CORRESPONDING_OBTAINED.getMessage());
                    results.add(result);
                }
                List<IotEmWitUserInfoResult> resultList = witResult.getData().getResultList();
                result.setCode(resultList.get(0).getResult());
                result.setMsg(IotEmWitExceptionEnum.getMsg(resultList.get(0).getResult()));
            }
        } catch (Exception e) {
            result.setCode(IotEmWitExceptionEnum.OPERATE_ERRY.getCode());
            result.setMsg(e.getMessage());
        }
        results.add(result);
        return results;
    }

请求工具类

public class HttpRequestUtils {

    private static final String Content_type = "application/json;charset=UTF-8";
    private static final String WWW_AUTHENTICATE = "WWW-Authenticate";

    /**
     * 摘要认证 两次请求
     *
     * @param url
     * @return 返回结果
     */
    public static EmResponse doPostDigest(String url, String username, String password, String parms, Map<String, String> map) {
        log.info("Post请求url:{}", url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpPost httpPost = null;
        String strResponse;
        try {
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            // 构造请求头Header.CONTENT_TYPE.getValue(), MediaType.TEXT_PLAIN_VALUE
            httpPost.setHeader("Content-type", Content_type);
            httpPost.addHeader("Cache-Control", "no-cache"); //设置缓存
            if (ObjectUtil.isNotEmpty(map)) {
                httpPost.addHeader("S-HASH", map.get("S-HASH"));
                httpPost.addHeader("X-HASH", map.get("X-HASH"));
                httpPost.addHeader("C-HASH", map.get("C-HASH"));
            }
            RequestConfig.Builder builder = RequestConfig.custom();
            builder.setSocketTimeout(3000); //设置请求时间
            builder.setConnectTimeout(5000); //设置超时时间
            builder.setRedirectsEnabled(false);//设置是否跳转链接(反向代理)
            // 设置 连接 属性
            httpPost.setConfig(builder.build());
            StringEntity entityss = new StringEntity(parms, StandardCharsets.UTF_8);
            httpPost.setEntity(entityss);
            // 执行请求
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            // 检验返回码
            int statusCode = response.getStatusLine().getStatusCode();
            log.info("第一次发送摘要认证 Post请求 返回码:{}", statusCode);
            if (401 == statusCode) {
                strResponse = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                log.info("Post请求401返回结果:{}", strResponse);

                // 组织参数,发起第二次请求
                Header[] headers = response.getHeaders(WWW_AUTHENTICATE);
                HeaderElement[] elements = headers[0].getElements();
                String realm = null;
                String qop = null;
                String nonce = null;
                String opaque = null;
                String method = "POST";
                for (HeaderElement element : elements) {
                    if (element.getName().equals("X-Digest realm")) {
                        realm = element.getValue();
                    } else if (element.getName().equals("qop")) {
                        qop = element.getValue();
                    } else if (element.getName().equals("nonce")) {
                        nonce = element.getValue();
                    } else if (element.getName().equals("opaque")) {
                        opaque = element.getValue();
                    }
                }
                // 以上为 获取第一次请求后返回的 数据
                String nc = "00000002";
                String cnonce = IdWorker.getIdStr();
                // 后期变成可配置
                String a1 = username + ":" + realm + ":" + password;
                String a2 = method + ":" + url;
                String response1 = null;
                // 获取 Digest 这个字符串
                response1 = DigestUtils.md5Hex((DigestUtils.md5Hex(a1.getBytes(StandardCharsets.UTF_8)) + ":" + nonce + ":" + nc
                        + ":" + cnonce + ":" + qop + ":" + DigestUtils.md5Hex(a2.getBytes(StandardCharsets.UTF_8))).getBytes(StandardCharsets.UTF_8));

                httpPost.addHeader("Authorization", "X-Diges username=\"" + username + "\"" + ",realm=\"" + realm + "\""
                        + ",nonce=\"" + nonce + "\"" + ",uri=\"" + url + "\"" + ",qop=\"" + qop + "\"" + ",nc=\"" + nc + "\""
                        + ",cnonce=\"" + cnonce + "\"" + ",response=\"" + response1 + "\"" + ",opaque=\"" + opaque);

                // 发送第二次请求
                long reqSeconds = DateUtil.currentSeconds();
                response = httpClient.execute(httpPost);
                int statusCode1 = response.getStatusLine().getStatusCode();
                log.info("第二次请求相应时长:{}", DateUtil.currentSeconds() - reqSeconds);
                log.info("第二次发送摘要认证 Post请求 返回码:{}", statusCode1);
                Map<String, String> dataResponse = getDataResponse(response);
                EmResponse emResponse = new EmResponse();
                if(CollUtil.isNotEmpty(dataResponse)){
                    emResponse.setHeaders(dataResponse);
                }
                emResponse.setResult(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));

                log.info("返回结果:{}", JSONUtil.toJsonStr(emResponse));
                return emResponse;

            } else {
                strResponse = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                log.info("第一次鉴权认证请求非401 返回结果:{}", strResponse);
            }
        } catch (Exception e) {
            log.info("摘要认证 发送请求失败:{}", e.getLocalizedMessage());
        } finally {
            if (null != httpPost) {
                httpPost.releaseConnection();
            }
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.info("httpResponse流关闭异常:", e);
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.info("httpClient 流关闭异常:", e);
                }
            }
        }
        return null;
    }

    public static String getResponseStr(CloseableHttpResponse response) {
         if(ObjectUtil.isNull(response)){
             return null;
         }
        try {
            HttpEntity entity = response.getEntity();
            int statusCode1 = response.getStatusLine().getStatusCode();
            if (statusCode1 != 200) {
                return null;
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8))) {
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info("解析数据line:{}", line);
                    stringBuilder.append(line);
                }
                log.info("解析数据:{}", stringBuilder);
                return stringBuilder.toString();
            }
        } catch (IOException e) {
            log.error("解析数据异常", e);
        }
        return null;
    }

    public static Map<String, String> getDataResponse(CloseableHttpResponse response) {
        int statusCode1 = response.getStatusLine().getStatusCode();
        if (statusCode1 == 200) {
            Map<String, String> map = new HashMap<>();
            if (ObjectUtil.isNotEmpty(response.getFirstHeader("S-HASH"))) {
                map.put("S-HASH", response.getFirstHeader("S-HASH").getValue());
                map.put("C-HASH", response.getFirstHeader("C-HASH").getValue());
                map.put("X-HASH", response.getFirstHeader("X-HASH").getValue());
                return map;
            }
        }
        return null;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值