上次我们已经提到海康ISC平台的应用,详见在vue项目中实现海康威视ISC平台(实时和回放)
这次记录下海康云眸平台的应用,风格与上一篇文章保持一致,方便食用。

环境

先下载安装海康插件HikOpenServicePlugin.exe

代码分享

index.html

<!-- 海康威视iot插件 -->
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js"></script>
<script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>

视频组件

也是将IOT的视频模块单独做成一个组件,以后可以按需加入不同项目。(以实时为例,回放同理)

<template>
  <div>
    <div id="playWnd" style="width: 700px;height:500px;"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      oWebControl: null,
      myAxios: axios.create({
        timeout: 20000,
        withCredentials: true,
        transformRequest: [
          function(data) {
            let ret = "";
            for (let i in data) {
              ret +=
                encodeURIComponent(i) + "=" + encodeURIComponent(data[i]) + "&";
            }
            return ret;
          }
        ]
      }),
      client_id: "XXXXXXXXX",
      client_secret: "XXXXXXXXX",
      accessToken: "",
      switchVideo: 0, // 0实时预览 1录像回放
      appKey: "",
      token: "",
      callbackMessage: "", //显示回调信息
      tips: "调用成功",
      successTip: false,
      tipsShow: false,
      IOTPlayData: ""
    };
  },
  props: ["IOTdata"],
  created() {},
  mounted() {
    this.oWebControl = this.WebControlInit(
      "playWnd",
      this.cbConnectSuccess,
      this.cbConnectError,
      this.cbConnectClose
    );
  },
  beforeDestroy() {
    try {
      this.oWebControl.JS_HideWnd();
      this.WebControlDistory();
    } catch (error) {
      console.error(error);
    }
  },
  watch: {
    IOTdata: function(newVal, oldVal) {
      this.IOTPlayData = newVal;
      this.playVideo();
    }
  },
  methods: {
    /**
     * 获取accessToken
     */
    getAccessToken() {
      this.myAxios
        .post("/test/api/oauth/token", {
          client_secret: this.client_secret,
          client_id: this.client_id,
          grant_type: "client_credentials",
          scope: ""
        })
        .then(response => {
          this.accessToken = response.data.access_token;
          this.getVideoToken();
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    /**
     * 获取萤石token
     */
    getVideoToken() {
      this.myAxios({
        url: "/test/api/v1/ezviz/account/info",
        method: "get",
        headers: {
          Authorization: "Bearer " + this.accessToken
        }
      })
        .then(response => {
          let data = response.data.data;

          this.textarea =
            "appKey:  " + data.appKey + ",\n" + "token:  " + data.token;
          this.appKey = data.appKey;
          this.token = data.token;
          this.showTips(true, response.data.message);
          this.initVideo();
        })
        .catch(error => {
          console.log(error);
          this.showTips(false, response.data.message);
        });
    },
    WebControlInit(id, cbConnectSuccess, cbConnectError, cbConnectClose) {
      return new WebControl({
        szPluginContainer: id,
        iServicePortStart: 14550, // 对应 LocalServiceConfig.xml 中的ServicePortStart值
        iServicePortEnd: 14559, // 对应 LocalServiceConfig.xml 中的ServicePortEnd值
        cbConnectSuccess,
        cbConnectError,
        cbConnectClose
      });
    },
    // 监听视频控件的事件
    cbIntegrationCallBack(oData) {
      console.log(oData.responseMsg);

      if (oData.responseMsg.eventName === "FireInitResult") {
        // 初始化事件
      } else if (oData.responseMsg.eventName === "FireTransFunction") {
        let requestObj = oData.responseMsg.arguments.request;
        console.log(requestObj, "requestObj");
        let { url, method, body } = requestObj;
        let params = {};
        let data = {};
        method.toLowerCase() === "get" ? (params = body) : (data = body);
        this.myAxios({
          url: "/test/api/v1" + url,
          method: method.toLowerCase(),
          headers: {
            Authorization: "Bearer " + this.accessToken
          },
          params,
          data
        }).then(res => {
          let argumentsD = {
            request: requestObj,
            response: res
          };
          oWebControl
            .JS_RequestInterface({
              funcName: "TransFunctionResult",
              argumentsD
            })
            .then(oData => {
              console.log(oData);
            });
        });
      }
    },
    cbConnectSuccess() {
      // 设置窗口控制回调
      this.oWebControl.JS_SetWindowControlCallback({
        cbIntegrationCallBack: this.cbIntegrationCallBack
      });
      //创建视频窗口
      this.oWebControl
        .JS_StartService("window", {
          dllPath: "./chain/cloudTransform.dll"
        })
        .then(() => {
          this.oWebControl
            .JS_CreateWnd("playWnd", 700, 500)
            .then(() => {
              console.log("JS_CreateWnd success");
              this.getAccessToken();
            })
            .catch(err => {
              console.log(err);
            });
        });
    },
    cbConnectError() {
      console.log("cbConnectError");
      this.oWebControl = null;
      console.error("确认本地进程是否已安装并开启成功!");
    },
    cbConnectClose(bNormalClose) {
      // 连接异常断开:bNormalClose = false
      // JS_Disconnect正常断开:bNormalClose = true
      console.log("cbConnectClose");
      this.oWebControl = null;
    },
    //销毁视频控件
    WebControlDistory() {
      // var bIE = !!window.ActiveXObject || 'ActiveXObject' in window // 是否为IE浏览器
      if (this.oWebControl != null) {
        this.oWebControl.JS_DestroyWnd().then(
          function() {
            console.log("JS_DestroyWnd");
          },
          function() {}
        );
        this.oWebControl.JS_StopService("window").then(()=> {
          this.oWebControl.JS_Disconnect().then(
            function() {
              console.log("JS_Disconnect");
            },
            function() {}
          );
        });
      }
    },
    /**
     * 设置视频初始化参数
     */
    initVideo() {
      if (this.oWebControl) {
        let initJson = {
          funcName: "Init",
          arguments: {
            type: "chain",
            initModel: 0,
            response: {}
          }
        };
        initJson.arguments.response.data = {
          appKey: this.appKey,
          ezvizToken: this.token,
          videoLevel: 0,
          uploadUrl: "uploadUrl",
          accessKeyId: "accessKeyId",
          accessKeySecret: "accessKeySecret",
          accessToken: "accessToken",
          bucket: "bucket",
          object: "object"
        };
        initJson.arguments = encodeURI(JSON.stringify(initJson.arguments));
        this.oWebControl
          .JS_RequestInterface(initJson)
          .then(oData => {
            this.showCBInfo(oData.responseMsg);
            this.showTips(true, "视频初始化成功!");
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    /**
     * 播放门店视频
     */
    playVideo() {
      let data = null;
      data = this.IOTPlayData;
      this.oWebControl
        .JS_RequestInterface({
          funcName: "StartPreview",
          arguments: encodeURI(
            JSON.stringify({
              response: {
                code: 0,
                message: null,
                data: data
              }
            })
          )
        })
        .then(oData => {
          console.log(JSON.stringify(oData.responseMsg));
          this.showCBInfo(oData.responseMsg);
        })
        .catch(err => {
          console.log(err);
        });
    },
    /**
     * 设置事件回调信息
     */
    showCBInfo(message) {
      this.callbackMessage =
        this.callbackMessage + JSON.stringify(message) + "\n";
    },
    showTips(status, message) {
      let self = this;
      this.successTip = status;
      this.tips = message;
      this.tipsShow = true;
      setTimeout(() => {
        self.tipsShow = false;
      }, 1000);
    }
  }
};
</script>

需要注意的是,不能只取最后需要的appkey和token,所有包括accessToken都必须由前端去获取。否则eventName会一直是FireInitResult,进不了下一步,也无法显示图像。

成果

根据左侧生成的摄像头设备树,点击去获取设备的信息,并且需要对传入的data进行如下的格式处理:
在这里插入图片描述
将数据传入data。

这样就可以看到摄像头画面了!
成果描述

Logo

前往低代码交流专区

更多推荐