Fork me on GitHub
.net求学者

海康8700视频调用

公共类

using Common;
using Model;
using SQLServerDAL;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace MainWeb.Video.GlobalClass
{
    public class APIHelper
    {
        /// <summary>
        /// post请求:json数据提交
        /// </summary>
        /// <param name="sUrl"></param>
        /// <param name="sJsonData"></param>
        /// <returns></returns>
        public static string Post(string sUrl, string sJsonData)
        {
            // Json不能为空
            if (sJsonData == null) sJsonData = string.Empty;
            string srcStr = sUrl + sJsonData + SysDefault.secret;
            string token = Md5_32(srcStr);//接口地址(不带域名/a/b)+参数json+secret 进行md5加密32位
            sUrl = "http://" + SysDefault.IP + sUrl + "?token=" + token;
            Uri url = new Uri(sUrl);

            HttpWebRequest request = WebRequest.Create(sUrl) as HttpWebRequest;
            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Timeout = 1000 * 120;
            //提交数据获取返回结果
            string strResult = string.Empty;
            request.Method = "POST";
            request.ContentType = "application/json";
            byte[] data = UTF8Encoding.UTF8.GetBytes(sJsonData);
            request.ContentLength = data.LongLength;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();
                requestStream.Dispose();
            }
            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response != null)
                {
                    using (Stream bookmarksStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(bookmarksStream, UTF8Encoding.UTF8);
                        strResult = reader.ReadToEnd();
                        reader.Close();
                        bookmarksStream.Close();
                        bookmarksStream.Dispose();
                    }
                }
            }
            catch
            { }
            return strResult;
        }

        /// <summary>
        /// 获取默认用户的UUID:后台调用接口
        /// </summary>
        /// <returns></returns>
        public static void  GetDefaultUUID()
        {
            SysParamData pd = new SysParamData();
            string json = JsonHelper.GetJson(pd);
            string retjson = Post(SysDefault.getDefaultUserUuind_Url, json);
            if (!string.IsNullOrEmpty(retjson))
            {
                DefaultUUIDData ud = JsonHelper.JSONString<DefaultUUIDData>(retjson);
                if (!string.IsNullOrEmpty(ud.data))
                {
                    SysDefault.DefaultUserID = ud.data;
                }
            }
        }

        /// <summary>
        /// 获取网域信息
        /// </summary>
        public static void GetnetZoneData()
        {
            InNetZoneParam zone = new InNetZoneParam();
            if (string.IsNullOrEmpty(SysDefault.DefaultUserID))
            {
                GetDefaultUUID();
            }
            zone.opUserUuid = SysDefault.DefaultUserID;
            string json = JsonHelper.GetJson(zone);
            string retjson = Post(SysDefault.getNetZone_Url, json);
            if (!string.IsNullOrEmpty(retjson))
            {
                OutNetZoneParam ret = JsonHelper.JSONString<OutNetZoneParam>(retjson);
                if (ret.data != null && ret.data.Count > 0)
                {
                    string[] split = SysDefault.IP.Split(new string[1] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                    string ipv=split[0];
                    bool isok = false;
                    foreach (ZoneData zd in ret.data)
                    {
                        if (ipv == zd.netZoneName)// 自身平台ip=视频网域名称匹配
                        {
                            isok = true;
                            SysDefault.netZoneUuid = zd.netZoneUuid;
                            SysDefault.netZoneName = zd.netZoneName;
                            break;
                        }
                    }
                    if (!isok)//没有设置对应的  读取第一个
                    {
                        SysDefault.netZoneUuid = ret.data[0].netZoneUuid;
                        SysDefault.netZoneName = ret.data[0].netZoneName;
                    }
                }
            }
        }

        /// <summary>
        /// MD5 32位加密:大写
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5_32(string str)
        {
            byte[] sor = Encoding.UTF8.GetBytes(str);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位

            }
            return strbul.ToString().ToUpper();

        }

        /// <summary>
        /// 视频类型编码
        /// </summary>
        public static string PlatformID = "hik8700";

        /// <summary>
        /// 默认加载初始数据:页面Pageload调用
        /// </summary>
        public static void DefaultLoadData()
        {
            IList<T_VideoPlatformInfo> vPlatform = new T_VideoPlatformDAL().GetByID(PlatformID);
            if (vPlatform.Count > 0)
            {
                SysDefault.IP = vPlatform[0].AccessIP;
                SysDefault.appkey = vPlatform[0].CagUser;
                SysDefault.secret = vPlatform[0].CagPass;
                if (vPlatform[0].AccessPort.HasValue)
                {
                    SysDefault.IP += ":" + vPlatform[0].AccessPort;
                }
            }
        }

        /// <summary>
        /// 根据编码设备名称获取编码设备
        /// </summary>
        /// <param name="name">设备名称</param>
        /// <param name="no">当前页码</param>
        /// <returns></returns>
        public static OutEncoderDevicesByNameExData GetEncoderDevicesByNameEx(string name, int no)
        {
            InEncoderDevicesByNameExParam param = new InEncoderDevicesByNameExParam();
            param.pageNo = no;
            param.pageSize = 300;//建议400以下,不超过1000
            param.encoderName = name;
            param.opUserUuid = SysDefault.DefaultUserID;
            string json = JsonHelper.GetJson(param);
            string retjson = Post(SysDefault.GetEncoderDevicesByNameEx_Url, json);
            OutEncoderDevicesByNameExData ret=null;
            if (!string.IsNullOrEmpty(retjson))
            {
                ret = JsonHelper.JSONString<OutEncoderDevicesByNameExData>(retjson);
            }
            return ret;
        }

        /// <summary>
        /// 通过名称分页查询,找到设备尸体
        /// </summary>
        /// <param name="name">设备名称</param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static DevicesData SearchDevices(string name,string code)
        {
            bool breakflag = true;
            DevicesData ret= null;
            int pageNo = 1;//从第一页开始
            while (breakflag)
            {
                OutEncoderDevicesByNameExData data = GetEncoderDevicesByNameEx(name, pageNo);
                if (data.errorCode == 0)
                {
                    foreach (DevicesData t in data.data.list)
                    {
                        if (t.encoderUuid == code)
                        {
                            ret = t;
                            breakflag = false;
                            break;
                        }
                    }
                    if (ret == null)
                    {
                        pageNo++;
                    }
                }
                else
                {
                    breakflag = false;
                    break;
                }
            }
            return ret;
        }


        /// <summary>
        /// 根据编码设备UUID集分页获取监控点
        /// </summary>
        /// <param name="uuids">设备uuid,多个用,号隔开</param>
        /// <param name="no">当前页码</param>
        /// <returns></returns>
        public static OutCamerasByEncoderUuidsData GetCamerasByEncoderUuids(string uuids,int no)
        {
            InCamerasByEncoderUuidsParam param = new InCamerasByEncoderUuidsParam();
            param.pageNo = no;
            param.pageSize = 300;//建议400以下,不超过1000
            param.encoderUuids = uuids;
            param.opUserUuid = SysDefault.DefaultUserID;
            string json = JsonHelper.GetJson(param);
            string retjson = Post(SysDefault.GetCamerasByEncoderUuids_Url, json);
            OutCamerasByEncoderUuidsData ret = null;
            if (!string.IsNullOrEmpty(retjson))
            {
                ret = JsonHelper.JSONString<OutCamerasByEncoderUuidsData>(retjson);
            }
            return ret;
        }

        /// <summary>
        /// 根据编码设备UUID得到所有信息
        /// </summary>
        /// <param name="uuids">设备uuid,多个用,号隔开</param>
        /// <returns></returns>
        public static List<CamerasData> GetCameras(string uuids)
        {
            List<CamerasData> ret = new List<CamerasData>();
            int pageNo=1;
            bool breakflag = true;
            while (breakflag)
            {
                OutCamerasByEncoderUuidsData data = GetCamerasByEncoderUuids(uuids,pageNo);
                if (data.errorCode == 0)
                {
                    foreach (CamerasData t in data.data.list)
                    {
                        ret.Add(t);
                    }
                    if (pageNo < data.data.pageNo)
                    {
                        pageNo++;
                    }
                    else
                    {
                        breakflag = false;
                        break;
                    }
                }
                else
                {
                    breakflag = false;
                    break;
                }
            }
            return ret;
            
        }

        /// <summary>
        /// 根据视频机器的uuid预览视频
        /// </summary>
        /// <param name="uuid">视频机器的uuid</param>
        /// <returns></returns>
        public static string GetVideoPreview(string uuid)
        {
            InCameraPreviewParam pre = new InCameraPreviewParam();
            pre.opUserUuid = SysDefault.DefaultUserID;
            pre.netZoneUuid = SysDefault.netZoneUuid;
            pre.cameraUuid = uuid;
            string json = JsonHelper.GetJson(pre);
            string retjson = Post(SysDefault.GetPreviewParamByCameraUuid_Url, json);
            string ret = null;
            if (!string.IsNullOrEmpty(retjson))
            {
                ret = retjson;// JsonHelper.JSONString<OutCameraPreviewData>(retjson);
            }
            return ret;
        }

        /// <summary>
        /// 根据监控点UUID集和网域UUID分页获取录像计划
        /// </summary>
        /// <param name="uuid">视频机器的uuid,多个用,号隔开</param>
        /// <returns></returns>
        public static OutPlansByCameraUuids GetRecordPlansByCameraUuids(string uuid)
        {
             InPlansByCameraUuidsParam param = new InPlansByCameraUuidsParam();
             param.pageNo = 1;
             param.pageSize = 300;
             param.opUserUuid = SysDefault.DefaultUserID;
             param.cameraUuids = uuid;
             param.netZoneUuid = SysDefault.netZoneUuid;
             string json = JsonHelper.GetJson(param);
             string retjson = Post(SysDefault.GetRecordPlansByCameraUuids_Url, json);
             OutPlansByCameraUuids ret = null;
             if (!string.IsNullOrEmpty(retjson))
             {
                 ret = JsonHelper.JSONString<OutPlansByCameraUuids>(retjson);
             }
             return ret;
        }

        /// <summary>
        /// 根据监控点UUID集和网域UUID分页获取录像计划
        /// </summary>
        /// <param name="uuid">视频机器的uuid,多个用,号隔开</param>
        /// <returns></returns>
        public static List<PalnsData> GetCameraPlan(string uuid)
        {
            List<PalnsData> ret = new List<PalnsData>();
            int pageNo = 1;
            bool breakflag = true;
            while (breakflag)
            {
                OutPlansByCameraUuids data = GetRecordPlansByCameraUuids(uuid);
                if (data.errorCode == 0)
                {
                    foreach (PalnsData t in data.data.list)
                    {
                        ret.Add(t);
                    }
                    if (pageNo < data.data.pageNo)
                    {
                        pageNo++;
                    }
                    else
                    {
                        breakflag = false;
                        break;
                    }
                }
                else
                {
                    breakflag = false;
                    break;
                }
            }
            return ret;
        }

       
        /// <summary>
        /// 视频回放
        /// </summary>
        /// <param name="plantype">录像计划类型</param>
        /// <param name="planid">录像计划id</param>
        /// <returns></returns>
        public static string GetVideoBack(string plantype, string planid)
        {
            InGetPlaybackParamByPlanUuidParam pre = new InGetPlaybackParamByPlanUuidParam();
            pre.opUserUuid = SysDefault.DefaultUserID;
            pre.netZoneUuid = SysDefault.netZoneUuid;
            pre.planType = Convert.ToInt32(plantype);
            pre.recordPlanUuid = planid;
            string json = JsonHelper.GetJson(pre);
            string retjson = Post(SysDefault.GetPlaybackParamByPlanUuid_Url, json);
            string ret = null;
            if (!string.IsNullOrEmpty(retjson))
            {
                ret = retjson;// JsonHelper.JSONString<OutPlaybackParamByPlanData>(retjson);
            }
            return ret;
        }
    }
}

