关于海康威视视频插件的踩坑之路

6,278 阅读5分钟

       刚入职新公司,接手的第一个项目中就有之前没有做过的视频监控的问题,内心是有点期待也有些无奈的,毕竟要给领导留个好印象却又害怕做不好。

       根据同事的介绍得知这个视频插件用的是海康威视的插件,下面就跟大家说一下海康威视插件的用法:

<script src="jquery-1.12.4.min.js"></script>
<script src="jsencrypt.min.js"></script>
<script src="jsWebControl-1.0.0.min.js"></script>

html部分:
<div id="playWnd" class="playWnd"></div>
    <div id="operate" class="operate">
        <div class="module">
            <div class="item"><span class="label">appkey:</span><input id="appkey" type="text"></div>
            <div class="item"><span class="label">secret:</span><input id="secret" type="text"></div>
            <div class="item"><span class="label">API网关IP地址:</span><input id="ip" type="text"></div>
			<div class="item">
				<span class="label">是否启用HTTPS协议</span>
				<select id="isHttps" onchange="UpdateValue()" value="不启用">
					<option value="0" selected>不启用</option>
                    <option value="1">启用</option>
				</select>
			</div>
            <div class="item"><span class="label">API网关端口:</span><input id="port" value="80" type="text"></div>
            <div class="item"><span class="label">抓图存储路径:</span><input id="snapDir" type="text" value="D:\SnapDir"></div>
            <div class="item">
                <span class="label">初始化布局:</span>
                <select id="layout" value="2x2">
                    <option value="1x1">1x1</option>
                    <option value="2x2" selected>2x2</option>
                    <option value="3x3">3x3</option>
                    <option value="4x4">4x4</option>
                </select>
            </div>
            <div class="item">
                <span class="label">加密字段:</span>
                <div style="display: inline-block; vertical-align: top;">
                    <label><input type="checkbox" value="secret" disabled checked>secret</label><br>
                    <label><input class="encryptedFields" type="checkbox" value="appkey">appkey</label><br>
                    <label><input class="encryptedFields" type="checkbox" value="ip">ip</label><br>
                    <label><input class="encryptedFields" type="checkbox" value="snapDir">抓图路径</label><br>
                    <label><input class="encryptedFields" type="checkbox" value="layout">布局</label>
                </div>
            </div>
            <div class="item"><button id="init" class="btn">初始化</button></div>
        </div>
        <div class="module">
            <div class="item"><span class="label">监控点编号:</span><input id="cameraIndexCode" type="text"></div>
            <div class="item">
                <span class="label">主子码流标识:</span>
                <select id="streamMode" value="0">
                    <option value="0">主码流</option>
                    <option value="1">子码流</option>
                </select>
            </div>
            <div class="item">
                <span class="label">传输协议:</span>
                <select id="transMode" value="1">
                    <option value="1">TCP</option>
                    <option value="0">UDP</option>
                </select>
            </div>
            <div class="item">
                <span class="label">是否启用GPU硬解:</span>
                <select id="gpuMode" value="0">
                    <option value="0">不启用</option>
                    <option value="1">启用</option>
                </select>
            </div>
            <div class="item"><button id="startPreview" class="btn">预览</button></div>
            <div class="item"><button id="stopAllPreview" class="btn">停止全部预览</button></div>
            <div class="item"><button id="uninit" class="btn">反初始化</button></div>
        </div>
        <fieldset class="cbInfoDiv">
            <legend>返回值信息</legend>
            <div id="cbInfo" class="cbInfo"></div>
            <button id="clear">清空</button>
        </fieldset>
    </div>
