Просмотр исходного кода

补充设备连接信息更新,删除,编辑功能

liuyaowen 1 год назад
Родитель
Сommit
464c57df7b

+ 0 - 76
src/main/java/com/yunfeiyun/agmp/iots/core/http/HikOpenHttpClient.java

@@ -1,76 +0,0 @@
-package com.yunfeiyun.agmp.iots.core.http;
-
-import com.alibaba.fastjson2.JSON;
-import com.alibaba.fastjson2.JSONObject;
-import com.hikvision.artemis.sdk.ArtemisHttpUtil;
-import com.hikvision.artemis.sdk.config.ArtemisConfig;
-import com.yunfeiyun.agmp.common.enums.RedisCacheKey;
-import com.yunfeiyun.agmp.common.framework.manager.RedisCacheManager;
-import com.yunfeiyun.agmp.iot.common.constant.devicetype.ServiceNameConst;
-import com.yunfeiyun.agmp.iot.common.domain.IotFirmdev;
-import com.yunfeiyun.agmp.iots.common.annotate.HttpCore;
-import com.yunfeiyun.agmp.iots.service.IIotFirmdevService;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.Resource;
-import java.util.HashMap;
-import java.util.Map;
-
-/**海康安防管理平台http对接*/
-@Component
-@Slf4j
-@HttpCore(serviceName = ServiceNameConst.SERVICE_HIK_OPEN_MINITOR)
-public class HikOpenHttpClient {
-
-    @Resource
-    private RedisCacheManager redisCacheManager;
-    @Resource
-    private IIotFirmdevService iIotFirmdevService;
-
-    public Object[] getConfig() {
-        try {
-            IotFirmdev iotFirmdev = redisCacheManager.getCacheObject(RedisCacheKey.IOT_HIK_OPEN_API_CONFIG, ServiceNameConst.SERVICE_HIK_OPEN_MINITOR);
-            log.info("海康安防管理平台从缓存中获取连接信息:{}",iotFirmdev);
-            if (null == iotFirmdev) {
-                iotFirmdev = iIotFirmdevService.selectIotFirmdevByServiceName(ServiceNameConst.SERVICE_HIK_OPEN_MINITOR);
-                redisCacheManager.setCacheObject(RedisCacheKey.IOT_HIK_OPEN_API_CONFIG, ServiceNameConst.SERVICE_HIK_OPEN_MINITOR, iotFirmdev);
-            }
-            JSONObject config = JSONObject.parseObject(iotFirmdev.getFirmdevCfg());
-            return new Object[]{config.getString("hik_open_client_key"), config.getString("hik_open_client_secret"),config.getString("hik_open_client_host"),config.get("video_address")};
-        } catch (Exception e) {
-            return new Object[]{"null", "null","null"};
-        }
-    }
-    public JSONObject httpSend(String camsApi,Map<String, Object> paramMap){
-      //  String[] firmConfig = new String[]{"20441891","WGNUWjQW7r7fglY1JZBm","192.168.100.100"};
-        Object[] firmConfig = getConfig();
-        /**
-         * https://ip:port/artemis/api/resource/v1/regions
-         * 过查阅AI Cloud开放平台文档或网关门户的文档可以看到分页获取区域列表的定义,这是一个POST请求的Rest接口, 入参为JSON字符串,接口协议为https。
-         * ArtemisHttpUtil工具类提供了doPostStringArtemis调用POST请求的方法,入参可传JSON字符串, 请阅读开发指南了解方法入参,没有的参数可传null
-         */
-        ArtemisConfig config = new ArtemisConfig();
-        //config.setHost("blhik.dev.yunfeiyun.com:9080"); // 代理API网关nginx服务器ip端口
-        config.setHost(String.valueOf(firmConfig[2]));
-        config.setAppKey(String.valueOf(firmConfig[0]));  // 秘钥appkey
-        config.setAppSecret(String.valueOf(firmConfig[1]));// 秘钥appSecret
-        Map<String, String> path = new HashMap<String, String>(2) {
-            {
-                put("https://", camsApi);
-            }
-        };
-        String body = JSON.toJSON(paramMap).toString();
-        try {
-            String result = ArtemisHttpUtil.doPostStringArtemis(config,path, body, null, null, "application/json");
-            return JSONObject.parseObject(result);
-        }catch (Exception e){
-            JSONObject result = new JSONObject();
-            result.put("code",500);
-            result.put("msg","请求失败");
-            result.put("body","{}");
-            return result;
-        }
-    }
-
-}

+ 84 - 4
src/main/java/com/yunfeiyun/agmp/iots/core/manager/ConnectionManager.java