页面--引用JQuery、EasyUI

public partial class VideoMulitHk8700 : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                APIHelper.DefaultLoadData();//加载默认信息
                APIHelper.GetDefaultUUID();//控制用户-默认
                APIHelper.GetnetZoneData();//网域信息
                // APIHelper.SearchDevices("鹿角", "A4306000002");//--设备编号=encoderUuid
                string strMN = "";
                if (Request["MN"] == null)
                {
                    strMN = GetMN;
                }
                else
                {
                    strMN = Request["MN"].ToString();
                }
                this.hfmn.Value = strMN;
                this.hfuserid.Value = this.LoginUserInfo.UserInfoID;
                this.hfip.Value = SysDefault.IP;
            }
        }

    }
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>视频8700</title>
<script src="/Video/Scripts/VideoHK8700.js" type="text/javascript"></script>
     <style type="text/css">
        .leftTree {
            border: 1px solid #F5F5F5;
            float: left;
            width: 15%;
            overflow: hidden;
            text-wrap: none;
            word-break: keep-all;
            white-space: nowrap;
            text-overflow: ellipsis;
            border-right: 5px solid #F3F3F3;
            background-color: white;
        }

        .leftEdit {
            width: 84.5%;
            float: left;
            /*background-color: white;*/
        }
         ul li {
             margin-left:4px;
         }
      </style>