js部分:    
    var oWebControl = null;// 插件对象
    var bIE = (!!window.ActiveXObject || 'ActiveXObject' in window);// 是否为IE浏览器
    var pubKey = '';

    var iLastCoverLeft = 0;
    var iLastCoverTop = 0;
    var iLastCoverRight = 0;
    var iLastCoverBottom = 0;
	var initCount = 0;

    console.log('1')
    // 标签关闭
    $(window).unload(function () {
        if (oWebControl != null){
                oWebControl.JS_Disconnect().then(function(){}, function() {});
            }
    });

    // 窗口resize
    $(window).resize(function () {
        if (oWebControl != null) {
            oWebControl.JS_Resize(600, 400);
            setWndCover();
        }
    });

    // 滚动条scroll
    $(window).scroll(function () {
        if (oWebControl != null) {
            oWebControl.JS_Resize(600, 400);
            setWndCover();
        }
    });

    // 设置窗口遮挡
    function setWndCover() {
        console.log('设置窗口遮挡')
        var iWidth = $(window).width();
        var iHeight = $(window).height();
        var oDivRect = $("#playWnd").get(0).getBoundingClientRect();

        var iCoverLeft = (oDivRect.left < 0) ? Math.abs(oDivRect.left): 0;
        var iCoverTop = (oDivRect.top < 0) ? Math.abs(oDivRect.top): 0;
        var iCoverRight = (oDivRect.right - iWidth > 0) ? Math.round(oDivRect.right - iWidth) : 0;
        var iCoverBottom = (oDivRect.bottom - iHeight > 0) ? Math.round(oDivRect.bottom - iHeight) : 0;

        iCoverLeft = (iCoverLeft > 600) ? 600 : iCoverLeft;
        iCoverTop = (iCoverTop > 400) ? 400 : iCoverTop;
        iCoverRight = (iCoverRight > 600) ? 600 : iCoverRight;
        iCoverBottom = (iCoverBottom > 400) ? 400 : iCoverBottom;

        if (iLastCoverLeft != iCoverLeft) {
            console.log("iCoverLeft: " + iCoverLeft);
            iLastCoverLeft = iCoverLeft;
            oWebControl.JS_SetWndCover("left", iCoverLeft);
        }
        if (iLastCoverTop != iCoverTop) {
            console.log("iCoverTop: " + iCoverTop);
            iLastCoverTop = iCoverTop;
            oWebControl.JS_SetWndCover("top", iCoverTop);
        }
        if (iLastCoverRight != iCoverRight) {
            console.log("iCoverRight: " + iCoverRight);
            iLastCoverRight = iCoverRight;
            oWebControl.JS_SetWndCover("right", iCoverRight);
        }
        if (iLastCoverBottom != iCoverBottom) {
            console.log("iCoverBottom: " + iCoverBottom);
            iLastCoverBottom = iCoverBottom;
            oWebControl.JS_SetWndCover("bottom", iCoverBottom);
        }
    }
	
	function UpdateValue()
	{
		var sel = document.getElementById("isHttps");
		var selectedId = sel.selectedIndex;
		var v = sel.options[selectedId].value;
		if (0 == v)
		{
			document.getElementById("port").value = 80;
		}
		else
		{
			document.getElementById("port").value = 443;
		}						
	}
	
    // 初始化插件
	function initPlugin () {
        console.log('初始化插件')
		$("#init").attr('disabled', false);
		$("#startPreview").attr('disabled', false);
	    $("#stopAllPreview").attr('disabled', false);
	    $("#uninit").attr('disabled', false);
		oWebControl = new WebControl({
			szPluginContainer: "playWnd",
			iServicePortStart: 15900,
			iServicePortEnd: 15909,
			cbConnectSuccess: function () {
				setCallbacks();
                console.log('初始化插件setCallbacks')

				oWebControl.JS_StartService("window", {
					dllPath: "./VideoPluginConnect.dll"
					//dllPath: "./DllForTest-Win32.dll"
				}).then(function () {
					oWebControl.JS_CreateWnd("playWnd", 600, 400).then(function () {
                        // console.log('初始化插件setCallbacks')
						console.log("JS_CreateWnd success");
						$("#init").attr('disabled', false);
						$("#startPreview").attr('disabled', false);
						$("#stopAllPreview").attr('disabled', false);
						$("#uninit").attr('disabled', false);
					});
				}, function () {
				
				});
			},
			cbConnectError: function () {
				console.log("cbConnectError");
				oWebControl = null;
				$("#playWnd").html("插件未启动,正在尝试启动,请稍候...");
				WebControl.JS_WakeUp("VideoWebPlugin://");
				initCount ++;
				if (initCount < 3) {
					setTimeout(function () {
						initPlugin();
					}, 3000)
				} else {
					$("#playWnd").html("插件启动失败,请检查插件是否安装!");
				}
			},
			cbConnectClose: function () {
				console.log("cbConnectClose");
				oWebControl = null;
			}
		});
	}
	
	initPlugin();

  
    

    // 获取公钥
    function getPubKey (callback) {
        oWebControl.JS_RequestInterface({
            funcName: "getRSAPubKey",
            argument: JSON.stringify({
                keyLength: 1024
            })
        }).then(function (oData) {
            console.log(oData)
            if (oData.responseMsg.data) {
                pubKey = oData.responseMsg.data
                callback()
            }
        })
    }

    // 设置窗口控制回调
    function setCallbacks() {
        oWebControl.JS_SetWindowControlCallback({
            cbIntegrationCallBack: cbIntegrationCallBack
        });
    }

    // 推送消息
    function cbIntegrationCallBack(oData) {
        showCBInfo(JSON.stringify(oData.responseMsg));
    }

    // RSA加密
    function setEncrypt (value) {
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(pubKey);
        return encrypt.encrypt(value);
    }

    // 初始化
    $("#init").click(function () {
        getPubKey(function () {
            console.log('初始化')
            var appkey = $("#appkey").val();
            var secret = setEncrypt($("#secret").val());
            var ip = $("#ip").val();
            var port = parseInt($("#port").val());
            var snapDir = $("#snapDir").val();
            var layout = $("#layout").val();
            var encryptedFields = ['secret'];
			var enableHttps = parseInt($("#isHttps").val());
            $(".encryptedFields").each(function (index, item) {
                var $item = $(item);
                if ($item.prop('checked')) {
                    var value = $item.val();
                    if (value !== 'secret') {
                        encryptedFields.push(value);
                    }
                    
                    // secret固定加密,其它根据用户勾选加密
                    if (value == 'ip') {
                        ip = setEncrypt(ip)
                    }
                    if (value == 'appkey') {
                        appkey = setEncrypt(appkey)
                    }
                    if (value == 'snapDir') {
                        snapDir = setEncrypt(snapDir)
                    }
                    if (value == 'layout') {
                        layout = setEncrypt(layout)
                    }
                }
            })
            encryptedFields = encryptedFields.join(",");

            if (!appkey) {
                showCBInfo("appkey不能为空!", 'error');
                return
            }
            if (!$("#secret").val()) {
                showCBInfo("secret不能为空!", 'error');
                return
            }
            if (!ip) {
                showCBInfo("ip不能为空!", 'error');
                return
            }
            if (!$("#port").val()) {
                showCBInfo("端口不能为空!", 'error');
                return
            } else if (!/^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/.test($("#port").val())) {
                showCBInfo("端口填写有误!", 'error');
                return
            }
            console.log({
                appkey: appkey,
                secret: secret,
                ip: ip,
                playMode: 0, // 预览
                port: port,
                snapDir: snapDir,
                layout: layout,
				enableHTTPS: enableHttps,
                encryptedFields: encryptedFields
            })

            oWebControl.JS_RequestInterface({
                funcName: "init",
                argument: JSON.stringify({
                    appkey: appkey,
                    secret: secret,
                    ip: ip,
                    playMode: 0, // 预览
                    port: port,
                    snapDir: snapDir,
                    layout: layout,
					enableHTTPS: enableHttps,
                    encryptedFields: encryptedFields
                })
            }).then(function (oData) {
                showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
            });
        })
    });

    // 视频预览
	$("#startPreview").click(function () {
        var cameraIndexCode  = $("#cameraIndexCode ").val();
        var streamMode = +$("#streamMode").val();
        var transMode = +$("#transMode").val();
        var gpuMode = +$("#gpuMode").val();

        if (!cameraIndexCode ) {
            showCBInfo("监控点编号不能为空!", 'error');
            return
        }

        oWebControl.JS_RequestInterface({
            funcName: "startPreview",
            argument: JSON.stringify({
                cameraIndexCode : cameraIndexCode ,
                streamMode: streamMode,
                transMode: transMode,
                gpuMode: gpuMode
            })
        }).then(function (oData) {
            showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
        });
    });

    // 停止预览
    $("#stopAllPreview").click(function () {
        oWebControl.JS_RequestInterface({
            funcName: "stopAllPreview"
        }).then(function (oData) {
            showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
        });
    })

    // 反初始化
    function uninit (cbFunc) {
        oWebControl.JS_RequestInterface({
            funcName: "uninit"
        }).then(function (oData) {
            showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));

            cbFunc && cbFunc();
        });
    }
    $("#uninit").click(uninit)


    // 显示回调信息
    function showCBInfo(szInfo, type) {
        if (type === 'error') {
            szInfo = "<div style='color: red;'>" + dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") + " " + szInfo + "</div>";
        } else {
            szInfo = "<div>" + dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") + " " + szInfo + "</div>";
        }
        $("#cbInfo").html(szInfo + $("#cbInfo").html());
    }

    $("#clear").click(function() {
        $("#cbInfo").html('');
    })

    // 格式化时间
    function dateFormat(oDate, fmt) {
        var o = {
            "M+": oDate.getMonth() + 1, //月份
            "d+": oDate.getDate(), //日
            "h+": oDate.getHours(), //小时
            "m+": oDate.getMinutes(), //分
            "s+": oDate.getSeconds(), //秒
            "q+": Math.floor((oDate.getMonth() + 3) / 3), //季度
            "S": oDate.getMilliseconds()//毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (oDate.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }

以上是最原始的demo.html,有兴趣的朋友可以看一下。当然需要提前和你们公司的同事获取一些参数值





好了,完事。

可以从下面的链接中下载插件中的js文件

github.com/triumphic/-