@@ -18,6 +18,7 @@ import com.yunfeiyun.agmp.iots.service.BusinessCoreService;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.http.util.TextUtils;
 import org.eclipse.paho.client.mqttv3.MqttException;
+import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
@@ -57,7 +58,7 @@ public class ConnectionManager {
         List<IotDeviceconnResVo> iotDeviceConnResVoList = businessCoreService.selectTosDevicetypeResVoList();
         log.info("【初始化】设备型号 构建链接 协议: {}个", iotDeviceConnResVoList.size());
         for (IotDeviceconnResVo iotDeviceconnResVo : iotDeviceConnResVoList) {
-            log.info("【初始化】【开始】协议加载,厂家:{},类型:{} ,配置:{}", iotDeviceconnResVo.getFirmName(), iotDeviceconnResVo.getDevtypeBid(), iotDeviceconnResVo.getDevconnConfig());
+            log.info("【初始化】【开始】协议加载,连接名称:{},厂家:{},类型:{} ,配置:{}", iotDeviceconnResVo.getDevconnName(),iotDeviceconnResVo.getFirmName(), iotDeviceconnResVo.getDevtypeBid(), iotDeviceconnResVo.getDevconnConfig());
             //将配置信息转换成jsonObject,这是个数组
             JSONArray jsonConfig = parseConfigJson(iotDeviceconnResVo.getDevconnConfig());
 
@@ -130,7 +131,9 @@ public class ConnectionManager {
         }
         return jsonConfig;
     }
-
+    /**
+     * 设备创建时,初始化设备连接
+     * */
     public void createDeviceHandle(IotDevice iotDevice) throws Exception {
         IotDeviceconn iotDeviceconn = deviceconnCacheService.getIotDeviceConnByDevconnBid(iotDevice.getDevconnBid());
         JSONArray connItemArray = JSONArray.parseArray(iotDeviceconn.getDevconnConfig());
@@ -164,7 +167,9 @@ public class ConnectionManager {
             }
         }
     }
-
+    /**
+     * 设备删除时,删除设备连接
+     * */
     public void deleteDeviceHandle(IotDevice iotDevice) {
         IotDeviceconn iotDeviceconn = deviceconnCacheService.getIotDeviceConnByDevconnBid(iotDevice.getDevconnBid());
         JSONArray connItemArray = JSONArray.parseArray(iotDeviceconn.getDevconnConfig());
@@ -198,11 +203,86 @@ public class ConnectionManager {
             }
         }
     }
-
+    /**
+     * 设备更新时,先删除旧设备连接,再创建新设备连接
+     * */
     public void editDeviceHandle(IotDeviceEditMqModel iotDeviceEditMqModel) throws Exception {
         deleteDeviceHandle(iotDeviceEditMqModel.getOldIotDevice());
         createDeviceHandle(iotDeviceEditMqModel.getNewIotDevice());
     }