</head>
<body>
    <form id="form1" runat="server">
       <asp:HiddenField ID="hfmn"  runat="server" />
       <asp:HiddenField ID="hfuserid"  runat="server" />
        <asp:HiddenField ID="hfip"  runat="server" />
       <div class="leftTree">
            <ul id="tree1" class="tree" style="margin-top:5px;">

             </ul>
     
       </div>
        <div class="leftEdit">
            <div class="ActiveX" style="margin-left:10px;">
                <object classid="clsid:9ECD2A40-1222-432E-A4D4-154C7CAB9DE3" id="spv"   />
        </div>
         </div>
    </form>
</body>
</html>

VideoHK8700.js

$(function () {
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
        try {
            var obj = new ActiveXObject("CAMERACONFIGOCX.CameraConfigOCXCtrl.1");
            //已经注册
            loadtree();
        }
        catch (e) {
            installPlug();
            return;
        }
       
    }
    else {
        showTipsMsg('请选用IE加载视频!', '2500', '5')
    }
});

function installPlug() {
    showConfirmMsg("您还没有安装浏览该视频的插件!是否进行安装?安装成功后请重新启动IE!", function fc() {
        var xip = $("#hfip").val();
        location.href = "http://" + xip + "/views/home/file/cmsocx.exe";
    });

}

    //设置滚动条的显示与隐藏
