Browse Source

初始化httpClient,整理萤石云监控实现

liuyaowen 1 year ago
parent
commit
2c822ef6cf

+ 65 - 44
src/main/java/com/yunfeiyun/agmp/iots/core/http/EzvizHttpClient.java

@@ -1,5 +1,6 @@
 package com.yunfeiyun.agmp.iots.core.http;
 
+import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.date.DateUnit;
 import cn.hutool.core.date.DateUtil;
 import com.alibaba.fastjson2.*;
@@ -8,15 +9,24 @@ import com.yunfeiyun.agmp.common.enums.RedisCacheKey;
 import com.yunfeiyun.agmp.common.exception.BizException;
 import com.yunfeiyun.agmp.common.framework.manager.RedisCacheManager;
 import com.yunfeiyun.agmp.common.utils.StringUtils;
+import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
 import com.yunfeiyun.agmp.iot.common.constant.IotErrorCode;
 import com.yunfeiyun.agmp.iot.common.constant.devicetype.ServiceNameConst;
 import com.yunfeiyun.agmp.iot.common.domain.IotEzvizuser;
 import com.yunfeiyun.agmp.iot.common.exception.IotBizException;
 import com.yunfeiyun.agmp.iots.common.annotate.HttpCore;
+import com.yunfeiyun.agmp.iots.common.modal.IotDeviceconnResVo;
 import com.yunfeiyun.agmp.iots.device.common.ezviz.EzvizApi;
 import com.yunfeiyun.agmp.iots.device.mapper.IotEzvizdevicebindMapper;
 import com.yunfeiyun.agmp.iots.device.mapper.IotEzvizuserMapper;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustStrategy;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.ssl.SSLContexts;
 import org.springframework.http.*;
 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
 import org.springframework.stereotype.Component;
@@ -27,6 +37,10 @@ import org.springframework.web.client.RestTemplate;
 
 import javax.annotation.PostConstruct;
 import javax.annotation.Resource;
+import javax.net.ssl.SSLContext;
+import java.security.KeyManagementException;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashMap;
@@ -36,30 +50,58 @@ import java.util.concurrent.TimeUnit;
  * 监控萤石云平台HttpClient(对接设备:海康,大华)
  * */
 @Slf4j
-@Component
 @HttpCore(serviceName = ServiceNameConst.SERVICE_EZVIZ_MINITOR)