+    /**
+     * 连接信息创建,初始化连接信息
+     * */
+    public void createIotDeviceconnHandle(IotDeviceconn iotDeviceconn){
+        log.info("【初始化】【开始】协议加载,连接名称:{},类型:{} ,配置:{}", iotDeviceconn.getDevconnName(), iotDeviceconn.getDevtypeBid(), iotDeviceconn.getDevconnConfig());
+        //将配置信息转换成jsonObject,这是个数组
+        JSONArray jsonConfig = parseConfigJson(iotDeviceconn.getDevconnConfig());
+
+        if (jsonConfig == null) {
+            log.error("【初始化】协议加载失败,连接名称:{},配置为空", iotDeviceconn.getDevconnName());
+            return;
+        }
+        IotDeviceconnResVo iotDeviceconnResVo = new IotDeviceconnResVo();
+        BeanUtils.copyProperties(iotDeviceconn,iotDeviceconnResVo);
+        // 遍历多个配置
+        for (int j = 0; j < jsonConfig.size(); j++) {
+            buildSingleMqttCoreByConfig(iotDeviceconnResVo, jsonConfig.getJSONObject(j));
+        }
+    }
+    /**
+     * 连接信息删除,删除连接信息
+     * */
+    public void deleteIotDeviceconnHandle(IotDeviceconn iotDeviceconn){
+        log.info("【连接信息删除】连接名称:{},类型:{} ,配置:{}", iotDeviceconn.getDevconnName(), iotDeviceconn.getDevtypeBid(), iotDeviceconn.getDevconnConfig());
+        //将配置信息转换成jsonObject,这是个数组
+        JSONArray jsonConfig = parseConfigJson(iotDeviceconn.getDevconnConfig());
+
+        if (jsonConfig == null) {
+            log.error("【连接信息删除】协议删除失败,连接名称:{},配置为空", iotDeviceconn.getDevconnName());
+            return;
+        }
+        IotDeviceconnResVo iotDeviceconnResVo = new IotDeviceconnResVo();
+        BeanUtils.copyProperties(iotDeviceconn,iotDeviceconnResVo);
+        // 遍历多个配置
+        for (int j = 0; j < jsonConfig.size(); j++) {
+            JSONObject config = jsonConfig.getJSONObject(j);
+            String type = config.getString("type");
+            if (TextUtils.isEmpty(type)) {
+                log.info("【连接信息删除】协议加载,厂家:{} type 为空:跳过", iotDeviceconnResVo.getFirmName());
+                return;
+            }
+            // 对核心构建方法catch,错了目前跳过
+            try {
+                switch (type) {
+                    case "mqtt":
+                        mqttManager.deleteMqttConnection(iotDeviceconnResVo.getDevconnBid());
+                        break;
+                    case "modbus-tcp": {
+                        //先不处理,对接到了再梳理
+                        break;
+                    }
+                    case "http": {
+                        httpManager.deleteHttpConnection(iotDeviceconnResVo.getDevconnBid());
+                        break;
+                    }
+                    default: {
+                        log.info("【连接信息删除】其它类型:{},跳过", type);
+                        return;
+                    }
+                }
+                log.info("【连接信息删除】【完成】连接名称:{},类型:{}", iotDeviceconnResVo.getDevconnName(), iotDeviceconnResVo.getDevtypeBid());
+            } catch (Exception e) {
+                log.error("【连接信息{}删除失败】", iotDeviceconnResVo.getDevconnName(), e);
+            }
+        }
+    }
+    /**
+     * 连接信息编辑,先删除连接信息,再初始化连接信息
+     * */
+    public void editIotDeviceconnHandle(IotDeviceconn iotDeviceconn){
+        deleteIotDeviceconnHandle(iotDeviceconn);
+        createIotDeviceconnHandle(iotDeviceconn);
+    }
 
     private void mqttDeviceCreateHandle(IotDevice iotDevice) throws Exception {
         String serviceName = typeCacheService.getServiceNameByDevTypeBid(iotDevice.getDevtypeBid());

+ 4 - 0
src/main/java/com/yunfeiyun/agmp/iots/core/manager/HttpManager.java

@@ -108,4 +108,8 @@ public class HttpManager {
         HttpClient httpClient = getHttpClientByDevice(iotDevice);
         httpClient.deviceCreateHandle(iotDevice);
     }
+
+    public void deleteHttpConnection(String devconnBid) {
+        privateHttpClientByConnBid.remove(devconnBid);
+    }
 }

+ 1 - 1
src/main/java/com/yunfeiyun/agmp/iots/device/common/ezviz/EzvizApi.java

@@ -17,5 +17,5 @@ public class EzvizApi {
     /**获取录像*/
     public static final String VIDEO = "https://open.ys7.com/api/lapp/video/by/time";
 
-    public static final String STATUS = "https://open.ys7.com/api/userdevice/v3/devices/op/permission?deviceSerial={deviceSerial}&accessToken={accessToken}";
+    public static final String STATUS = "https://open.ys7.com/api/lapp/device/camera/list";
 }

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

@@ -4,6 +4,8 @@ import com.alibaba.fastjson2.JSONObject;
 import com.yunfeiyun.agmp.iot.common.domain.IotDevice;
 import com.yunfeiyun.agmp.iots.device.common.HttpDevice;
 
+import java.util.List;
+
 public interface IHikVisionEzvizDevice extends HttpDevice {
-    public JSONObject refreshStatus(JSONObject param, IotDevice iotDevice);
+    public JSONObject refreshStatus(IotDevice iotDevice, List<IotDevice> childDeviceList);
 }

+ 47 - 26
src/main/java/com/yunfeiyun/agmp/iots/device/serviceImp/IHikVisionEzvizDeviceImpl.java

@@ -1,5 +1,6 @@
 package com.yunfeiyun.agmp.iots.device.serviceImp;
 
+import com.alibaba.fastjson2.JSONArray;
 import com.alibaba.fastjson2.JSONObject;
 import com.yunfeiyun.agmp.common.constant.ResConstants;
 import com.yunfeiyun.agmp.common.enums.RedisCacheKey;