$(document).ready(function () {
    $(".leftTree").hover(function () {
        $(this).css("overflow", "scroll");
    }, function () {
        $(this).css("overflow", "hidden");
    });
    var curWidth = $(window).width();
    var curHeight = $(window).height();
    $(".leftTree").height(curHeight - 20);
    $(".leftEdit").width(curWidth - $(".leftTree").width() - 12);
    $("#spv").width(curWidth - $(".leftTree").width() - 20);
    $("#spv").height(curHeight - 20);
});


function loadtree() {
    var MN = $("#hfmn").val();
    var userid = $("#hfuserid").val();
    $.ajax({
        type: 'POST',
        url: '/Video/Ajax/GetInfo8700.ashx',
        data: { "action": "LoadTree", "MN": MN, "userid": userid },
        success: function (data) {
            if (data != null && data != "") {
                var jsonData = eval('(' + data + ')');
                $('#tree1').tree({
                    data: jsonData,
                    onClick: function (node) {
                        //节点事件
                        addvideo(node.id);
                    },
                    onLoadSuccess: function (node, data) {
                        //加载视屏
                        if (data != null)
                        {
                            InitSpvx();//初始化
                            SetLocalParam();//本地参数
                            isopenvideo = true;
                        }
                       
                    }
                });
            }
        }
    });
}

function addvideo(cameraUuid) {
    $.ajax({
        type: 'POST',
        url: '/Video/Ajax/GetInfo8700.ashx',
        data: { "action": "LoadVideo", "cameraUuid": cameraUuid },
        success: function (xml) {
            if (xml != null && xml != "") {
                var jsonData = eval('(' + xml + ')');
                if (jsonData.data != "") {
                    var spvxOcx = document.getElementById("spv");
                    var ret = spvxOcx.MPV_StartPreview(jsonData.data);
                    if (ret != 0) {
                        alert("预览失败");
                    }
                }
                else {
                    alert("查询预览参数失败");
                }
            }
        }
    });
}