-public class EzvizHttpClient {
+public class EzvizHttpClient extends HttpClient{
+
     private RestTemplate restTemplate;
-    @Resource
-    private RedisCacheManager redisCacheManager ;
-    @Resource
-    private IotEzvizuserMapper iotEzvizuserMapper;
-    @Resource
-    private IotEzvizdevicebindMapper iotEzvizdevicebindMapper;
+    private String ezvizAppKey ;
+    private String ezvizAppSecret;
+    private String hikCloudClientId;
+    private String hikCloudClientSecret;
+    private RedisCacheManager redisCacheManager;
 
-    @PostConstruct
-    public void start() throws InterruptedException{
-        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
-        factory.setConnectTimeout(1000*60*3);
-        factory.setReadTimeout(1000*60*3);
-        factory.setConnectionRequestTimeout(1000*60*3);
-        restTemplate = new RestTemplate(factory);
+    @Override
+    public void init(IotDeviceconnResVo iotDeviceconnResVo, JSONObject configJson) {
+        try {
+            super.init(iotDeviceconnResVo,configJson);
+            initRestTemplate();
+            ezvizAppKey = configJson.getString("ezvizAppKey");
+            ezvizAppSecret = configJson.getString("ezvizAppSecret");
+            hikCloudClientId = configJson.getString("hikCloudClientId");
+            hikCloudClientSecret = configJson.getString("hikCloudClientSecret");
+            redisCacheManager = SpringUtils.getBean(RedisCacheManager.class);
+        } catch (Exception e) {
+            log.error("萤石云httpClient初始化失败",e);
+        }
+    }
+    private void initRestTemplate() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
+        TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
+        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
+        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
+        HttpClientBuilder clientBuilder = HttpClients.custom();
+        CloseableHttpClient httpClient = clientBuilder.setSSLSocketFactory(sslsf).build();
+        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
+        requestFactory.setConnectTimeout(1000 * 10 );
+        requestFactory.setReadTimeout(1000 * 10 );
+        requestFactory.setConnectionRequestTimeout(1000 * 10 );
+        requestFactory.setHttpClient(httpClient);
+        restTemplate = new RestTemplate(requestFactory);
+    }
+    public String getAccessToken(){
+        String accessToken = redisCacheManager.getCacheObject(RedisCacheKey.IOT_EZVIZ_HTTP_TOKEN,ezvizAppKey);
+        if(StringUtils.isEmpty(accessToken)){
+            accessToken = refreshToken();
+        }
+        if(StringUtils.isEmpty(accessToken)){
+            throw new IotBizException(IotErrorCode.GET_TOKEN_FAIL);
+        }
+        return accessToken;
     }
 
-    public String refreshToken(String appKey,String appSecret){
+    public String refreshToken(){
         MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
-        paramsMap.add("appKey",appKey);
-        paramsMap.add("appSecret",appSecret);
+        paramsMap.add("appKey",ezvizAppKey);
+        paramsMap.add("appSecret",ezvizAppSecret);
         MultiValueMap<String, String> headers = new HttpHeaders();
         headers.add("Content-Type","application/x-www-form-urlencoded");
         HttpEntity<?> httpEntity = new HttpEntity<>(paramsMap,headers);
@@ -72,34 +114,17 @@ public class EzvizHttpClient {
                 String accessToken = data.getString("accessToken");
                 Date expireTime = new Date(data.getLong("expireTime"));
                 long timeOut = DateUtil.between(new Date(),expireTime, DateUnit.SECOND);
-                redisCacheManager.setCacheObject(RedisCacheKey.IOT_EZVIZ_HTTP_TOKEN,appKey,accessToken,timeOut, TimeUnit.SECONDS);
+                redisCacheManager.setCacheObject(RedisCacheKey.IOT_EZVIZ_HTTP_TOKEN,ezvizAppKey,accessToken,timeOut, TimeUnit.SECONDS);
                 return accessToken;
             }
         }
         return null;
     }
-    public String getAccessToken(String deviceCode){
-        log.info("设备查询萤石云用户信息:【{}】",deviceCode);
-        IotEzvizuser iotEzvizuser = iotEzvizuserMapper.selectIotEzvizuserByDeviceCode(deviceCode);
-        log.info("萤石云用户信息:【{}】",iotEzvizuser);
-        String accessToken = redisCacheManager.getCacheObject(RedisCacheKey.IOT_EZVIZ_HTTP_TOKEN,iotEzvizuser.getAppKey());
-        if(StringUtils.isEmpty(accessToken)){
-           accessToken = refreshToken(iotEzvizuser.getAppKey(), iotEzvizuser.getAppSecret());
-        }
-        if(StringUtils.isEmpty(accessToken)){
-            throw new IotBizException(IotErrorCode.GET_TOKEN_FAIL);
-        }
-        return accessToken;
-    }
+
 
 
     public Object postExchange( String url, JSONObject body, Class<?> responseType){
-        String channelNo = body.getString("channelNo");
-        String devCode = body.getString("deviceSerial");
-        if(StringUtils.isNotEmpty(channelNo)){
-            devCode = devCode+"-"+body.getString("channelNo");
-        }
-        String accessToken = getAccessToken(devCode);
+        String accessToken = refreshToken();
         MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
         paramsMap.setAll(JSONObject.parseObject(body.toJSONString(JSONWriter.Feature.IgnoreNoneSerializable), HashMap.class));
         paramsMap.add("accessToken",accessToken);
@@ -122,12 +147,8 @@ public class EzvizHttpClient {
     }
 
     public Object getExchange( String url, JSONObject body, Class<?> responseType){
-        String channelNo = body.getString("channelNo");
-        String devCode = body.getString("deviceSerial");
-        if(StringUtils.isNotEmpty(channelNo)){
-            devCode = devCode+"-"+channelNo;
-        }
-        String accessToken = getAccessToken(devCode);
+
+        String accessToken = refreshToken();
         MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
         paramsMap.setAll(JSONObject.parseObject(body.toJSONString(JSONWriter.Feature.IgnoreNoneSerializable), HashMap.class));
         paramsMap.add("accessToken",accessToken);

+ 1 - 10
src/main/java/com/yunfeiyun/agmp/iots/core/http/HttpClient.java

@@ -43,16 +43,7 @@ public class HttpClient {
 
     }
 
-    /**
-     * 唯一标识
-     */
-    private String clientID;
-    // 弃用,每个厂家的httpClient自己定义存储配置信息
-    @Deprecated
-    HttpConfig httpConfig;
-    // 弃用,接口认证每个厂家的httpClient自己定义存储
-    @Deprecated
-    private String token;
+
 
     private IotDeviceconnResVo iotDeviceconnResVo;
     private JSONObject clientConfig;

+ 11 - 2
src/main/java/com/yunfeiyun/agmp/iots/core/manager/HttpManager.java

@@ -1,6 +1,8 @@
 package com.yunfeiyun.agmp.iots.core.manager;
 
 import com.alibaba.fastjson2.JSONObject;
+import com.yunfeiyun.agmp.iot.common.domain.IotDevice;
+import com.yunfeiyun.agmp.iot.common.enums.IotDeviceconnTypeEnum;
 import com.yunfeiyun.agmp.iot.common.service.TypeCacheService;
 import com.yunfeiyun.agmp.iots.common.annotate.HttpCore;
 import com.yunfeiyun.agmp.iots.common.modal.IotDeviceconnResVo;
@@ -47,7 +49,7 @@ public class HttpManager {
      * 注意:原来的getFirmDevBid(原来的配置id)暂时换成了getDevtypeBid,真正实现时候看是否正确
      */
     public void buildHttpConnection(IotDeviceconnResVo iotDeviceconnResVo, JSONObject configJson) {
-        if("0".equals(iotDeviceconnResVo.getDevconnType())){
+        if(IotDeviceconnTypeEnum.COMMON.getCode().equals(iotDeviceconnResVo.getDevconnType())){
             initCommonClient(iotDeviceconnResVo,configJson);
             // 通用连接处理
         }else {
@@ -76,7 +78,6 @@ public class HttpManager {
         privateHttpClientByConnBid.put(iotDeviceconnResVo.getDevconnBid(),httpClient);
         iotDeviceconnResVoHashMap.put(iotDeviceconnResVo.getDevconnBid(),iotDeviceconnResVo);
     }
-
     private HttpClient initHttpClient(IotDeviceconnResVo iotDeviceconnResVo ,JSONObject configJson){
         //获取继承了HttpClient的所有类
         Class<? extends HttpClient> httpClientClass = httpClinetClassMap.get(typeCacheService.getServiceNameByDevTypeBid(iotDeviceconnResVo.getDevtypeBid()));
@@ -94,4 +95,12 @@ public class HttpManager {
         }
     }
 
+    public HttpClient getHttpClientByDevice(IotDevice iotDevice){
+        IotDeviceconnResVo iotDeviceconnResVo = iotDeviceconnResVoHashMap.get(iotDevice.getDevconnBid());
+        if(IotDeviceconnTypeEnum.COMMON.getCode().equals(iotDeviceconnResVo.getDevconnType())){
+            return commonHttpClientByTypeCode.get(iotDevice.getDevtypeBid());
+        }else {
+            return privateHttpClientByConnBid.get(iotDevice.getDevconnBid());
+        }
+    }
 }

+ 2 - 1
src/main/java/com/yunfeiyun/agmp/iots/device/service/IHikVisionEzvizDevice.java

@@ -1,8 +1,9 @@
 package com.yunfeiyun.agmp.iots.device.service;
 
 import com.alibaba.fastjson2.JSONObject;
+import com.yunfeiyun.agmp.iot.common.domain.IotDevice;
 import com.yunfeiyun.agmp.iots.device.common.HttpDevice;
 
 public interface IHikVisionEzvizDevice extends HttpDevice {
-    public JSONObject refreshStatus(JSONObject param);
+    public JSONObject refreshStatus(JSONObject param, IotDevice iotDevice);
 }

+ 25 - 21
src/main/java/com/yunfeiyun/agmp/iots/device/serviceImp/IHikVisionEzvizDeviceImpl.java

@@ -14,6 +14,7 @@ import com.yunfeiyun.agmp.iot.common.domain.IotMonitorCapture;
 import com.yunfeiyun.agmp.iot.common.model.cmd.CmdModel;
 import com.yunfeiyun.agmp.iot.common.service.MongoService;
 import com.yunfeiyun.agmp.iots.core.http.EzvizHttpClient;
+import com.yunfeiyun.agmp.iots.core.manager.HttpManager;
 import com.yunfeiyun.agmp.iots.core.manager.MqttManager;
 import com.yunfeiyun.agmp.iots.device.common.HttpDeviceAbstractImpl;
 import com.yunfeiyun.agmp.iots.device.common.ezviz.EzvizApi;
@@ -39,8 +40,7 @@ import java.util.concurrent.TimeUnit;
 @Slf4j
 @Component(value = ServiceNameConst.SERVICE_EZVIZ_MINITOR)
 public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements IHikVisionEzvizDevice {
-    @Resource
-    private EzvizHttpClient ezvizHttpClient;
+    
     @Resource
     private RedisCacheManager redisCacheManager;
     @Resource
@@ -53,6 +53,8 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
     private ResManager resManager;
     @Autowired
     private MqttManager mqttManager;
+    @Resource
+    private HttpManager httpManager;
 
     @Override
     public Object sendCmd(CmdModel cmdModel) throws Exception {
@@ -62,8 +64,8 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
         CmdModel.Cmd cmdDistribution = cmdModel.getCmdDistribution();
         // 获取执行的方法 ,方法可以通过反射获取执行,也可以临时case 匹配
         String methodName = cmdDistribution.getFunc();
-        Method method = this.getClass().getDeclaredMethod(methodName,JSONObject.class);
-        Object result =  method.invoke(this,cmdDistribution.getJsons());
+        Method method = this.getClass().getDeclaredMethod(methodName,JSONObject.class,IotDevice.class);
+        Object result =  method.invoke(this,cmdDistribution.getJsons(),cmdModel.getIotDevice());
         JSONObject resultObject = JSONObject.from(result);
         log.info("【海康萤石云平台监控】指令发送结果:{}",resultObject);
         cmdModel.setClogDesc(cmdDistribution.getJsons().toJSONString());
@@ -95,21 +97,21 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
     }
 
 
-    private Object ptzStart(JSONObject param){
-        return ezvizHttpClient.postExchange(EzvizApi.START_PTZ,param,JSONObject.class);
+    private Object ptzStart(JSONObject param,IotDevice iotDevice){
+        return ezvizHttpClient(iotDevice).postExchange(EzvizApi.START_PTZ,param,JSONObject.class);
     }
-    private Object ptzEnd(JSONObject param){
-        return ezvizHttpClient.postExchange(EzvizApi.STOP_PTZ,param,JSONObject.class);
+    private Object ptzEnd(JSONObject param,IotDevice iotDevice){
+        return ezvizHttpClient(iotDevice).postExchange(EzvizApi.STOP_PTZ,param,JSONObject.class);
     }
-    private Object capture(JSONObject param){
-        JSONObject captureResult = (JSONObject) ezvizHttpClient.postExchange(EzvizApi.CAPTURE,param,JSONObject.class);
+    private Object capture(JSONObject param,IotDevice iotDevice){
+        JSONObject captureResult = (JSONObject) ezvizHttpClient(iotDevice).postExchange(EzvizApi.CAPTURE,param,JSONObject.class);
         if(String.valueOf(HttpStatus.OK.value()).equals(captureResult.get("code"))){
             Object data = captureResult.get("data");
             if(data!=null){
                 JSONObject dataObject = JSONObject.from(data);
                 String picUrl = dataObject.getString("picUrl");
                 String devCode = param.getString("deviceSerial")+"-"+param.getString("channelNo");
-                IotDevice iotDevice = iotDeviceService.selectDeviceByDeviceServiceNameAndDevCode(ServiceNameConst.SERVICE_EZVIZ_MINITOR,devCode);
+                iotDevice = iotDeviceService.selectDeviceByDeviceServiceNameAndDevCode(ServiceNameConst.SERVICE_EZVIZ_MINITOR,devCode);
                 IotMonitorCapture iotMonitorCapture = new IotMonitorCapture();
                 iotMonitorCapture.setDevBid(iotDevice.getDevBid());
                 iotMonitorCapture.setPicBid(iotMonitorCapture.getUUId());
@@ -121,31 +123,29 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
         }
         return captureResult;
     }
-    private Object video(JSONObject param){
-        return ezvizHttpClient.postExchange(EzvizApi.VIDEO,param,JSONObject.class);
+    private Object video(JSONObject param,IotDevice iotDevice){
+        return ezvizHttpClient(iotDevice).postExchange(EzvizApi.VIDEO,param,JSONObject.class);
     }
-    private Object address(JSONObject param){
-        JSONObject addressObject = (JSONObject) ezvizHttpClient.postExchange(EzvizApi.GET_DEVICE_VISION_ADDRESS,param,JSONObject.class);
+    private Object address(JSONObject param,IotDevice iotDevice){
+        JSONObject addressObject = (JSONObject) ezvizHttpClient(iotDevice).postExchange(EzvizApi.GET_DEVICE_VISION_ADDRESS,param,JSONObject.class);
         if(String.valueOf(HttpStatus.OK.value()).equals(addressObject.get("code"))){
             Object data = addressObject.get("data");
             if(data!=null){
                 JSONObject dataObject = JSONObject.from(data);
-                String devCode = param.getString("deviceSerial")+"-"+param.getString("channelNo");
-                dataObject.put("accessToken",ezvizHttpClient.getAccessToken(devCode));
+                dataObject.put("accessToken",ezvizHttpClient(iotDevice).getAccessToken());
             }
         }
         return addressObject;
     }
 
     @Override
-    public JSONObject refreshStatus(JSONObject param){
-        IotDevice iotDevice = JSONObject.parseObject(param.toJSONString(),IotDevice.class);
+    public JSONObject refreshStatus(JSONObject param,IotDevice iotDevice){
         log.info("【海康萤石云平台监控】设备检测设备在线状态,devCode={}",iotDevice.getDevCode());
         param = new JSONObject();
         String[] devCodeArray = iotDevice.getDevCode().split("-");
         param.put("deviceSerial",devCodeArray[0]);
         param.put("channelNo",devCodeArray[1]);
-        JSONObject refreshStatus = (JSONObject) ezvizHttpClient.getExchange(EzvizApi.STATUS,param,JSONObject.class);
+        JSONObject refreshStatus = (JSONObject) ezvizHttpClient(iotDevice).getExchange(EzvizApi.STATUS,param,JSONObject.class);
         if(refreshStatus.get("status").equals(1)) {
             iotDevice.setDevStatus(IotEnumOnlineStatus.ONLINE.getStatus());
             iotDeviceService.updateIotDevice(iotDevice);
@@ -170,7 +170,7 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
             for(IotDevice iotDevice : iotDeviceList){
                 CompletableFuture<JSONObject> generateGraphics = CompletableFuture.supplyAsync(() -> {
                     try {
-                        return this.refreshStatus(JSONObject.from(iotDevice));
+                        return this.refreshStatus(null,iotDevice);
                     } catch (Exception e) {
                         throw new RuntimeException(e);
                     }
@@ -184,4 +184,8 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
             log.error("同步海康设备数据失败",e);
         }
     }
+    
+    public EzvizHttpClient ezvizHttpClient(IotDevice iotDevice){
+        return (EzvizHttpClient) httpManager.getHttpClientByDevice(iotDevice);
+    }
 }