@@ -7,6 +8,7 @@ import com.yunfeiyun.agmp.common.framework.manager.RedisCacheManager;
 import com.yunfeiyun.agmp.common.framework.manager.ResManager;
 import com.yunfeiyun.agmp.common.utils.DateUtils;
 import com.yunfeiyun.agmp.common.utils.uuid.UUID;
+
 import com.yunfeiyun.agmp.iot.common.constant.IotEnumOnlineStatus;
 import com.yunfeiyun.agmp.iot.common.constant.devicetype.ServiceNameConst;
 import com.yunfeiyun.agmp.iot.common.domain.IotDevice;
@@ -29,11 +31,10 @@ import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
 import java.lang.reflect.Method;
-import java.util.Date;
-import java.util.LinkedList;
-import java.util.List;
+import java.util.*;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
 
 
 @Service
@@ -64,7 +65,7 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
         CmdModel.Cmd cmdDistribution = cmdModel.getCmdDistribution();
         // 获取执行的方法 ,方法可以通过反射获取执行,也可以临时case 匹配
         String methodName = cmdDistribution.getFunc();
-        Method method = this.getClass().getDeclaredMethod(methodName,JSONObject.class,IotDevice.class);
+        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);
@@ -111,7 +112,6 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
                 JSONObject dataObject = JSONObject.from(data);
                 String picUrl = dataObject.getString("picUrl");
                 String devCode = param.getString("deviceSerial")+"-"+param.getString("channelNo");
-                iotDevice = iotDeviceService.selectDeviceByDeviceServiceNameAndDevCode(ServiceNameConst.SERVICE_EZVIZ_MINITOR,devCode);
                 IotMonitorCapture iotMonitorCapture = new IotMonitorCapture();
                 iotMonitorCapture.setDevBid(iotDevice.getDevBid());
                 iotMonitorCapture.setPicBid(iotMonitorCapture.getUUId());
@@ -139,26 +139,41 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
     }
 
     @Override