function InitSpvx() {
    var ocxObj = document.getElementById("spv");
    var languageType = 1;
    var ret = ocxObj.MPV_Init(languageType);
    if (ret != 0) {
        alert("初始化失败");
    }
}
function stopAllPreview() {
    var ocxObj = document.getElementById("spv");
    var ret = ocxObj.MPV_StopAllPreview();
    if (ret != 0) {
        alert("停止所有预览失败");
    }
}

function UninitSpvx() {
    var ocxObj = document.getElementById("spv");
    var ret = ocxObj.MPV_Uninit();
    if (ret != 0) {
        alert("反初始化失败");
    }
}

function SetLocalParam() {
    var ocxObj = document.getElementById("spv");
    var devPxRa = screen.deviceXDPI / screen.logicalXDPI;
    var height = $('#spv').height() * devPxRa;
    var width = $('#spv').width() * devPxRa;
    var xml = '<?xml version="1.0" encoding="UTF-8"?> ' +
        '<localParam> ' +
        '<width>' + width + '</width> ' +
        '<height>' + height + '</height> ' +
        '<picType>1</picType> ' +
        '<capturePath>C:\\Hikvision</capturePath> ' +
        '<recordSize>2</recordSize> ' +
        '<recordPath>C:\\Hikvision</recordPath> ' +
        '<limitPreviewTime>0</limitPreviewTime> ' +
        '</localParam>';
    var ret = ocxObj.MPV_SetLocalParam(xml);
    if (ret != 0) {
        alert("设置本地参数失败");
    }
}


    var isopenvideo = false;

    window.onbeforeunload = function (e) {
        if (isopenvideo) {
            //页面离开  还原
            stopAllPreview();
            UninitSpvx();
            isopenvideo = false;
        }
    }

 

 

/****视频回看****/

页面--后台代码与前面查看实时视频一致

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>视频8700回放</title><script src="/Video/Scripts/VideoHK8700Back.js" type="text/javascript"></script>
     <style type="text/css">
        .leftTree {
            border: 1px solid #F5F5F5;
            float: left;
            width: 15%;
            overflow: hidden;
            text-wrap: none;
            word-break: keep-all;
            white-space: nowrap;
            text-overflow: ellipsis;
            border-right: 5px solid #F3F3F3;
            background-color: white;
        }

        .leftEdit {
            width: 84.5%;
            float: left;
            /*background-color: white;*/
        }
         ul li {
             margin-left:4px;
         }
      </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:HiddenField ID="hfmn"  runat="server" />
       <asp:HiddenField ID="hfuserid"  runat="server" />
        <asp:HiddenField ID="hfip"  runat="server" />
       <div class="leftTree">
            <ul id="tree1" class="tree" style="margin-top:5px;">

             </ul>
     
       </div>
        <div class="leftEdit">
            <div id="divFind" class="containerbox">
                          <div class="grid_4 lbl">
                              开始时间:
                          </div>
                          <div class="grid_10 val" >
                            <input type="text" id="sTime" style="width:140px;" readonly="readonly" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" class="z-txt  easyui-validatebox grid_10 val" />
                          </div>
                         <div class="grid_4 lbl">
                              结束时间:
                          </div>
                          <div class="grid_10 val" >
                            <input type="text" id="eTime"readonly="readonly" style="width:140px;" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" class="z-txt  easyui-validatebox grid_10 val" />
                          </div>
                         <div class="grid_8 val" style="width:80px;">
                             <input type="button" class="btnSearch" value="回 放" onclick="search();" />
                         </div>
                   </div>
            <div class="ActiveX" >
                <object classid="clsid:863E7B58-A280-40A5-8394-CE33F4E7B654" id="spb"   />
        </div>
         </div>
    </form>
</body>
</html>

 

posted @ 2019-01-04 15:20  hy31337  阅读(3128)  评论(0编辑  收藏  举报
.net求学者