-    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(iotDevice).getExchange(EzvizApi.STATUS,param,JSONObject.class);
-        if(refreshStatus.get("status").equals(1)) {
-            iotDevice.setDevStatus(IotEnumOnlineStatus.ONLINE.getStatus());
-            iotDeviceService.updateIotDevice(iotDevice);
-            log.info("【海康萤石云平台监控】检测设备在线状态,结果:在线,devCode={}",iotDevice.getDevCode());
-            redisCacheManager.setCacheObject(RedisCacheKey.IOT_DEVICE_STATUS,iotDevice.getDevBid(),"1",1, TimeUnit.HOURS);
-            return refreshStatus;
+    public JSONObject refreshStatus(IotDevice iotDevice,List<IotDevice> childDeviceList){
+        JSONObject param = new JSONObject();
+        param.put("deviceSerial", iotDevice.getDevCode());
+        JSONObject refreshResult = (JSONObject) ezvizHttpClient(iotDevice).postExchange(EzvizApi.STATUS, param, JSONObject.class);
+        if (String.valueOf(HttpStatus.OK.value()).equals(refreshResult.get("code"))) {
+            JSONArray result = refreshResult.getJSONArray("data");
+            if (null != result) {
+                Map<String, String> map = new HashMap<>();
+                for (Object resultItemObj : result) {
+                    JSONObject resultItem = JSONObject.from(resultItemObj);
+                    String status = resultItem.getString("status");
+                    String deviceSerial = resultItem.getString("deviceSerial");
+                    String channelNo = resultItem.getString("channelNo");
+                    map.put(deviceSerial + "-" + channelNo, status);
+                }
+                for (IotDevice childDevice : childDeviceList) {
+                    String status = map.get(iotDevice.getDevCode());
+                    if (null != status) {
+                        log.info("【海康萤石云平台监控】更新设备状态,devCode = {},设备状态:{}",childDevice.getDevCode(), IotEnumOnlineStatus.messageOfCode(childDevice.getDevStatus()));
+                        childDevice.setDevStatus(status);
+                    } else {
+                        log.info("【海康萤石云平台监控】更新设备状态,未查询到设备状态信息,视为设备离线 devCode = {}",childDevice.getDevCode());
+                        childDevice.setDevStatus(IotEnumOnlineStatus.OFFLINE.getStatus());
+                    }
+                    if(IotEnumOnlineStatus.ONLINE.getStatus().equals(childDevice.getDevStatus())){
+                        redisCacheManager.setCacheObject(RedisCacheKey.IOT_DEVICE_STATUS,childDevice.getDevBid(),"1",1, TimeUnit.HOURS);
+                    }else {
+                        redisCacheManager.deleteObject(RedisCacheKey.IOT_DEVICE_STATUS,childDevice.getDevBid());
+                    }
+                }
+                iotDeviceService.updateIotDeviceBatch(childDeviceList);
+                return refreshResult;
+            }
         }
-        iotDevice.setDevStatus(IotEnumOnlineStatus.OFFLINE.getStatus());
-        iotDevice.setDevOfflinedate(DateUtils.dateTimeNow());
-        iotDeviceService.updateIotDevice(iotDevice);
-        redisCacheManager.deleteObject(RedisCacheKey.IOT_DEVICE_STATUS,iotDevice.getDevBid());
-        log.info("【海康萤石云平台监控】检测设备在线状态,结果:离线,devCode={}",iotDevice.getDevCode());
-        return refreshStatus;
+        return refreshResult;
     }
 
     @Override
@@ -166,11 +181,17 @@ public class IHikVisionEzvizDeviceImpl extends HttpDeviceAbstractImpl implements
         try {
             log.info("海康设备定时检测设备在线状态开始");
             List<CompletableFuture<JSONObject>> completableFutureList = new LinkedList<>();
+            // 此处若后续数据较多时,可按租户分批处理
             List<IotDevice> iotDeviceList = iotDeviceService.selectAllDeviceByDeviceServiceName(ServiceNameConst.SERVICE_EZVIZ_MINITOR);
-            for(IotDevice iotDevice : iotDeviceList){
+            Map<String,List<IotDevice>> map = iotDeviceList.stream().collect(Collectors.groupingBy(item->item.getDevCode().split("-")[0]));
+            for(Map.Entry<String,List<IotDevice>> entry:map.entrySet()){
                 CompletableFuture<JSONObject> generateGraphics = CompletableFuture.supplyAsync(() -> {
                     try {
-                        return this.refreshStatus(null,iotDevice);
+                        IotDevice iotDevice = new IotDevice();
+                        iotDevice.setDevCode(entry.getKey());
+                        iotDevice.setDevtypeBid(entry.getValue().get(0).getDevtypeBid());
+                        iotDevice.setDevconnBid(entry.getValue().get(0).getDevconnBid());
+                        return this.refreshStatus(iotDevice,entry.getValue());
                     } catch (Exception e) {
                         throw new RuntimeException(e);
                     }

+ 7 - 0
src/main/java/com/yunfeiyun/agmp/iots/mq/listener/IotmBaseDataChannelAwareMessageListener.java

@@ -6,6 +6,7 @@ import com.yunfeiyun.agmp.common.framework.mq.rabbitmq.model.SynGlobalTenantInfo
 import com.yunfeiyun.agmp.common.utils.JSONUtils;
 import com.yunfeiyun.agmp.iot.common.constant.mq.IotActionEnums;
 import com.yunfeiyun.agmp.iot.common.domain.IotDevice;
+import com.yunfeiyun.agmp.iot.common.domain.IotDeviceconn;
 import com.yunfeiyun.agmp.iot.common.model.cmd.CmdGroupModel;
 import com.yunfeiyun.agmp.iot.common.model.cmd.CmdModel;
 import com.yunfeiyun.agmp.iot.common.model.mq.IotDeviceEditMqModel;
@@ -77,20 +78,26 @@ public class IotmBaseDataChannelAwareMessageListener implements ChannelAwareMess
                         break;
                     //设备连接信息创建
                     case DEVICE_COON_CREATE:
+                        connectionManager.createIotDeviceconnHandle(synGlobalTenantInfoDto.getData().to(IotDeviceconn.class));
                         break;
                     //设备连接信息更新
                     case DEVICE_COON_UPDATE:
+                        connectionManager.editIotDeviceconnHandle(synGlobalTenantInfoDto.getData().to(IotDeviceconn.class));
                         break;
                     //设备连接信息删除
                     case DEVICE_COON_DELETE:
+                        connectionManager.deleteIotDeviceconnHandle(synGlobalTenantInfoDto.getData().to(IotDeviceconn.class));
                         break;
                     //更新所有设备信息
                     case DEVICE_ALL_SYN:
+
                         break;
                     //测报灯重新识别
                     case DEVICE_CBD_AGAIN_RECORD:
                         iotCbdImgService.iotmAgainRecog(synGlobalTenantInfoDto.getData().toString());
                         break;
+
+
                     default:
                         break;
                 }

+ 1 - 4
src/main/java/com/yunfeiyun/agmp/iots/service/impl/IotDeviceServiceImpl.java

@@ -14,10 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 
 
 /**