/// <summary> /// 停止服务 /// </summary> public override void StopService() { if (serviceHost != null) { NLog.Logger log = NLog.LogManager.GetCurrentClassLogger(); NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); CgwService.Instance().StopAllStream();//stop all stream. SmcErr err = CgwService.Instance().DisconnectMonitor(); logEx.Info("CGW service.StopService DisconnectMonitor.ErrNo ={0}!", err.ErrNo); serviceHost.Close(); logEx.Info("CGW service.StopService Close Success."); } }
/// <summary> /// PTZ(Pan/Tilt/Zoom)控制,该接口需要在预览模式下使用 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <param name="ptzCommandType">命令类型</param> /// <param name="param">命令参数</param> /// <returns>返回错误码</returns> public SmcErr StartControlPtz(string cameraNo, PtzCommandType ptzCommandType, int param) { SmcErr err = new CgwError(); NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); err = CheckSession(currentSessionID); //调任何接口前 需要判断监控平台是否加载成功 if (err.IsSuccess()) { err = VideoMonitorManage.Instance().StartControlPtz(cameraNo, ptzCommandType, param); } if (err.IsSuccess()) { logEx.Info("MonitorManageService StartControlPtz Successful,Current Cgw IP is : {0}", CgwConst.ClientIp); } else { logEx.Error("MonitorManageService StartControlPtz failed,ErrNo :{0}", err.ErrNo); } return(err); }
/// <summary> /// 关闭PTZ操作 /// </summary> /// <param name="Camerano">摄像头</param> /// <returns></returns> public Cgw.SmcError.SmcErr StopControlPtz(string cameraNo, Common.PtzCommandType ptzCommandType) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: CgwMonitorManageAdapter.StopControlPtz"); Cgw.SmcError.SmcErr err = new Cgw.SmcError.SmcErr(); try { //if (serviceControl.MonitorServiceRun() && client.State == CommunicationState.Opened) if (serviceControl.MonitorServiceRun()) { client = new MonitorManageServiceClient(); CgwMonitorManageServiceReference.PtzCommandType ptzCommand = (CgwMonitorManageServiceReference.PtzCommandType)ptzCommandType; //将平台的枚举转换成服务中的枚举 CgwMonitorManageServiceReference.SmcErr serviceErr = client.StopControlPtz(cameraNo, ptzCommand); client.Close(); if (serviceErr.ErrNo != Cgw.SmcError.CgwError.ERR_MONITOR_MANAGE_SERVICE_SUCCESS) { logEx.Error("Stop control ptz failed.Camera no:{0},ptzCommandType:{1},Error Code:{2} ", cameraNo, ptzCommand, err.ErrNo); err = SetCgwErrNo(serviceErr); } else { logEx.Info("Stop control ptz success.Camera no:{0},ptzCommandType:{1}.", cameraNo, ptzCommand); } } else { err.SetErrorNo(Cgw.SmcError.CgwError.ERR_MONITOR_MANAGE_SERVICE_RESTARTING); } } catch (System.Exception ex) { err.SetErrorNo(Cgw.SmcError.CgwError.ERR_MONITOR_MANAGE_SERVICE_RESTARTING); logEx.Error("CgwMonitorManageServiceReference.StopControlPtz failed. Exception is {0} ", ex.ToString()); } return(err); }
/// <summary> /// 刷新监控摄像头列表 /// </summary> /// <returns></returns> public SmcErr RefreshMonitorCamera() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.RefreshMonitorCamera"); SmcErr err = new CgwError(); if (refreshMonitorCameraOperateLock.TryEnterWriteLock(CgwConst.EFRESH_MONITOR_CAMERA_WAIT_TIME)) { try { GetAllCamerasMethod(); //重新开始计时 updateCameraTimer.Stop(); updateCameraTimer.Start(); } finally { refreshMonitorCameraOperateLock.ExitWriteLock(); } } logEx.Info("RefreshMonitorCamera success."); return(err); }
/// <summary> /// 刷新监控摄像头列表 /// </summary> /// <returns></returns> public SmcErr RefreshMonitorCamera() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: CgwService.RefreshMonitorCamera"); SmcErr err = new CgwError(); err = CheckSession(); if (err.IsSuccess()) { err = MonitorChannelBll.Instance().RefreshMonitorCamera(); } if (err.IsSuccess()) { logEx.Info("SMC RefreshMonitorCamera Successful,Current SMC IP is : {0}", CgwConst.SmcIp); } else { logEx.Error("SMC RefreshMonitorCamera failed,ErrNo :{0}", err.ErrNo); } return(err); }
/// <summary> /// 停止云台控制,摄像头控制 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <param name="ptzCommand">命令类型</param> /// <returns></returns> public SmcErr StopControlPtz(string cameraNo, PtzCommandType ptzCommand) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.StopControlPtz({0}).", cameraNo); SmcErr err = new CgwError(); logEx.Trace("Call ivsSdkClient.StopPtzControl({0}).", cameraNo); int result = this.ivsSdkClient.StopPtzControl(cameraNo); //如果为0,表示成功 if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("Stop control ptz success.Camera No:{0}.", cameraNo); } else { //直接将IVS的错误码返回 err.SetErrorNo(CgwError.STOP_CONTROL_PTZ_FAILED); logEx.Error("Stop control ptz failed.Camera No:{0}.Ivs sdk error code:{1}.", cameraNo, result); return(err); } return(err); }
/// <summary> /// 开始云台控制,摄像头控制 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <param name="ptzCommand">命令类型</param> /// <param name="param">命令参数(速度、倍数)</param> /// <returns></returns> public SmcErr StartControlPtz(string cameraNo, PtzCommandType ptzCommand, int param) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.StartControlPtz({0},{1},{2}).", cameraNo, ptzCommand, param); SmcErr err = new CgwError(); //将ptz命令转换成IVS的命令 string name = Enum.GetName(typeof(PtzCommandType), ptzCommand); if (Enum.IsDefined(typeof(IvsPtzCommandType), name)) { IvsPtzCommandType ivsPtzCommandType = (IvsPtzCommandType)Enum.Parse(typeof(IvsPtzCommandType), name); logEx.Trace("Call ivsSdkClient.StartPtzControl({0},{1},{2}).", cameraNo, (int)ivsPtzCommandType, param); int result = this.ivsSdkClient.StartPtzControl(cameraNo, (int)ivsPtzCommandType, param.ToString()); //如果为0,表示成功 if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("Start control ptz success.Camera No:{0}.", cameraNo); } else { err.SetErrorNo(CgwError.START_CONTROL_PTZ_FAILED); logEx.Error("Start control ptz failed.Camera No:{0}.Ivs sdk error code:{1}.", cameraNo, result); return(err); } } else { err.SetErrorNo(CgwError.START_CONTROL_PTZ_FAILED); logEx.Error("The ivs monitor is not support the command.ptzCommand:{0}.", ptzCommand); return(err); } return(err); }
/// <summary> /// 注销SDK资源 /// </summary> /// <returns></returns> public bool Unload() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandySdkClient.Unload()."); try { //释放SDK资源 if (client_sdk_cleanup()) { logEx.Info("Call Tiandy sdk function client_sdk_cleanup success."); return(true); } else { logEx.Error("Call Tiandy sdk function client_sdk_cleanup failed."); return(false); } } catch (Exception e) { logEx.Error("Call Tiandy sdk function client_sdk_cleanup failed. Exception message:{0}.", e.Message); return(false); } }
/// <summary> /// 停止预览 /// </summary> /// <param name="playfd">设备ID</param> /// <returns>成功返回0,失败返回错误码</returns> public bool StopReceiveVideo(int playfd) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandySdkClient.StopReceiveVideo({0}).", playfd); try { //调用SDK接口,停止预览,回调设置为空 client_sdk_set_h264_callback(playfd, null, 0); if (client_sdk_stop_realplay(playfd)) { if (this.handelOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { this.receiveSuccHandle.Remove(playfd); } finally { this.handelOperateLock.ExitWriteLock(); } } logEx.Info("Call Tiandy sdk function client_sdk_stop_realplay success.playfd:{0}.", playfd); return(true); } else { logEx.Error("Call Tiandy sdk function client_sdk_stop_realplay failed. playfd:{0}.", playfd); return(false); } } catch (Exception e) { logEx.Error("Stop Receive camera video data failed.Exception message:{0}.", e.Message); return(false); } }
/// <summary> /// 获取监控设备列表 /// </summary> /// <param name="CameraInfoList">摄像头基本信息</param> /// <param name="CameraGroupList">组基本信息</param> /// <param name="nodeRelationList">所属分组关系信息</param> /// <returns></returns> public SmcErr QueryMonitorCamera(PlatformType platformType, PageParam pageParam, out List <Camera> cameraInfoList, out List <CameraGroup> cameraGroupList, out List <NodeRelation> nodeRelationList, out PagesInfo pagesInfo) { SmcErr err = new CgwError(); NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); cameraInfoList = null; cameraGroupList = null; nodeRelationList = null; pagesInfo = null; err = CheckSession(); if (err.IsSuccess()) { err = MonitorChannelBll.Instance().QueryMonitorCamera(platformType, pageParam, out cameraInfoList, out cameraGroupList, out nodeRelationList, out pagesInfo); } if (err.IsSuccess()) { logEx.Info("SMC QueryMonitorCamera Successful,Current SMC IP is : {0}", CgwConst.SmcIp); } else { logEx.Error("SMC QueryMonitorCamera failed,ErrNo :{0}", err.ErrNo); } return(err); }
/// <summary> /// 写日志回调函数 /// </summary> /// <param name="level"></param> /// <param name="log"></param> /// <param name="len"></param> /// <returns></returns> private uint WriteLog(NLogLevel level, string log, int len) { NLog.Logger sotLog = NLog.LogManager.GetLogger("SoftTerminal"); NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(sotLog); try { switch (level) { case NLogLevel.Error: logEx.Error(log); break; case NLogLevel.Warn: logEx.Warn(log); break; case NLogLevel.Info: logEx.Info(log); break; case NLogLevel.Trace: logEx.Trace(log); break; default: break; } } catch (System.Exception ex) { logEx.Error(ex, "WriteLog Exception level:{0}, log:{1}.", level, log); } return(1); }
/// <summary> /// 注销监控平台资源 /// </summary> /// <returns></returns> public SmcErr Unload() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Info("Enter: VideoMonitorManage.Unload()."); SmcErr err = new CgwError(); if (this.monitorsOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { foreach (KeyValuePair <string, IVideoMonitor> monitor in monitorsDictionary) { IVideoMonitor videoMonitor = monitor.Value; SmcErr result = videoMonitor.Unload(); if (!result.IsSuccess()) { logEx.Error("Unload monitor failed.Monitor id:{0} ,Error code:{1}", monitor.Key, result.ErrNo); //一个失败,记录失败,继续其他平台卸载 err.SetErrorNo(result.ErrNo); continue; } } monitorsDictionary.Clear(); } catch (Exception e) { logEx.Error("Unload monitor failed..Execption message:{0}", e.Message); } finally { this.monitorsOperateLock.ExitWriteLock(); } } return(err); }
/// <summary> /// 设置扬声器 /// </summary> /// <param name="cameraNo"></param> /// <param name="isOn"></param> /// <returns></returns> public Cgw.SmcError.SmcErr SetSpeaker(string cameraNo, bool isOn) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: CgwMonitorManageAdapter.SetSpeaker"); Cgw.SmcError.SmcErr err = new Cgw.SmcError.SmcErr(); try { //if (serviceControl.MonitorServiceRun() && client.State == CommunicationState.Opened) if (serviceControl.MonitorServiceRun()) { client = new MonitorManageServiceClient(); CgwMonitorManageServiceReference.SmcErr serviceErr = client.SetSpeaker(cameraNo, isOn); client.Close(); if (serviceErr.ErrNo == Cgw.SmcError.CgwError.ERR_MONITOR_MANAGE_SERVICE_SUCCESS) { logEx.Info("Cgw SetSpeaker Successful,Current Cgw IP is : {0}", CgwConst.CGWSERVICE_IP_TAG); } else { logEx.Error("Cgw SetSpeaker failed,ErrNo :{0}", err.ErrNo); err = SetCgwErrNo(serviceErr); } } else { err.SetErrorNo(Cgw.SmcError.CgwError.ERR_MONITOR_MANAGE_SERVICE_RESTARTING); } } catch (System.Exception ex) { err.SetErrorNo(Cgw.SmcError.CgwError.ERR_MONITOR_MANAGE_SERVICE_RESTARTING); logEx.Error("CgwMonitorManageServiceReference.SetSpeaker failed. Exception is {0} ", ex.ToString()); } return(err); }
/// <summary> /// 注销IVS监控平台资源 /// </summary> /// <returns></returns> public SmcErr Unload() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Info("Enter: IvsVideoMonitor.Unload()."); SmcErr err = new CgwError(); loadResult = true; //停止定时器 this.updateCameraTimer.Stop(); logEx.Trace("Call ivsSdkClient.Logout()."); int result = this.ivsSdkClient.Logout(); logEx.Trace("Call ivsSdkClient.Cleanup()."); result = this.ivsSdkClient.Cleanup(); if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("Unload video monitor success.Monitor id:{0}.", this.monitorId); } else { err.SetErrorNo(CgwError.MONITOR_UDLOAD_FAILED); logEx.Error("Unload video monitor failed.Monitor id:{0}.", this.monitorId); } return err; }
/// <summary> /// 停止云台控制,摄像头控制 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <param name="ptzCommand">命令类型</param> /// <returns></returns> public SmcErr StopControlPtz(string cameraNo, PtzCommandType ptzCommand) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.StopControlPtz({0}).", cameraNo); SmcErr err = new CgwError(); logEx.Trace("Call ivsSdkClient.StopPtzControl({0}).", cameraNo); int result = this.ivsSdkClient.StopPtzControl(cameraNo); //如果为0,表示成功 if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("Stop control ptz success.Camera No:{0}.", cameraNo); } else { //直接将IVS的错误码返回 err.SetErrorNo(CgwError.STOP_CONTROL_PTZ_FAILED); logEx.Error("Stop control ptz failed.Camera No:{0}.Ivs sdk error code:{1}.", cameraNo, result); return err; } return err; }
/// <summary> /// 开始云台控制,摄像头控制 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <param name="ptzCommand">命令类型</param> /// <param name="param">命令参数(速度、倍数)</param> /// <returns></returns> public SmcErr StartControlPtz(string cameraNo, PtzCommandType ptzCommand, int param) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.StartControlPtz({0},{1},{2}).", cameraNo, ptzCommand, param); SmcErr err = new CgwError(); //将ptz命令转换成IVS的命令 string name = Enum.GetName(typeof(PtzCommandType), ptzCommand); if (Enum.IsDefined(typeof(IvsPtzCommandType), name)) { IvsPtzCommandType ivsPtzCommandType = (IvsPtzCommandType)Enum.Parse(typeof(IvsPtzCommandType), name); logEx.Trace("Call ivsSdkClient.StartPtzControl({0},{1},{2}).", cameraNo, (int)ivsPtzCommandType, param); int result = this.ivsSdkClient.StartPtzControl(cameraNo, (int)ivsPtzCommandType, param.ToString()); //如果为0,表示成功 if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("Start control ptz success.Camera No:{0}.", cameraNo); } else { err.SetErrorNo(CgwError.START_CONTROL_PTZ_FAILED); logEx.Error("Start control ptz failed.Camera No:{0}.Ivs sdk error code:{1}.", cameraNo, result); return err; } } else { err.SetErrorNo(CgwError.START_CONTROL_PTZ_FAILED); logEx.Error("The ivs monitor is not support the command.ptzCommand:{0}.", ptzCommand); return err; } return err; }
/// <summary> /// 初始化IVS监控平台 /// </summary> /// <param name="monitorConfigElement">监控平台配置节点</param> /// <returns></returns> public SmcErr Load(XmlElement monitorConfigElement) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Info("Enter: IvsVideoMonitor.Load()."); SmcErr err = new CgwError(); try { //解析xml节点,获取所需参数 this.monitorId = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.ID_TAG); ip = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.IP_TAG); port = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PORT_TAG); user = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.USER_TAG); //password = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PASSWORD_TAG); pwdByte = CommonFunction.EncryptStr2Byte(CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PASSWORD_TAG),CgwConst.PASSWORD_TAG); //从配置文件读取的参数要简单判断一下合法性 //初始化之前设置日志路径 logEx.Trace("Call SetLogPath:{0}", ivsLogPath); this.ivsSdkClient.SetLogPath(ivsLogPath); logEx.Trace("Call ivsSdkClient.Init()."); //初始化 int result = this.ivsSdkClient.Init(); if (result != CgwConst.IVS_SDK_SUCCESS_TAG) { //直接将IVS的错误码返回 err.SetErrorNo(CgwError.MONITOR_LOAD_FAILED); logEx.Error("Init ivs monitor failed.Monitor id:{0}.ivs sdk error code:{1}.", this.monitorId, result); return err; } else { logEx.Info("Init ivs sdk success.Monitor id:{0}", this.monitorId); } //设置监控平台id this.ivsSdkClient.SetId(this.monitorId); this.sdkCallbackFunc = IvsRealPlayCallBackRaw; this.ivsSdkClient.SetRealPlayCBRawCallBackFunc(this.sdkCallbackFunc); //sdk事件回调 this.ivsEventCallBackFunc = IvsEventCallBackFunc; this.ivsSdkClient.SetEventCallBackFunc(this.ivsEventCallBackFunc); IvsLoginInfo loginInfo = new IvsLoginInfo(); loginInfo.Ip = ip; loginInfo.Port = int.Parse(port); loginInfo.User = user; //loginInfo.Pwd = password; loginInfo.Pwd = CommonFunction.DecryptByte2Str(pwdByte,CgwConst.PASSWORD_TAG); loadResult = false; //使用线程轮询加载监控平台 Thread loaderThread = new Thread(LoginThread); loaderThread.IsBackground = true; loaderThread.Start(loginInfo); } catch (Exception e) { err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID); logEx.Error("Load ivs monitor failed.Execption message:{0}.", e.Message); return err; } logEx.Info("Load video monitor success.Monitor id:{0}.", this.monitorId); return err; }
/// <summary> /// 设置实况rtp数据包回调 /// </summary> /// <param name="dataCallBack"></param> public void SetNetDataCallBack(NET_DATA_CALLBACK dataCallBack, NET_EXCEPTION_CALLBACK netExceptionCallBack) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: SipStackAdapter.SetNetDataCallBack()."); cbDataCallBack = dataCallBack; cbNetExceptionCallBack = netExceptionCallBack; logEx.Info("Set SetNetDataCallBack success"); }
/// <summary> /// 刷新监控摄像头列表 /// </summary> /// <returns></returns> public SmcErr RefreshMonitorCamera() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.RefreshMonitorCamera"); SmcErr err = new CgwError(); if (refreshMonitorCameraOperateLock.TryEnterWriteLock(CgwConst.EFRESH_MONITOR_CAMERA_WAIT_TIME)) { try { GetAllCamerasMethod(); //重新开始计时 updateCameraTimer.Stop(); updateCameraTimer.Start(); } finally { refreshMonitorCameraOperateLock.ExitWriteLock(); } } logEx.Info("RefreshMonitorCamera success."); return err; }
/// <summary> /// 停止云台控制,摄像头控制 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <param name="ptzCommand">命令类型</param> /// <returns></returns> public SmcErr StopControlPtz(string cameraNo, PtzCommandType ptzCommand) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.StopControlPtz({0}).", cameraNo); SmcErr err = new CgwError(); int handel = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; if (this.handelOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { if (this.cameraVideoHandeDic.ContainsKey(cameraNo)) { handel = this.cameraVideoHandeDic[cameraNo]; } else { logEx.Warn("The camera was not Preview.Don't need to end the control.Camera No:{0}.", cameraNo); } } finally { this.handelOperateLock.ExitReadLock(); } } if (handel != CgwConst.START_RECEIVE_VIDEO_DATA_FAILED) { Client_PTZ_Command client_ptz_command = new Client_PTZ_Command(); client_ptz_command.start = false; //将ptz命令转换成天地伟业的命令 string name = Enum.GetName(typeof(PtzCommandType), ptzCommand); if (Enum.IsDefined(typeof(TiandyPtzCommandType), name)) { TiandyPtzCommandType tiandyPtzCommandType = (TiandyPtzCommandType)Enum.Parse(typeof(TiandyPtzCommandType), name); client_ptz_command.cmd = (int)tiandyPtzCommandType; } else { err.SetErrorNo(CgwError.STOP_CONTROL_PTZ_FAILED); logEx.Error("The tiandy monitor is not support the command.ptzCommand:{0}.", ptzCommand); return(err); } bool result = this.sdkClient.ControlPtz(handel, client_ptz_command); if (result) { logEx.Info("Stop control camera ptz success.Camera No:{0}.", cameraNo); } else { err.SetErrorNo(CgwError.STOP_CONTROL_PTZ_FAILED); logEx.Error("Stop control camera ptz failed.Camera No:{0}.", cameraNo); } } else { err.SetErrorNo(CgwError.STOP_CONTROL_PTZ_FAILED); logEx.Error("Handel is not found. Stop control camera ptz failed. Camera No:{0}.", cameraNo); return(err); } return(err); }
/// <summary> /// 启动摄像头预览 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <returns></returns> public SmcErr StartReceiveVideo(string cameraNo) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.StartReceiveVideo({0}).", cameraNo); SmcErr err = new CgwError(); TiandyCamera camera = null; Host host = null; //摄像头所连接的流媒体服务器 MediaServer cameraMediaServer = null; if (this.cameraOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { if (!this.tiandyCameraDictionary.ContainsKey(cameraNo)) { err.SetErrorNo(CgwError.CAMERA_NOT_FOUND); logEx.Error("Start Receive camera video data failed.Camera No is not found.Camera No:{0}", cameraNo); return(err); } camera = this.tiandyCameraDictionary[cameraNo]; host = this.hostDictionary[camera.HostNo]; cameraMediaServer = this.mediaServerDictionary[host.MediaServerNo]; } catch (Exception e) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Start Receive camera video data failed.Camera No:{0},Execption message:{1}", cameraNo, e.Message); return(err); } finally { this.cameraOperateLock.ExitReadLock(); } } if (camera == null) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Start Receive camera video data failed.Camera No is not found.Camera No:{0}", cameraNo); return(err); } RealPlayInfo real = new RealPlayInfo(); real.ch = camera.Channel; real.data_type = (int)TiandyDateType.PRIMARY; real.hPlayWnd = null; int result = this.sdkClient.StartReceiveVideo(host.No, cameraMediaServer, ref real); //如果为负数,表示预览失败 if (result < 0) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Start Receive camera video data failed.Camera No:{0}.", cameraNo); return(err); } else { //需要停止的预览句柄 int needToStopHandel = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; if (this.handelOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { //如果预览句柄已经存在,删除掉原来的句柄,用新的句柄替换 if (this.cameraVideoHandeDic.ContainsKey(cameraNo)) { needToStopHandel = this.cameraVideoHandeDic[cameraNo]; this.videoHandleCameraDic.Remove(needToStopHandel); this.cameraVideoHandeDic.Remove(cameraNo); } this.cameraVideoHandeDic.Add(cameraNo, result); this.videoHandleCameraDic.Add(result, cameraNo); } finally { this.handelOperateLock.ExitWriteLock(); } } logEx.Info("Start Receive camera video data success.Camera No:{0},Handle:{1}.", cameraNo, result); //重新预览后,更新了预览句柄,需要将原来的预览停止,放在handelOperateLock外面,防止长时间占用锁 if (needToStopHandel != CgwConst.START_RECEIVE_VIDEO_DATA_FAILED) { this.sdkClient.StopReceiveVideo(needToStopHandel); } } return(err); }
/// <summary> /// 获取本机ip /// </summary> /// <returns></returns> private string GetLocalIP(string serverIP, int serverPort, int localPort) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: SipStackAdapter.GetLocalIP()."); try { IPAddress serverAddress = IPAddress.Parse(serverIP); IPAddress[] arrIPAddresses = Dns.GetHostAddresses(System.Environment.MachineName); foreach (IPAddress ip in arrIPAddresses) { //如果serverIP为IPv4 if (serverAddress.AddressFamily.Equals(AddressFamily.InterNetwork) && ip.AddressFamily.Equals(serverAddress.AddressFamily)) { #region IPv4 IPEndPoint serverEndpoint = new IPEndPoint(serverAddress, serverPort); Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint clientEndpoint = new IPEndPoint(ip, localPort); socketClient.Bind(clientEndpoint); try { socketClient.Connect(serverEndpoint); if (socketClient.Connected) { logEx.Trace("SipStackAdapter.try GetLocalIP ={0}.", ip.ToString()); return ip.ToString(); } } catch (SocketException e) { //logEx.Warn("SipStackAdapter.GetLocalIP failed,e.ErrorCode:{0}", e.ErrorCode); if (e.ErrorCode == 10061 || e.ErrorCode == 10048) //Even No connection could be made because the target machine actively refused it ,but IP is valid. { logEx.Trace("SipStackAdapter.catch GetLocalIP ={0}.", ip.ToString()); return ip.ToString(); } logEx.Error("SipStackAdapter.GetLocalIP failed.catch Execption message:{0}", e.Message); } finally { socketClient.Close(); logEx.Info("SipStackAdapter.GetLocalIP finally,Close the socketClient success"); } #endregion } //如果serverIP为IPv6 else if (serverAddress.AddressFamily.Equals(AddressFamily.InterNetworkV6) && ip.AddressFamily.Equals(serverAddress.AddressFamily)) { #region IPV6 IPEndPoint serverEndpoint = new IPEndPoint(serverAddress, serverPort); Socket socketClient = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); IPEndPoint clientEndpoint = new IPEndPoint(ip, localPort); socketClient.Bind(clientEndpoint); try { socketClient.Connect(serverEndpoint); if (socketClient.Connected) { logEx.Trace("SipStackAdapter.try GetLocalIP ={0}.", ip.ToString()); return ip.ToString(); } } catch (SocketException e) { //logEx.Warn("SipStackAdapter.GetLocalIP failed,e.ErrorCode:{0}", e.ErrorCode); if (e.ErrorCode == 10061 || e.ErrorCode == 10048) //Even No connection could be made because the target machine actively refused it ,but IP is valid. { logEx.Trace("SipStackAdapter.catch GetLocalIP ={0}.", ip.ToString()); return ip.ToString(); } logEx.Error("SipStackAdapter.GetLocalIP failed.catch Execption message:{0}", e.Message); } finally { socketClient.Close(); logEx.Info("SipStackAdapter.GetLocalIP finally,Close the socketClient success"); } #endregion } } return null; } catch (System.Exception ex) { logEx.Error("SipStackAdapter.GetLocalIP failed.Execption message:{0}", ex.Message); return null; } }
/// <summary> /// 打开通道,开始接收实况RTP数据流 /// </summary> /// <param name="cameraCode">摄像机编码</param> /// <returns></returns> public UInt32 StartRecvStream(string cameraCode, string domain, string iSipPort, string localPort) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: SipStackAdapter.StartRecvStream cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); try { //接收视频码流RTP端口号 uint uiLocalRecvStreamVideoRtpPort = 0; //接收音频码流RTP端口号 uint uiLocalRecvStreamAudioRtpPort = 0; //通道号 UInt32 uiChannel = 0; //string strLocal = GetLocalIP(domain, Convert.ToInt32(iSipPort), Convert.ToInt32(localPort)); if (string.IsNullOrEmpty(localIP)) { localIP = GetLocalIP(domain, Convert.ToInt32(iSipPort), Convert.ToInt32(localPort)); } string strLocal = localIP; //获取可用通道 NetSourcedInterface.IVS_NETSOURCE_GetChannel(ref uiChannel); //用户参数,4字节整数 IntPtr pUser = Marshal.AllocHGlobal(4); Marshal.Copy(new int[1] { Convert.ToInt32(uiChannel) }, 0, pUser, 1); //设置媒体流回调函数 NetSourcedInterface.IVS_NETSOURCE_SetDataCallBack(uiChannel, cbDataCallBack, pUser); //异常回调函数 IVS_NETSOURCE_RESULT iRet = NetSourcedInterface.IVS_NETSOURCE_SetExceptionCallBack(cbNetExceptionCallBack, pUser); //协议类型 UDP iRet = NetSourcedInterface.IVS_NETSOURCE_SetProtocolType(uiChannel, 1); if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.StartRecvStream.IVS_NETSOURCE_SetProtocolType failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return CgwConst.T28181_ERROR_HANDLE; } iRet = NetSourcedInterface.IVS_NETSOURCE_SetLocalRecvStreamIP(uiChannel, localIP); if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.StartRecvStream.IVS_NETSOURCE_SetLocalRecvStreamIP failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return CgwConst.T28181_ERROR_HANDLE; } iRet = NetSourcedInterface.IVS_NETSOURCE_GetLocalRecvStreamPort(uiChannel, ref uiLocalRecvStreamVideoRtpPort, ref uiLocalRecvStreamAudioRtpPort); if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.StartRecvStream.IVS_NETSOURCE_GetLocalRecvStreamPort failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return CgwConst.T28181_ERROR_HANDLE; } //Invite消息体 string strRealPlay = "v=0\r\n" + "o=" + cameraCode + @" 0 0 IN IP4 " + strLocal + "\r\n" + "s=Play\r\n" + "c=IN IP4 " + strLocal + "\r\n" + "t=0 0\r\n" + "m=video " + uiLocalRecvStreamVideoRtpPort + " RTP/AVP 96 98 97\r\n" + "a=recvonly\r\n" + "a=rtpmap:96 PS/90000\r\n" + "a=rtpmap:98 H264/90000\r\n" + "a=rtpmap:97 MPEG4/90000\r\n"; //发送SIP Invite消息 int iResponseID = 0; //制定字符串长度为1024 StringBuilder strRemoteBody = new StringBuilder(1024); //发送SIP Invite消息 EM_SIP_RESULT iSip = SIP_SDK_INVITE(cameraCode, strRealPlay, ref iResponseID, strRemoteBody); if (iSip != EM_SIP_RESULT.RET_SUCCESS) { logEx.Error("SipStackAdapter.SIP_SDK_INVITE failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return CgwConst.T28181_ERROR_HANDLE; } //源端发送码流IP; string pRemoteSendStreamIp = ""; //源端发送视频码流RTP端口号 uint uiRemoteSendStreamVideoPort = 0; GetInviteRemoteIPPort(strRemoteBody.ToString(), ref pRemoteSendStreamIp, ref uiRemoteSendStreamVideoPort); iRet = NetSourcedInterface.IVS_NETSOURCE_OpenNetStream(uiChannel, pRemoteSendStreamIp, uiRemoteSendStreamVideoPort, 0);//无音频,传入0 if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.StartRecvStream failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return CgwConst.T28181_ERROR_HANDLE; } iRet = NetSourcedInterface.IVS_NETSOURCE_StartRecvStream(uiChannel); if (iRet == IVS_NETSOURCE_RESULT.SUCCESS) { channelResponseIDDic.Add(uiChannel, iResponseID); channelInPtrDic.Add(uiChannel, pUser); logEx.Info("SipStackAdapter.StartRecvStream pChannel: {0}, cameraCode :{1},domain = {2},iSipPort ={3} ", uiChannel, cameraCode, domain, iSipPort); return uiChannel; } else { logEx.Error("SipStackAdapter.StartRecvStream failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); StopRecvStream(uiChannel); Marshal.FreeHGlobal(pUser); return CgwConst.T28181_ERROR_HANDLE; } } catch (System.Exception ex) { logEx.Error("StartRecvStream failed.Exception message:{0},cameraCode :{0},domain = {1},iSipPort ={2}", ex.Message, cameraCode, domain, iSipPort); return CgwConst.T28181_ERROR_HANDLE; } }
/// <summary> /// 该函数用于发送SIP Register消息 /// </summary> public EM_SIP_RESULT SIP_SDK_REGISTER() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: SipStackAdapter.SIP_SDK_REGISTER()."); EM_SIP_RESULT iRet = EM_SIP_RESULT.RET_FAILURE; try { iRet = SipSDKInterface.SIP_SDK_REGISTER(); if (iRet != EM_SIP_RESULT.RET_SUCCESS) { logEx.Error("SipStackAdapter.SIP_SDK_REGISTER Error = {0}.", Enum.GetName(typeof(EM_SIP_RESULT), iRet)); } else { logEx.Info("SipStackAdapter.SIP_SDK_REGISTER Success"); } } catch (System.Exception ex) { logEx.Error("SipStackAdapter.SIP_SDK_REGISTER ,Exception:{0}", ex.ToString()); iRet = EM_SIP_RESULT.RET_FAILURE; } return iRet; }
/// <summary> /// 该函数用于发送SIP Invite消息 /// </summary> /// <param name="pAccount">对方账号</param> /// <param name="pSdpBody">SDP描述字符串</param> public EM_SIP_RESULT SIP_SDK_INVITE(string pAccount, string pSdpBody, ref int iResponseID, StringBuilder strRemoteBody) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: SipStackAdapter.SIP_SDK_INVITE()."); iResponseID = 0; EM_SIP_RESULT iRet = EM_SIP_RESULT.RET_FAILURE; try { iRet = SipSDKInterface.SIP_SDK_INVITE(pAccount, pSdpBody, ref iResponseID, strRemoteBody); SIP_SDK_ACK(iResponseID); if (iRet != EM_SIP_RESULT.RET_SUCCESS) { logEx.Error("SipStackAdapter.SIP_SDK_INVITE ,pSdpBody:{0}", pSdpBody); } else { logEx.Info("SipStackAdapter.SIP_SDK_INVITE ,iResponseID={0}", iResponseID); } } catch (System.Exception ex) { logEx.Error("SipStackAdapter.SIP_SDK_INVITE ,Exception:{0}", ex.ToString()); iRet = EM_SIP_RESULT.RET_FAILURE; } return iRet; }
/// <summary> /// 该函数用于发送SIP ACK消息 /// </summary> /// <param name="iResponseID">iResponseID</param> public EM_SIP_RESULT SIP_SDK_ACK(int iResponseID) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: SipStackAdapter.SIP_SDK_ACK()."); EM_SIP_RESULT iRet = EM_SIP_RESULT.RET_FAILURE; try { iRet = SipSDKInterface.SIP_SDK_ACK(iResponseID); if (iRet != EM_SIP_RESULT.RET_SUCCESS) { logEx.Error("SipStackAdapter.SIP_SDK_ACK ,iResponseID:{0}", iResponseID); } else { logEx.Info("SipStackAdapter.SIP_SDK_ACK ,iResponseID={0}", iResponseID); } } catch (System.Exception ex) { logEx.Error("SipStackAdapter.SIP_SDK_ACK ,Exception:{0}", ex.ToString()); iRet = EM_SIP_RESULT.RET_FAILURE; } return iRet; }
/// <summary> /// 初始化监控平台 /// </summary> /// <returns></returns> public SmcErr Load() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Info("Enter: VideoMonitorManage.Load()"); SmcErr err = new CgwError(); XmlElement monitorsRootElement = ConfigSettings.MonitorSettings; if (monitorsRootElement == null) { err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID); logEx.Error("Monitor config file is invalid.Can not found monitorSettings node."); return(err); } foreach (XmlNode monitorNode in monitorsRootElement) { XmlElement monitorElement = monitorNode as XmlElement; if (monitorElement == null) { continue; } else if (CgwConst.MONITOR_TAG.Equals(monitorElement.Name)) { //判断监控平台是否启用 string isEnable = monitorElement.GetAttribute(CgwConst.ENABLE_TAG).Trim(); if (!CgwConst.TRUE_TAG.Equals(isEnable.ToLower())) { logEx.Warn("This monitor is disable."); continue; } string monitorId; string className; err = GetMonitorConfig(monitorElement, out monitorId, out className); if (!err.IsSuccess()) { return(err); } IVideoMonitor videoMonitor; //加载监控平台 err = CreateMonitor(monitorId, className, out videoMonitor); if (!err.IsSuccess()) { logEx.Error("Create monitor failed.monitorId:{0}, className:{1}, Error code:{2}", monitorId, className, err.ErrNo); return(err); } err = videoMonitor.Load(monitorElement); if (err.IsSuccess()) { if (this.monitorsOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { monitorsDictionary.Add(monitorId, videoMonitor); } catch (Exception e) { logEx.Error("Load monitor failed.Execption message:{0}", e.Message); return(err); } finally { this.monitorsOperateLock.ExitWriteLock(); } } } else { logEx.Error("Load monitor failed.MonitorId:{0},Error code:{1}", monitorId, err.ErrNo); return(err); } } } logEx.Info("Load all monitors success."); return(err); }
/// <summary> /// 启动实时预览 /// </summary> /// <param name="dev_id">主机ID </param> /// <param name="cameraMediaServer">设备端接入的流媒体服务器信息 </param> /// <param name="info">实时播放信息</param> /// <returns>-1 失败,其他则是返回预览句柄</returns> public int StartReceiveVideo(string dev_id, MediaServer cameraMediaServer, ref RealPlayInfo info) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandySdkClient.StartReceiveVideo({0},{1},{2}).", dev_id, cameraMediaServer.No, info); int iPlayFd = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; //如果摄像机的流媒体服务器为空,那么启动码流失败 if (cameraMediaServer == null) { logEx.Error("cameraMediaServer can't be null"); return(CgwConst.START_RECEIVE_VIDEO_DATA_FAILED); } MediaServer clientMediaServer = this.sdkMediaServer; if (clientMediaServer == null) { clientMediaServer = cameraMediaServer; } try { iPlayFd = client_sdk_realplay2_ex( dev_id, clientMediaServer.User, clientMediaServer.Pwd, clientMediaServer.No, cameraMediaServer.No, clientMediaServer.Ip, clientMediaServer.Port, ref info, null, 0); if (iPlayFd == CgwConst.START_RECEIVE_VIDEO_DATA_FAILED) { logEx.Error("Call Tiandy sdk function client_sdk_realplay2_ex failed."); return(iPlayFd); } else { logEx.Info("Call Tiandy sdk function client_sdk_realplay2_ex success.dev_id:{0},username:{1},client_sup_id:{2},dev_sup_id{3},client_sup_ip:{4},client_sup_port:{5}.", dev_id, clientMediaServer.User, clientMediaServer.No, cameraMediaServer.No, clientMediaServer.Ip, clientMediaServer.Port); } //预览成功设置码流回调 //if (!client_sdk_set_realdata_callback(iPlayFd, func, 0)) if (!client_sdk_set_h264_callback(iPlayFd, this.sdkRealDataCallBackFunc, 0)) { logEx.Error("Start Receive camera video data failed.Call Tiandy sdk function client_sdk_set_h264_callback failed.playfd:{0}", iPlayFd); return(CgwConst.START_RECEIVE_VIDEO_DATA_FAILED); } else { logEx.Info("Call Tiandy sdk function client_sdk_set_h264_callback success.playfd:{0}", iPlayFd); } //因天地伟业的预览接口是异步的,还需要通过消息回调判断是否成功 int count = 0; bool isSuccess = false; //循环5次 while (count < 5) { //等待500ms Thread.Sleep(CgwConst.CHECK_RECEIVE_STATUS_WAIT_TIME); if (this.handelOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { if (this.receiveSuccHandle.Contains(iPlayFd)) { logEx.Info("Start Receive camera video data success."); isSuccess = true; break; } } finally { this.handelOperateLock.ExitReadLock(); } } //等待500ms Thread.Sleep(CgwConst.CHECK_RECEIVE_STATUS_WAIT_TIME); count++; } if (!isSuccess) { logEx.Error("Set callback function success. But not receive any video data.Try to stop receive."); client_sdk_set_h264_callback(iPlayFd, null, 0); client_sdk_stop_realplay(iPlayFd); iPlayFd = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; } } catch (Exception e) { iPlayFd = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; logEx.Error("Start Receive camera video data failed.Exception message:{0}.", e.Message); } return(iPlayFd); }
/// <summary> /// 获取监控摄像头列表刷新状态,返回结果为0是表示刷新完毕,为1是刷新操作中。当查询刷新状态为0时,可调用获取监控摄像头列表接口,获取刷新后监控摄像头列表 /// </summary> /// <param name="refreshStatus">刷新状态</param> /// <returns></returns> public SmcErr GetRefreshStatus(out SmcErr refreshStatus) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.GetRefreshStatus"); SmcErr err = new CgwError(); refreshStatus = new SmcErr(); refreshStatus.ErrNo = CgwError.ERR_DEVICE_LIST_REFRESH_STATUS_END; if (refreshMonitorCameraOperateLock.TryEnterWriteLock(CgwConst.EFRESH_MONITOR_CAMERA_WAIT_TIME)) { try { refreshStatus.ErrNo = isRefreshSucess ? CgwError.ERR_DEVICE_LIST_REFRESH_STATUS_END : CgwError.ERR_DEVICE_LIST_REFRESH_STATUS_FAILED; } finally { refreshMonitorCameraOperateLock.ExitWriteLock(); } } else { refreshStatus.ErrNo = CgwError.ERR_DEVICE_LIST_REFRESH_STATUS_EXECUTING; } logEx.Info("GetRefreshStatus success."); return err; }
/// <summary> /// 预览摄像头视频,使用命名管道方式接收数据 /// </summary> /// <param name="cameraNo"></param> /// <param name="pipeName"></param> /// <returns></returns> public Cgw.SmcError.SmcErr StartReceiveVideoByPipe(string cameraNo, out string pipeName) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: CgwMonitorManageAdapter.StartReceiveVideoByPipe"); pipeName = ""; Cgw.SmcError.SmcErr err = new Cgw.SmcError.SmcErr(); try { //if (serviceControl.MonitorServiceRun() && client.State == CommunicationState.Opened) if (serviceControl.MonitorServiceRun()) { client = new MonitorManageServiceClient(); CgwMonitorManageServiceReference.SmcErr serviceErr = client.StartReceiveVideoByPipe(out pipeName, cameraNo); client.Close(); if (serviceErr.ErrNo != Cgw.SmcError.CgwError.ERR_MONITOR_MANAGE_SERVICE_SUCCESS) { logEx.Error("CgwMonitorManageAdapter.StartReceiveVideoByPipe failed. ErrNo = {0} ", serviceErr.ErrNo); err = SetCgwErrNo(serviceErr); } else { //将摄像头通道删除。避免重启服务后,VideoPipe未清除,导致调用停止播放。by zWX231378 2015/7/16 VideoPipe delVideoPipe = VideoPipeManage.Instance().DeleteVideoPipe(cameraNo); if (delVideoPipe != null) { logEx.Info("CgwMonitorManageAdapter.StartReceiveVideoByPipe delete VideoPipe. cameraNo = {0}", cameraNo); delVideoPipe.Stop(); } VideoPipe videoPipe = VideoPipeManage.Instance().AddVideoPipe(cameraNo, pipeName); if (videoPipe != null) { try { videoPipe.Run(); if (videoPipe.HaveConnect) { videoPipe.ReadData(this.dataCallBack); logEx.Info("CgwMonitorManageAdapter.StartReceiveVideoByPipe Success. pipeName = {0} ", pipeName); } else { logEx.Error("CgwMonitorManageAdapter.StartReceiveVideoByPipe failed. cameraNo = {0} ", cameraNo); } } catch (System.Exception ex) { logEx.Error("CgwMonitorManageAdapter.StartReceiveVideoByPipe Exception= {0} ", ex.ToString()); } } else { logEx.Error("CgwMonitorManageAdapter.StartReceiveVideoByPipe failed. cameraNo = {0} ", cameraNo); } } } else { //当监控服务未启动,则关闭管道。 //StopReceiveVideoByPipe(cameraNo); err.SetErrorNo(Cgw.SmcError.CgwError.ERR_MONITOR_MANAGE_SERVICE_RESTARTING); } } catch (System.Exception ex) { err.SetErrorNo(Cgw.SmcError.CgwError.ERR_MONITOR_MANAGE_SERVICE_RESTARTING); logEx.Error("CgwMonitorManageServiceReference.StartReceiveVideoByPipe failed. Exception is {0} ", ex.ToString()); } return(err); }
/// <summary> /// 启动摄像头预览 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <returns></returns> public SmcErr StartReceiveVideo(string cameraNo) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.StartReceiveVideo({0}).", cameraNo); SmcErr err = new CgwError(); TiandyCamera camera = null; Host host = null; //摄像头所连接的流媒体服务器 MediaServer cameraMediaServer = null; if (this.cameraOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { if (!this.tiandyCameraDictionary.ContainsKey(cameraNo)) { err.SetErrorNo(CgwError.CAMERA_NOT_FOUND); logEx.Error("Start Receive camera video data failed.Camera No is not found.Camera No:{0}", cameraNo); return err; } camera = this.tiandyCameraDictionary[cameraNo]; host = this.hostDictionary[camera.HostNo]; cameraMediaServer = this.mediaServerDictionary[host.MediaServerNo]; } catch (Exception e) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Start Receive camera video data failed.Camera No:{0},Execption message:{1}", cameraNo, e.Message); return err; } finally { this.cameraOperateLock.ExitReadLock(); } } if (camera == null) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Start Receive camera video data failed.Camera No is not found.Camera No:{0}", cameraNo); return err; } RealPlayInfo real = new RealPlayInfo(); real.ch = camera.Channel; real.data_type = (int)TiandyDateType.PRIMARY; real.hPlayWnd = null; int result = this.sdkClient.StartReceiveVideo(host.No, cameraMediaServer, ref real); //如果为负数,表示预览失败 if (result < 0) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Start Receive camera video data failed.Camera No:{0}.", cameraNo); return err; } else { //需要停止的预览句柄 int needToStopHandel = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; if (this.handelOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { //如果预览句柄已经存在,删除掉原来的句柄,用新的句柄替换 if (this.cameraVideoHandeDic.ContainsKey(cameraNo)) { needToStopHandel = this.cameraVideoHandeDic[cameraNo]; this.videoHandleCameraDic.Remove(needToStopHandel); this.cameraVideoHandeDic.Remove(cameraNo); } this.cameraVideoHandeDic.Add(cameraNo, result); this.videoHandleCameraDic.Add(result, cameraNo); } finally { this.handelOperateLock.ExitWriteLock(); } } logEx.Info("Start Receive camera video data success.Camera No:{0},Handle:{1}.", cameraNo, result); //重新预览后,更新了预览句柄,需要将原来的预览停止,放在handelOperateLock外面,防止长时间占用锁 if (needToStopHandel != CgwConst.START_RECEIVE_VIDEO_DATA_FAILED) { this.sdkClient.StopReceiveVideo(needToStopHandel); } } return err; }
/// <summary> /// 打开通道,开始接收实况RTP数据流 /// </summary> /// <param name="cameraCode">摄像机编码</param> /// <returns></returns> public UInt32 StartRecvStream(string cameraCode, string domain, string iSipPort, string localPort) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: SipStackAdapter.StartRecvStream cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); try { //接收视频码流RTP端口号 uint uiLocalRecvStreamVideoRtpPort = 0; //接收音频码流RTP端口号 uint uiLocalRecvStreamAudioRtpPort = 0; //通道号 UInt32 uiChannel = 0; //string strLocal = GetLocalIP(domain, Convert.ToInt32(iSipPort), Convert.ToInt32(localPort)); if (string.IsNullOrEmpty(localIP)) { localIP = GetLocalIP(domain, Convert.ToInt32(iSipPort), Convert.ToInt32(localPort)); } string strLocal = localIP; //获取可用通道 NetSourcedInterface.IVS_NETSOURCE_GetChannel(ref uiChannel); //用户参数,4字节整数 IntPtr pUser = Marshal.AllocHGlobal(4); Marshal.Copy(new int[1] { Convert.ToInt32(uiChannel) }, 0, pUser, 1); //设置媒体流回调函数 NetSourcedInterface.IVS_NETSOURCE_SetDataCallBack(uiChannel, cbDataCallBack, pUser); //异常回调函数 IVS_NETSOURCE_RESULT iRet = NetSourcedInterface.IVS_NETSOURCE_SetExceptionCallBack(cbNetExceptionCallBack, pUser); //协议类型 UDP iRet = NetSourcedInterface.IVS_NETSOURCE_SetProtocolType(uiChannel, 1); if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.StartRecvStream.IVS_NETSOURCE_SetProtocolType failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return(CgwConst.T28181_ERROR_HANDLE); } iRet = NetSourcedInterface.IVS_NETSOURCE_SetLocalRecvStreamIP(uiChannel, localIP); if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.StartRecvStream.IVS_NETSOURCE_SetLocalRecvStreamIP failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return(CgwConst.T28181_ERROR_HANDLE); } iRet = NetSourcedInterface.IVS_NETSOURCE_GetLocalRecvStreamPort(uiChannel, ref uiLocalRecvStreamVideoRtpPort, ref uiLocalRecvStreamAudioRtpPort); if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.StartRecvStream.IVS_NETSOURCE_GetLocalRecvStreamPort failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return(CgwConst.T28181_ERROR_HANDLE); } //Invite消息体 string strRealPlay = "v=0\r\n" + "o=" + cameraCode + @" 0 0 IN IP4 " + strLocal + "\r\n" + "s=Play\r\n" + "c=IN IP4 " + strLocal + "\r\n" + "t=0 0\r\n" + "m=video " + uiLocalRecvStreamVideoRtpPort + " RTP/AVP 96 98 97\r\n" + "a=recvonly\r\n" + "a=rtpmap:96 PS/90000\r\n" + "a=rtpmap:98 H264/90000\r\n" + "a=rtpmap:97 MPEG4/90000\r\n"; //发送SIP Invite消息 int iResponseID = 0; //制定字符串长度为1024 StringBuilder strRemoteBody = new StringBuilder(1024); //发送SIP Invite消息 EM_SIP_RESULT iSip = SIP_SDK_INVITE(cameraCode, strRealPlay, ref iResponseID, strRemoteBody); if (iSip != EM_SIP_RESULT.RET_SUCCESS) { logEx.Error("SipStackAdapter.SIP_SDK_INVITE failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return(CgwConst.T28181_ERROR_HANDLE); } //源端发送码流IP; string pRemoteSendStreamIp = ""; //源端发送视频码流RTP端口号 uint uiRemoteSendStreamVideoPort = 0; GetInviteRemoteIPPort(strRemoteBody.ToString(), ref pRemoteSendStreamIp, ref uiRemoteSendStreamVideoPort); iRet = NetSourcedInterface.IVS_NETSOURCE_OpenNetStream(uiChannel, pRemoteSendStreamIp, uiRemoteSendStreamVideoPort, 0);//无音频,传入0 if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.StartRecvStream failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); return(CgwConst.T28181_ERROR_HANDLE); } iRet = NetSourcedInterface.IVS_NETSOURCE_StartRecvStream(uiChannel); if (iRet == IVS_NETSOURCE_RESULT.SUCCESS) { channelResponseIDDic.Add(uiChannel, iResponseID); channelInPtrDic.Add(uiChannel, pUser); logEx.Info("SipStackAdapter.StartRecvStream pChannel: {0}, cameraCode :{1},domain = {2},iSipPort ={3} ", uiChannel, cameraCode, domain, iSipPort); return(uiChannel); } else { logEx.Error("SipStackAdapter.StartRecvStream failed. cameraCode :{0},domain = {1},iSipPort ={2}", cameraCode, domain, iSipPort); StopRecvStream(uiChannel); Marshal.FreeHGlobal(pUser); return(CgwConst.T28181_ERROR_HANDLE); } } catch (System.Exception ex) { logEx.Error("StartRecvStream failed.Exception message:{0},cameraCode :{0},domain = {1},iSipPort ={2}", ex.Message, cameraCode, domain, iSipPort); return(CgwConst.T28181_ERROR_HANDLE); } }
/// <summary> /// sdk回调函数,用于重连 /// </summary> /// <param name="iEventType">事件类型</param> /// <param name="pEventBuf"> 数据</param> /// <param name="uiBufSize">buf长度</param> /// <param name="pUserData">用户数据,自定义,相应回调函数被调用时返回该参数</param> public void IvsEventCallBackFunc(int iEventType, IvsUserOfflineOff pEventBuf, UInt32 uiBufSize, string pUserData) { if (10019 == iEventType || 10301 == iEventType)//用户下线通知、客户端登录失败 { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); IvsLoginInfo loginInfo = new IvsLoginInfo(); loginInfo.Ip = ip; loginInfo.Port = int.Parse(port); loginInfo.User = user; //loginInfo.Pwd = password; loginInfo.Pwd = CommonFunction.DecryptByte2Str(pwdByte,CgwConst.PASSWORD_TAG); logEx.Info("IvsEventCallBackFunc.user ={0}.", user); //使用线程轮询加载监控平台 Thread loaderThread = new Thread(LoginThread); loaderThread.IsBackground = true; loaderThread.Start(loginInfo); } }
/// <summary> /// 获取本机ip /// </summary> /// <returns></returns> private string GetLocalIP(string serverIP, int serverPort, int localPort) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: SipStackAdapter.GetLocalIP()."); try { IPAddress serverAddress = IPAddress.Parse(serverIP); IPAddress[] arrIPAddresses = Dns.GetHostAddresses(System.Environment.MachineName); foreach (IPAddress ip in arrIPAddresses) { //如果serverIP为IPv4 if (serverAddress.AddressFamily.Equals(AddressFamily.InterNetwork) && ip.AddressFamily.Equals(serverAddress.AddressFamily)) { #region IPv4 IPEndPoint serverEndpoint = new IPEndPoint(serverAddress, serverPort); Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint clientEndpoint = new IPEndPoint(ip, localPort); socketClient.Bind(clientEndpoint); try { socketClient.Connect(serverEndpoint); if (socketClient.Connected) { logEx.Trace("SipStackAdapter.try GetLocalIP ={0}.", ip.ToString()); return(ip.ToString()); } } catch (SocketException e) { //logEx.Warn("SipStackAdapter.GetLocalIP failed,e.ErrorCode:{0}", e.ErrorCode); if (e.ErrorCode == 10061 || e.ErrorCode == 10048) //Even No connection could be made because the target machine actively refused it ,but IP is valid. { logEx.Trace("SipStackAdapter.catch GetLocalIP ={0}.", ip.ToString()); return(ip.ToString()); } logEx.Error("SipStackAdapter.GetLocalIP failed.catch Execption message:{0}", e.Message); } finally { socketClient.Close(); logEx.Info("SipStackAdapter.GetLocalIP finally,Close the socketClient success"); } #endregion } //如果serverIP为IPv6 else if (serverAddress.AddressFamily.Equals(AddressFamily.InterNetworkV6) && ip.AddressFamily.Equals(serverAddress.AddressFamily)) { #region IPV6 IPEndPoint serverEndpoint = new IPEndPoint(serverAddress, serverPort); Socket socketClient = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); IPEndPoint clientEndpoint = new IPEndPoint(ip, localPort); socketClient.Bind(clientEndpoint); try { socketClient.Connect(serverEndpoint); if (socketClient.Connected) { logEx.Trace("SipStackAdapter.try GetLocalIP ={0}.", ip.ToString()); return(ip.ToString()); } } catch (SocketException e) { //logEx.Warn("SipStackAdapter.GetLocalIP failed,e.ErrorCode:{0}", e.ErrorCode); if (e.ErrorCode == 10061 || e.ErrorCode == 10048) //Even No connection could be made because the target machine actively refused it ,but IP is valid. { logEx.Trace("SipStackAdapter.catch GetLocalIP ={0}.", ip.ToString()); return(ip.ToString()); } logEx.Error("SipStackAdapter.GetLocalIP failed.catch Execption message:{0}", e.Message); } finally { socketClient.Close(); logEx.Info("SipStackAdapter.GetLocalIP finally,Close the socketClient success"); } #endregion } } return(null); } catch (System.Exception ex) { logEx.Error("SipStackAdapter.GetLocalIP failed.Execption message:{0}", ex.Message); return(null); } }
/// <summary> /// 指定码流回调函数 /// </summary> /// <param name="videoDataCallBack"></param> /// <param name="sender"></param> public void SetDataCallBackFunc(DataCallBack videoDataCallBack, string sender) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.SetVideoDataCallBackFunc()."); this.dataCallBack = videoDataCallBack; this.sender = sender; logEx.Info("Set VideoDataCallBackFunc success. Monitor id:{0}", this.monitorId); }
/// <summary> /// 初始化IVS监控平台 /// </summary> /// <param name="monitorConfigElement">监控平台配置节点</param> /// <returns></returns> public SmcErr Load(XmlElement monitorConfigElement) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Info("Enter: IvsVideoMonitor.Load()."); SmcErr err = new CgwError(); try { //解析xml节点,获取所需参数 this.monitorId = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.ID_TAG); ip = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.IP_TAG); port = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PORT_TAG); user = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.USER_TAG); //password = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PASSWORD_TAG); pwdByte = CommonFunction.EncryptStr2Byte(CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PASSWORD_TAG), CgwConst.PASSWORD_TAG); //从配置文件读取的参数要简单判断一下合法性 //初始化之前设置日志路径 logEx.Trace("Call SetLogPath:{0}", ivsLogPath); this.ivsSdkClient.SetLogPath(ivsLogPath); logEx.Trace("Call ivsSdkClient.Init()."); //初始化 int result = this.ivsSdkClient.Init(); if (result != CgwConst.IVS_SDK_SUCCESS_TAG) { //直接将IVS的错误码返回 err.SetErrorNo(CgwError.MONITOR_LOAD_FAILED); logEx.Error("Init ivs monitor failed.Monitor id:{0}.ivs sdk error code:{1}.", this.monitorId, result); return(err); } else { logEx.Info("Init ivs sdk success.Monitor id:{0}", this.monitorId); } //设置监控平台id this.ivsSdkClient.SetId(this.monitorId); this.sdkCallbackFunc = IvsRealPlayCallBackRaw; this.ivsSdkClient.SetRealPlayCBRawCallBackFunc(this.sdkCallbackFunc); //sdk事件回调 this.ivsEventCallBackFunc = IvsEventCallBackFunc; this.ivsSdkClient.SetEventCallBackFunc(this.ivsEventCallBackFunc); IvsLoginInfo loginInfo = new IvsLoginInfo(); loginInfo.Ip = ip; loginInfo.Port = int.Parse(port); loginInfo.User = user; //loginInfo.Pwd = password; loginInfo.Pwd = CommonFunction.DecryptByte2Str(pwdByte, CgwConst.PASSWORD_TAG); loadResult = false; //使用线程轮询加载监控平台 Thread loaderThread = new Thread(LoginThread); loaderThread.IsBackground = true; loaderThread.Start(loginInfo); } catch (Exception e) { err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID); logEx.Error("Load ivs monitor failed.Execption message:{0}.", e.Message); return(err); } logEx.Info("Load video monitor success.Monitor id:{0}.", this.monitorId); return(err); }
/// <summary> /// 启动摄像头预览 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <returns></returns> public SmcErr StartReceiveVideo(string cameraNo) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.StartReceiveVideo({0}).", cameraNo); SmcErr err = new CgwError(); int handle; logEx.Trace("Call ivsSdkClient.StartRealPlayCBRaw({0}).", cameraNo); int result = this.ivsSdkClient.StartRealPlayCBRaw(cameraNo, out handle); //如果不为0,表示预览失败 if (result != CgwConst.IVS_SDK_SUCCESS_TAG) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Start Receive camera video data failed.Camera No:{0}.Ivs sdk error code:{1}", cameraNo, result); return err; } else { logEx.Info("Start Receive camera video data success.Camera No:{0},Handle:{1}.", cameraNo, handle); } //预览成功,需要停止原来的预览,并将预览句柄添加到缓存 //需要停止的预览句柄 int needToStopHandel = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; if (this.handelOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { //如果预览句柄已经存在,删除掉原来的句柄,用新的句柄替换 if (this.cameraVideoHandeDic.ContainsKey(cameraNo)) { needToStopHandel = this.cameraVideoHandeDic[cameraNo]; this.videoHandleCameraDic.Remove(needToStopHandel); this.cameraVideoHandeDic.Remove(cameraNo); } this.cameraVideoHandeDic.Add(cameraNo, handle); MediaDataSender mediaDataSender = new MediaDataSender(cameraNo, this.dataCallBack); this.videoHandleCameraDic.Add(handle, mediaDataSender); } finally { this.handelOperateLock.ExitWriteLock(); } } //重新预览后,更新了预览句柄,需要将原来的预览停止,放在handelOperateLock外面,防止长时间占用锁 if (needToStopHandel != CgwConst.START_RECEIVE_VIDEO_DATA_FAILED) { result = this.ivsSdkClient.StopRealPlay(needToStopHandel); //如果不为0,表示停止原来的预览失败,只记录日志,不返回错误,不设置错误码 if (result != CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Error("Get a new preview success. But stop old preview failed.CameraNo:{0},Ivs sdk error code:{0}", cameraNo, result); return err; } } return err; }
/// <summary> /// 启动摄像头预览 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <returns></returns> public SmcErr StartReceiveVideo(string cameraNo) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.StartReceiveVideo({0}).", cameraNo); SmcErr err = new CgwError(); int handle; logEx.Trace("Call ivsSdkClient.StartRealPlayCBRaw({0}).", cameraNo); int result = this.ivsSdkClient.StartRealPlayCBRaw(cameraNo, out handle); //如果不为0,表示预览失败 if (result != CgwConst.IVS_SDK_SUCCESS_TAG) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Start Receive camera video data failed.Camera No:{0}.Ivs sdk error code:{1}", cameraNo, result); return(err); } else { logEx.Info("Start Receive camera video data success.Camera No:{0},Handle:{1}.", cameraNo, handle); } //预览成功,需要停止原来的预览,并将预览句柄添加到缓存 //需要停止的预览句柄 int needToStopHandel = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; if (this.handelOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { //如果预览句柄已经存在,删除掉原来的句柄,用新的句柄替换 if (this.cameraVideoHandeDic.ContainsKey(cameraNo)) { needToStopHandel = this.cameraVideoHandeDic[cameraNo]; this.videoHandleCameraDic.Remove(needToStopHandel); this.cameraVideoHandeDic.Remove(cameraNo); } this.cameraVideoHandeDic.Add(cameraNo, handle); MediaDataSender mediaDataSender = new MediaDataSender(cameraNo, this.dataCallBack); this.videoHandleCameraDic.Add(handle, mediaDataSender); } finally { this.handelOperateLock.ExitWriteLock(); } } //重新预览后,更新了预览句柄,需要将原来的预览停止,放在handelOperateLock外面,防止长时间占用锁 if (needToStopHandel != CgwConst.START_RECEIVE_VIDEO_DATA_FAILED) { result = this.ivsSdkClient.StopRealPlay(needToStopHandel); //如果不为0,表示停止原来的预览失败,只记录日志,不返回错误,不设置错误码 if (result != CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Error("Get a new preview success. But stop old preview failed.CameraNo:{0},Ivs sdk error code:{0}", cameraNo, result); return(err); } } return(err); }
/// <summary> /// 停止预览 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <returns>成功返回0,失败返回错误码</returns> public SmcErr StopReceiveVideo(string cameraNo) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.StopReceiveVideo({0}).", cameraNo); SmcErr err = new CgwError(); //需要停止的预览句柄 int needToStopHandel = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; if (this.handelOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { if (this.cameraVideoHandeDic.ContainsKey(cameraNo)) { needToStopHandel = this.cameraVideoHandeDic[cameraNo]; this.videoHandleCameraDic.Remove(needToStopHandel); this.cameraVideoHandeDic.Remove(cameraNo); } else { logEx.Warn("Stop Receive camera video data failed. Don't need to end the preview.Camera No:{0}.", cameraNo); //如果预览句柄不存在,不需要处理,直接返回 return err; } } catch (Exception ex) { err.SetErrorNo(CgwError.STOP_RECEIVE_VIDEO_FAILED); logEx.Error("Stop Receive camera video data failed.Execption message:{0}", ex.Message); return err; } finally { this.handelOperateLock.ExitWriteLock(); } } //调用sdk的停止方法,放在handelOperateLock外面,防止长时间占用锁 if (needToStopHandel != CgwConst.START_RECEIVE_VIDEO_DATA_FAILED) { int result = this.ivsSdkClient.StopRealPlay(needToStopHandel); //如果不为0,表示预览失败 if (result != CgwConst.IVS_SDK_SUCCESS_TAG) { err.SetErrorNo(CgwError.STOP_RECEIVE_VIDEO_FAILED); logEx.Error("Stop Receive camera video data failed.Ivs sdk error code:{0}", result); return err; } logEx.Info("Stop Receive camera video data success.Camera No:{0},Handle:{1}.", cameraNo, needToStopHandel); } return err; }
/// <summary> /// 启动摄像头预览 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <returns></returns> public SmcErr StartReceiveVideo(string cameraNo) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: T28181VideoMonitor.StartReceiveVideo({0}).", cameraNo); SmcErr err = new CgwError(); //打开通道,开始接收实况RTP数据流 UInt32 channel = sipStack.StartRecvStream(cameraNo, domain, sipPort); //如果为0,表示预览失败 if (channel == CgwConst.T28181_ERROR_HANDLE) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Start Receive camera video data failed.Camera No:{0}.Handle:{1}.", cameraNo, channel); return(err); } else { logEx.Info("Start Receive camera video data success.Camera No:{0},Handle:{1}.", cameraNo, channel); } //设置rtp解析回调函数 rtpAdapter.ESDK_RTP_OpenChannel(frameDataCallBack, channel); //预览成功,需要停止原来的预览,并将预览句柄添加到缓存 //需要停止的预览句柄 UInt32 needToStopChannel = CgwConst.T28181_ERROR_HANDLE; if (this.handelOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { //如果预览句柄已经存在,删除掉原来的句柄,用新的句柄替换 if (this.cameraVideoChannelDic.ContainsKey(cameraNo)) { needToStopChannel = this.cameraVideoChannelDic[cameraNo]; this.videoChannelDataSenderDic.Remove(needToStopChannel); this.cameraVideoChannelDic.Remove(cameraNo); //关闭rtp回调 rtpAdapter.ESDK_RTP_CloseChannel(needToStopChannel); } this.cameraVideoChannelDic.Add(cameraNo, channel); MediaDataSender mediaDataSender = new MediaDataSender(cameraNo, this.dataCallBack); this.videoChannelDataSenderDic.Add(channel, mediaDataSender); } finally { this.handelOperateLock.ExitWriteLock(); } } //重新预览后,更新了预览句柄,需要将原来的预览停止,放在handelOperateLock外面,防止长时间占用锁 if (needToStopChannel != CgwConst.T28181_ERROR_HANDLE) { int result = sipStack.StopRecvStream(needToStopChannel); //如果不为0,表示停止原来的预览失败,只记录日志,不返回错误,不设置错误码 if (result != CgwConst.IVS_SDK_SUCCESS_TAG) { err.SetErrorNo(CgwError.START_RECEIVE_VIDEO_FAILED); logEx.Error("Get a new preview success. But stop old preview failed.CameraNo:{0},Ivs sdk error code:{0}", cameraNo, result); return(err); } } return(err); }
/// <summary> /// 获取摄像头列表及分组信息 /// </summary> private void GetAllCamerasMethod() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.GetAllCamerasMethod()."); try { //1、获取系统中所有的域 List<IvsDomainRoute> ivsDomainRouteList; logEx.Trace("Call ivsSdkClient.GetDomainRoute()."); int result = this.ivsSdkClient.GetDomainRoute(out ivsDomainRouteList); if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("GetDomainRoute success.List count:{0}", ivsDomainRouteList.Count); } else { logEx.Error("GetDomainRoute failed.Ivs sdk error code:{0}", result); ClearCamera(); isRefreshSucess = false; return; } List<Camera> cameraListTemp = new List<Camera>(); List<CameraGroup> groupListTemp = new List<CameraGroup>(); List<NodeRelation> nodeRelationListTemp = new List<NodeRelation>(); Dictionary<string, NodeRelation> nodeRelationDicTemp = new Dictionary<string, NodeRelation>(); foreach (IvsDomainRoute route in ivsDomainRouteList) { //加上此判断条件的话,子域将不会作查目录处理,不合理,故注释掉 //if (route.ParentDomain != "") //{ // continue; //} Dictionary<string, IvsCameraGroup> ivsCameraGroupDic; logEx.Trace("Call ivsSdkClient.GetDeviceGroupList({0},{1},out groupCount, out ivsCameraGroupDic).", route.DomainCode, CgwConst.IVS_SDK_ROOTGROUP_TAG); result = this.ivsSdkClient.GetDeviceGroupList(route.DomainCode, CgwConst.IVS_SDK_ROOTGROUP_TAG, out ivsCameraGroupDic); if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("GetDeviceGroupList success.Current group count:{0}", ivsCameraGroupDic.Count); } else { logEx.Error("GetDeviceGroupList failed.Ivs sdk error code:{0}", result); ClearCamera(); isRefreshSucess = false; return; } //域也当做分组使用 string encodeDomainNo = CgwConst.IVS_SDK_ROOTGROUP_TAG + CgwConst.IVS_SDK_DOMAINCODE_SEPARATOR_TAG + route.DomainCode; CameraGroup domainGroup = new CameraGroup(encodeDomainNo, route.DomainName); groupListTemp.Add(domainGroup); List<string> pathDomainList = new List<string>(); RecursionGroupPath(route.DomainCode, ivsDomainRouteList,ref pathDomainList); NodeRelation nodeDomainRelation = new NodeRelation(encodeDomainNo, pathDomainList, CgwMonitorManage.Common.NodeType.GROUP); nodeRelationDicTemp.Add(encodeDomainNo, nodeDomainRelation); foreach (KeyValuePair<string, IvsCameraGroup> ivsCameraGroupKeyValue in ivsCameraGroupDic) { IvsCameraGroup group = ivsCameraGroupKeyValue.Value; string encodeGroupNo = group.GroupNo + CgwConst.IVS_SDK_DOMAINCODE_SEPARATOR_TAG + group.DomainCode; //添加组信息 CameraGroup cameraGroup = new CameraGroup(encodeGroupNo, group.GroupName); groupListTemp.Add(cameraGroup); List<string> pathList = new List<string>(); RecursionPath(group.GroupNo, ivsCameraGroupDic, ref pathList); NodeRelation nodeRelation = new NodeRelation(encodeGroupNo, pathList, CgwMonitorManage.Common.NodeType.GROUP); nodeRelationDicTemp.Add(encodeGroupNo, nodeRelation); } } //添加所有组节点 nodeRelationListTemp.AddRange(nodeRelationDicTemp.Values); List<IvsCamera> ivsCameraPageList = new List<IvsCamera>(); int cameraCount = 0; logEx.Trace("Call ivsSdkClient.GetDeviceList"); //查询第一页记录,同时获取摄像头个数 result = this.ivsSdkClient.GetDeviceList(CgwConst.PAGE_FIRST_INDEX, CgwConst.PAGE_LAST_INDEX, out cameraCount, out ivsCameraPageList); List<IvsCamera> ivsCameraLeaveList = new List<IvsCamera>(); //如果总记录大于一页的总记录数 if (cameraCount > CgwConst.PAGE_LAST_INDEX) { //一次将剩下所有记录查询出来 result = this.ivsSdkClient.GetDeviceList(CgwConst.PAGE_LAST_INDEX + 1, cameraCount, out cameraCount, out ivsCameraLeaveList); } if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("GetDeviceList success.Current group count:{0}", cameraCount); ivsCameraPageList.AddRange(ivsCameraLeaveList); } else { logEx.Error("GetDeviceList failed.Ivs sdk error code:{0}", result); ClearCamera(); isRefreshSucess = false; return; } foreach (IvsCamera ivsCamera in ivsCameraPageList) { Camera camera = new Camera(ivsCamera.No, ivsCamera.Name); camera.Status = ivsCamera.Status; List<string> cameraPathList = new List<string>(); //string encodeGroupNo = ivsCamera.GroupNo + CgwConst.IVS_SDK_DOMAINCODE_SEPARATOR_TAG + ivsCamera.DomainCode;//摄像头所属组号错误(与群组组号混淆了)。 string encodeGroupNo = ivsCamera.GroupNo; if (nodeRelationDicTemp.ContainsKey(encodeGroupNo)) { //如果自定义分组里面包含该摄像头的父节点,需要设置分组路径 cameraPathList.AddRange(nodeRelationDicTemp[encodeGroupNo].Path); cameraPathList.Add(encodeGroupNo); } NodeRelation nodeRelation = new NodeRelation(camera.No, cameraPathList, CgwMonitorManage.Common.NodeType.CAMERA); //解决问题单DTS2013080201001,规避因IVS服务器存在摄像头重复的bug导致融合网关异常的问题 if (!nodeRelationDicTemp.ContainsKey(camera.No)) { cameraListTemp.Add(camera); nodeRelationDicTemp.Add(camera.No, nodeRelation); } nodeRelationListTemp.Add(nodeRelation); } //nodeRelationListTemp.AddRange(nodeRelationDicTemp.Values); DateTime dtStart = DateTime.Now; DateTime dtNow = new DateTime(); while (!isGetDevicesFinish) { dtNow = DateTime.Now; if ((dtNow - dtStart).TotalSeconds > refreshDeviceListOverTime) { isRefreshSucess = false; return; } Thread.Sleep(1); continue; } //将实时获取的值放到缓存 if (this.cameraOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { this.cameraList = cameraListTemp; this.groupList = groupListTemp; this.nodeRelationList = nodeRelationListTemp; isRefreshSucess = true; } catch (Exception ex) { isRefreshSucess = false; logEx.Error("Set the list to the buffer failed. ", ex.Message); } finally { this.cameraOperateLock.ExitWriteLock(); } } else { isRefreshSucess = false; } } catch (System.Exception ex) { logEx.Error("GetAllCamerasMethod failed.Exception message:{0}", ex.Message); isRefreshSucess = false; } }
/// <summary> /// 停止预览 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <returns>成功返回0,失败返回错误码</returns> public SmcErr StopReceiveVideo(string cameraNo) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.StopReceiveVideo({0}).", cameraNo); SmcErr err = new CgwError(); //需要停止的预览句柄 int needToStopHandel = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; if (this.handelOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { if (this.cameraVideoHandeDic.ContainsKey(cameraNo)) { needToStopHandel = this.cameraVideoHandeDic[cameraNo]; this.videoHandleCameraDic.Remove(needToStopHandel); this.cameraVideoHandeDic.Remove(cameraNo); } else { //不存在,表示已经删除,不返回错误 //err.SetErrorNo(CgwError.STOP_RECEIVE_VIDEO_FAILED); logEx.Warn("Stop Receive camera video data failed. Don't need to end the preview.Camera No:{0}.", cameraNo); } } finally { this.handelOperateLock.ExitWriteLock(); } } //调用sdk的停止方法,放在handelOperateLock外面,防止长时间占用锁 if (needToStopHandel != CgwConst.START_RECEIVE_VIDEO_DATA_FAILED) { this.sdkClient.StopReceiveVideo(needToStopHandel); } logEx.Info("Stop Receive camera video data success.Camera No:{0},Handle:{1}.", cameraNo, needToStopHandel); return err; }
/// <summary> /// 获取摄像头列表及分组信息 /// </summary> /// <param name="fromMonitorSys">如果该值为true,则实时从监控平台获取,否则从融合网关缓存获取</param> /// <param name="cameraList">摄像头列表</param> /// <param name="groupList">组信息</param> /// <param name="nodeRelationList">分组关系</param> /// <returns></returns> public SmcErr GetAllCameras(PagesParam pageparam, out List <Camera> cameraList, out List <CameraGroup> groupList, out List <NodeRelation> nodeRelationList, out PageInfo pageinfo, PlatformLicenseInfo licenseInfo = null) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: VideoMonitorManage.GetAllCameras()."); SmcErr err = new CgwError(); cameraList = new List <Camera>(); groupList = new List <CameraGroup>(); nodeRelationList = new List <NodeRelation>(); pageinfo = new PageInfo(); //copy 一份,防止长时间占用锁 Dictionary <string, IVideoMonitor> monitorsDictionaryTemp = null; if (this.monitorsOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { monitorsDictionaryTemp = new Dictionary <string, IVideoMonitor>(monitorsDictionary); } catch (Exception e) { logEx.Error("Get all cameras failed.Execption message:{0}", e.Message); } finally { this.monitorsOperateLock.ExitReadLock(); } } if (monitorsDictionaryTemp == null) { //记录日志,获取*监控平台的摄像头列表失败 logEx.Error("Get all cameras from monitor failed.No any monitor."); err.SetErrorNo(CgwError.GET_ALL_CAMERAS_FAILED); return(err); } //循环已加载的所有的监控平台,将所有摄像头和分组组成一个list返回 foreach (KeyValuePair <string, IVideoMonitor> monitor in monitorsDictionaryTemp) { //if ((monitor.Key == "ivs" || monitor.Key == "tiandy" || monitor.Key == "T28181IVS") && licenseInfo.IsMonitorPlatform == false) //{ // logEx.Warn("GetAllCameras.smc license no right:{0}", monitor.Key); // continue; //} //if (monitor.Key == "eLTE" && licenseInfo.IsEltePlatform == false) //{ // logEx.Warn("GetAllCameras.smc license no right:{0}", monitor.Key); // continue; //} IVideoMonitor videoMonitor = monitor.Value; List <Camera> cameraListTemp; List <CameraGroup> groupListTemp; List <NodeRelation> nodeRelationListTemp; err = videoMonitor.GetAllCameras(out cameraListTemp, out groupListTemp, out nodeRelationListTemp); if (err.IsSuccess()) { //摄像头编号加上监控平台唯一标识 foreach (Camera camera in cameraListTemp) { camera.No = EncodeNo(camera.No, monitor.Key); cameraList.Add(camera); } //组编号加上监控平台唯一标识 foreach (CameraGroup cameraGroup in groupListTemp) { cameraGroup.No = EncodeNo(cameraGroup.No, monitor.Key); groupList.Add(cameraGroup); } //节点关系编号加上监控平台唯一标识 foreach (NodeRelation nodeRelation in nodeRelationListTemp) { nodeRelation.No = EncodeNo(nodeRelation.No, monitor.Key); List <string> pathListTemp = null; if (null != nodeRelation.Path) { pathListTemp = new List <string>(); foreach (string path in nodeRelation.Path) { pathListTemp.Add(EncodeNo(path, monitor.Key)); } } nodeRelation.Path = pathListTemp; nodeRelationList.Add(nodeRelation); } } else { //记录日志,获取*监控平台的摄像头列表失败 logEx.Error("Get all cameras from monitor failed.Monitor id:{0} ,Error code:{1}", monitor.Key, err.ErrNo); err.SetErrorNo(CgwError.GET_ALL_CAMERAS_FAILED); continue; } } //2015/2/26 打印日志 logEx.Info("all List Counts."); logEx.Info("cameraList:" + cameraList.Count); logEx.Info("groupList:" + groupList.Count); logEx.Info("nodeRelationList:" + nodeRelationList.Count); #region 判断传递的pageParam信息的合法性 //计算cameraList、groupList、nodeRelationList中数据最多的列表长度 int maxNum = (cameraList.Count > groupList.Count) ? cameraList.Count : groupList.Count; maxNum = maxNum > nodeRelationList.Count ? maxNum : nodeRelationList.Count; pageinfo.TotalRecords = maxNum; logEx.Info("GetAllCameras.pageparam.CurrentPage ={0},pageparam.NumberPerPage ={1}", pageparam.CurrentPage, pageparam.NumberPerPage); if (pageparam.CurrentPage <= 0 || pageparam.NumberPerPage <= 0) //如果当前页数或者每页条数小于0,则提示错误 { logEx.Error("The CurrentPage or NumberPerPage can not be smaller than zero ,the CurrentPage is {0},the NumberPerPage is {1}", pageparam.CurrentPage, pageparam.NumberPerPage); err.SetErrorNo(CgwError.GET_ALL_CAMERAS_FAILED); cameraList = new List <Camera>(); groupList = new List <CameraGroup>(); nodeRelationList = new List <NodeRelation>(); pageinfo = new PageInfo(); return(err); } else if (maxNum == 0) { pageinfo = new PageInfo(); return(err); } else if (maxNum % pageparam.NumberPerPage != 0) { if (pageparam.CurrentPage > (pageinfo.TotalRecords / pageparam.NumberPerPage + 1)) //如果当前页数大于记录总页数,则提示错误 { logEx.Error("The CurrentPage can not be more than The Total pageNum(odd),the CurrentPage is {0},the Total PageNum is {1}", pageparam.CurrentPage, pageinfo.TotalRecords / pageparam.NumberPerPage + 1); err.SetErrorNo(CgwError.GET_ALL_CAMERAS_FAILED); cameraList = new List <Camera>(); groupList = new List <CameraGroup>(); nodeRelationList = new List <NodeRelation>(); pageinfo = new PageInfo(); return(err); } } else { if (pageparam.CurrentPage > (pageinfo.TotalRecords / pageparam.NumberPerPage)) //如果当前页数大于记录总页数,则提示错误 { logEx.Error("The CurrentPage can not be more than The Total pageNum(even),the CurrentPage is {0},the Total PageNum is {1}", pageparam.CurrentPage, pageinfo.TotalRecords / pageparam.NumberPerPage); err.SetErrorNo(CgwError.GET_ALL_CAMERAS_FAILED); cameraList = new List <Camera>(); groupList = new List <CameraGroup>(); nodeRelationList = new List <NodeRelation>(); pageinfo = new PageInfo(); return(err); } } #endregion #region 设置返回项PageInfo的值 pageinfo.TotalRecords = maxNum; pageinfo.CurrentPage = pageparam.CurrentPage; if (pageinfo.TotalRecords % pageparam.NumberPerPage != 0) { pageinfo.TotalPages = pageinfo.TotalRecords / pageparam.NumberPerPage + 1; } else { pageinfo.TotalPages = pageinfo.TotalRecords / pageparam.NumberPerPage; } #endregion #region 分割数据列表 List <Camera> CameraListTemp = new List <Camera>();; List <CameraGroup> CameraGroupTemp = new List <CameraGroup>();; List <NodeRelation> CamerNodeRelationaListTemp = new List <NodeRelation>(); int BeforeCurrentPageNum = (pageparam.CurrentPage - 1) * pageparam.NumberPerPage; //vsd传递的当前页(PageParam.CurrentPage)之前的数据总数 //cameraList ↓↓ if (null != cameraList && cameraList.Count > 0) { for (int i = BeforeCurrentPageNum; i < BeforeCurrentPageNum + pageparam.NumberPerPage; i++) //i从0开始 { if (i > cameraList.Count - 1) { break; } CameraListTemp.Add(cameraList[i]); } cameraList = CameraListTemp; } //groupList↓↓ if (null != groupList && groupList.Count > 0) { for (int i = BeforeCurrentPageNum; i < BeforeCurrentPageNum + pageparam.NumberPerPage; i++) //将请求页中包含的数据读取出来,并赋值给groupList { if (i > groupList.Count - 1) { break; } CameraGroupTemp.Add(groupList[i]); } groupList = CameraGroupTemp; } //nodeRelationList↓↓ if (null != nodeRelationList && nodeRelationList.Count > 0) { for (int i = BeforeCurrentPageNum; i < BeforeCurrentPageNum + pageparam.NumberPerPage; i++) //将请求页中包含的数据读取出来,并赋值给nodeRelationList { if (i > nodeRelationList.Count - 1) { break; } CamerNodeRelationaListTemp.Add(nodeRelationList[i]); } nodeRelationList = CamerNodeRelationaListTemp; } #endregion logEx.Info("Get all cameras success."); //特殊处理,监控平台统一返回成功,做轮询处理 err.SetErrorNo(SmcErr.SMC_ERR_SUCCESS); return(err); }
/// <summary> /// 初始化T28181监控平台 /// </summary> /// <param name="monitorConfigElement">监控平台配置节点</param> /// <returns></returns> public SmcErr Load(System.Xml.XmlElement monitorConfigElement) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: T28181VideoMonitor.Load()."); SmcErr err = new CgwError(); try { //解析xml节点,获取所需参数 string queryDeviceTimeOut = string.Empty; monitorId = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.ID_TAG); domain = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.IP_TAG); sipPort = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.SIP_PORT); deviceID = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.Device_ID); username = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.USER_TAG); password = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PASSWORD_TAG); localPort = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.LOCAL_PORT); queryDeviceTimeOut = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.QueryDeviceTimeOut); //检测配置文件是否有错误 int iSipPort = 0; bool bRet = int.TryParse(sipPort, out iSipPort); if (bRet == false) { err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID); logEx.Error("Load T28181 monitor failed.Execption sipPort:{0}.", sipPort); return(err); } int iLocalPort = 0; bRet = int.TryParse(localPort, out iLocalPort); if (bRet == false) { err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID); logEx.Error("Load T28181 monitor failed.Execption localPort:{0}.", localPort); return(err); } bRet = int.TryParse(queryDeviceTimeOut, out iQueryDeviceTimeOut); //转为毫秒 iQueryDeviceTimeOut *= 1000; if (bRet == false) { err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID); logEx.Error("Load T28181 monitor failed.Execption QueryDeviceTimeOut:{0}.", iQueryDeviceTimeOut); return(err); } //开始连接、注册Sip服务器 StartConnectRegisterSip(domain, iSipPort, iLocalPort, username, password); //开始查询设备列表 Thread th = new Thread(new ThreadStart(() => { GetAllCamerasTimer(null, null); })); th.Start(); //启动定时器 updateCameraTimer.Start(); } catch (Exception e) { err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID); logEx.Error("Load T28181 monitor failed.Execption message:{0}.", e.Message); return(err); } logEx.Info("Load T28181 monitor success.Monitor id:{0}.", this.monitorId); return(err); }
/// <summary> /// 创建监控平台实例 /// </summary> /// <param name="monitorElement"></param> /// <returns></returns> private SmcErr CreateMonitor(string monitorId, string className, out IVideoMonitor videoMonitor) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: VideoMonitorManage.CreateMonitor()."); SmcErr err = new CgwError(); videoMonitor = null; if (this.monitorsOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { if (monitorsDictionary.ContainsKey(monitorId)) { //监控平台的id重复 err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID_ID_EXIST); logEx.Error("Monitor id has been exist. Monitor id:{0}.", monitorId); return(err); } } catch (Exception e) { logEx.Error("CreateMonitor failed..Execption message:{0}", e.Message); } finally { this.monitorsOperateLock.ExitWriteLock(); } } Type monitorType = Type.GetType(className); if (monitorType == null) { //class不合法 err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID_CLASS_INVALID); logEx.Error("The class of Monitor is invalid. Class:{0}, Monitor id:{1}.", className, monitorId); return(err); } try { //create instance logEx.Info("VideoMonitorManage.className = {0}", className); if (className == "CgwMonitorManage.eLTE.eLTEVideoMonitor,CgwMonitorManage.eLTE") { //eLTE dll放在eLTeSDK目录下,否则跟ivs DLL冲突 string strPath = System.AppDomain.CurrentDomain.BaseDirectory; System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(strPath + @"eLTeSDK\CgwMonitorManage.eLTE.dll"); Type[] types = assembly.GetTypes(); if (types.Length > 0) { monitorType = types.First((x) => x.FullName == "CgwMonitorManage.eLTE.eLTEVideoMonitor"); } } else if (className == "CgwMonitorManage.Ivs.IvsVideoMonitor,CgwMonitorManage.Ivs") { string strPath = System.AppDomain.CurrentDomain.BaseDirectory; System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(strPath + @"IVSSDK\CgwMonitorManage.Ivs.dll"); Type[] types = assembly.GetTypes(); if (types.Length > 0) { monitorType = types.First((x) => x.FullName == "CgwMonitorManage.Ivs.IvsVideoMonitor"); } } logEx.Info("VideoMonitorManage.monitorType = {0}", monitorType); videoMonitor = Activator.CreateInstance(monitorType) as CgwMonitorManage.Common.IVideoMonitor; } catch (Exception e) { //无法加载指定的类 err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID_CLASS_INVALID); logEx.Error("The class of Monitor is invalid. May be not as IVideoMonitor. Class:{0}, Monitor id:{1},Exception message:{2}.", className, monitorId, e.Message); return(err); } if (videoMonitor == null) { //无法加载指定的类 err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID_CLASS_INVALID); logEx.Error("The class of Monitor is invalid. May be not as IVideoMonitor. Class:{0}, Monitor id:{1}.", className, monitorId); return(err); } return(err); }
/// <summary> /// 开启服务函数 /// </summary> static void StartService() { MonitorManageService inist = MonitorManageService.Instance(); ServiceHost host = new ServiceHost(inist); inist.SetHost(host); host.Opened += delegate { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); Thread dbConnectionThread = new Thread(new ThreadStart(LoadMonitorTimer_Elapsed)); dbConnectionThread.Start(); logEx.Info("Enter: Start CgwMonitorManage.Service"); }; host.Open(); ServiceBase.Run(inist); }
/// <summary> /// 获取摄像头列表及分组信息 /// </summary> /// <param name="fromMonitorSys">如果该值为true,则实时从监控平台获取,否则从融合网关缓存获取</param> /// <param name="cameraList">摄像头列表</param> /// <param name="groupList">组信息</param> /// <param name="nodeRelationListT">分组关系</param> /// <returns></returns> public SmcErr GetAllCameras(out List<Camera> cameraList, out List<CameraGroup> groupList, out List<NodeRelation> nodeRelationListT) { monitorManageServiceGetCameraList.Stop(); isGetDevicesFinish = false; NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.GetAllCameras()."); SmcErr err = new CgwError(); cameraList = new List<Camera>(); groupList = new List<CameraGroup>(); nodeRelationListT = new List<NodeRelation>(); if (this.cameraOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { #region 深度克隆数据 foreach (KeyValuePair<string, TiandyCamera> tiandyCameraKeyValue in this.tiandyCameraDictionary) { TiandyCamera tiandyCamera = tiandyCameraKeyValue.Value; //从缓存获取 Camera camera = new Camera(tiandyCamera.No, tiandyCamera.Name); cameraList.Add(camera); } foreach (KeyValuePair<string, CameraGroup> groupDicKeyValue in this.groupDic) { CameraGroup cameraGroupTemp = new CameraGroup(groupDicKeyValue.Value.No, groupDicKeyValue.Value.Name); groupList.Add(cameraGroupTemp); } foreach (NodeRelation nodeRelation in this.nodeRelationList) { NodeRelation nodeRelationTemp = new NodeRelation(nodeRelation.No, nodeRelation.Path, nodeRelation.Type); nodeRelationListT.Add(nodeRelationTemp); } #endregion } catch (Exception e) { err.SetErrorNo(CgwError.GET_ALL_CAMERAS_FAILED); logEx.Error("Get all cameras failed.Execption message:{0}", e.Message); return err; } finally { this.cameraOperateLock.ExitReadLock(); } } monitorManageServiceGetCameraList.Start(); logEx.Info("Get all cameras success."); return err; }
/// <summary> /// 登陆http服务接口 /// </summary> /// <returns>成功返回登录信息对象,失败返回null</returns> public LoginInfo Login() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyHttpClient.Login()."); LoginInfo loginInfo = null; //设置访问天地伟业登陆接口的uri string requestUrl = string.Format( "{0}/LogIn.jsp?UserName={1}&Password={2}&LoginType=1", this.serverUrl, this.user, this.pwd); //日志不能记密码,单独处理 string logString = string.Format( "{0}/LogIn.jsp?UserName={1}&Password=******&LoginType=1", this.serverUrl, this.user); //调用HTTP接口获取json字符串 string loginInfoString = CallHttpInterface(requestUrl); if (!string.IsNullOrEmpty(loginInfoString)) { loginInfo = JsonUtil.ParseLoginInfo(loginInfoString); if (loginInfo == null) { logEx.Error("Login to http server failed.Url:{0}", logString); //返回失败设置错误码 } logEx.Info("Login to http server success.Url:{0}", logString); } else { //如果字符串为空,说明调用不成功 logEx.Error("Login to http server failed.Url:{0}", logString); loginInfo = null; } return loginInfo; }
/// <summary> /// 初始化天地伟业监控平台 /// </summary> /// <param name="monitorConfigElement">监控平台配置节点</param> /// <returns></returns> public SmcErr Load(XmlElement monitorConfigElement) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.Load()."); SmcErr err = new CgwError(); string userLevel = ""; //解析xml节点,获取所需参数 try { #region Tiandy视频监控平台(Easy7)连接信息 this.monitorId = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.ID_TAG); userLevel = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PTZCONTROLLEVEL_TAG); string httpUser = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PLATFORM_USER_TAG); string httpPassword = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PLATFORM_PASSWORD_TAG); string httpUrl = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.PLATFORM_URL_TAG); string mediaServerId = CommonFunction.GetSingleNodeValue(monitorConfigElement, CgwConst.MEDIASERVER_SERVERID_TAG); #endregion this.httpClient = new TiandyHttpClient(httpUrl, httpUser, httpPassword); //使用线程轮询加载监控平台 Thread loaderThread = new Thread(LoaderThread); loaderThread.Start(mediaServerId); } catch (Exception e) { err.SetErrorNo(CgwError.MONITOR_CONFIG_FILE_INVALID); logEx.Error("Load Tiandy monitor failed.Execption message:{0}.", e.Message); return err; } this.sdkClient = new TiandySdkClient(); //如果控制级别配置错误,只记录错误日志,不向外报错 try { this.sdkClient.PtzControlLevel = int.Parse(userLevel); } catch (Exception e) { logEx.Error("Ptz Control Level is invalid.Execption message:{0}.", e.Message); this.sdkClient.PtzControlLevel = CgwConst.PTZ_CONTROL_LEVEL; } logEx.Info("Load video monitor success.Monitor id:{0}.", this.monitorId); return err; }
/// <summary> /// 获取设备树 /// </summary> /// <param name="requestUrl"></param> /// <returns>成功返回对象列表,失败返回null</returns> private List<Resource> GetResourceTree(String requestUrl) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); List<Resource> resources = null; //调用HTTP接口获取json字符串 string resourceString = CallHttpInterface(requestUrl); if (!string.IsNullOrEmpty(resourceString)) { resources = JsonUtil.ParseResource(resourceString); if (resources == null) { logEx.Error("Call function GetResourceTree() failed."); } else { logEx.Info("Call function GetResourceTree() success."); } } else { //如果字符串为空,说明调用不成功 resources = null; logEx.Error("Call function GetResourceTree() failed."); } return resources; }
/// <summary> /// 设置麦克风状态 /// </summary> /// <param name="cameraNo"></param> /// <param name="isOn">麦克风是否开启</param> /// <returns></returns> public SmcErr SetMic(string cameraNo, bool isOn) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.SetMic({0},{1}).", cameraNo, isOn); SmcErr err = new CgwError(); if (this.micOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { if (this.cameraMicStatusDic.ContainsKey(cameraNo)) { this.cameraMicStatusDic[cameraNo] = isOn; } else { this.cameraMicStatusDic.Add(cameraNo, isOn); } } finally { this.micOperateLock.ExitWriteLock(); } } logEx.Info("Set Mic status success.Camera no:{0},isOn:{1}).", cameraNo, isOn); return err; }
/// <summary> /// 监控平台加载器,轮询加载,直到成功 /// </summary> /// <param name="loginInfo"></param> private void LoginThread(Object loginInfoObj) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.LoginThread()."); try { IvsLoginInfo loginInfo = loginInfoObj as IvsLoginInfo; while (!loadResult) { if (loginInfo == null) { logEx.Error("loginInfoObj is Null."); return; } //等待ivs sdk事件回调结束,再调用sdk接口,否则调用失败 Thread.Sleep(1000); logEx.Trace("Call ivsSdkClient.Login({0},{1},{2},******).", loginInfo.Ip, loginInfo.Port, loginInfo.User); //登陆 int result = this.ivsSdkClient.Login(loginInfo.Ip, loginInfo.Port, loginInfo.User, loginInfo.Pwd); if (result != CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Error("Login to ivs monitor failed.Monitor id:{0}.ip:{1}, port:{2}, user:{3}.ivs sdk error code:{4}.", this.monitorId, loginInfo.Ip, loginInfo.Port, loginInfo.User, result); //登陆失败,等待1分钟后再次尝试登陆 Thread.Sleep(CgwConst.RELOAD_MONITOR_WAIT_TIME); loadResult = false; continue; } else { logEx.Info("Login to ivs monitor success.Monitor id:{0}.ip:{1}, port:{2}, user:{3}.", this.monitorId, loginInfo.Ip, loginInfo.Port, loginInfo.User); loadResult = true; } this.GetAllCamerasTimer(null, null); //启动定时器 this.updateCameraTimer.Start(); } } catch (System.Exception ex) { logEx.Error("Load IVS monitor failed. Exception message:{0}.", ex.Message); } }
/// <summary> /// 停止云台控制,摄像头控制 /// </summary> /// <param name="cameraNo">摄像头编号</param> /// <param name="ptzCommand">命令类型</param> /// <returns></returns> public SmcErr StopControlPtz(string cameraNo, PtzCommandType ptzCommand) { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.StopControlPtz({0}).", cameraNo); SmcErr err = new CgwError(); int handel = CgwConst.START_RECEIVE_VIDEO_DATA_FAILED; if (this.handelOperateLock.TryEnterReadLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { if (this.cameraVideoHandeDic.ContainsKey(cameraNo)) { handel = this.cameraVideoHandeDic[cameraNo]; } else { logEx.Warn("The camera was not Preview.Don't need to end the control.Camera No:{0}.", cameraNo); } } finally { this.handelOperateLock.ExitReadLock(); } } if (handel != CgwConst.START_RECEIVE_VIDEO_DATA_FAILED) { Client_PTZ_Command client_ptz_command = new Client_PTZ_Command(); client_ptz_command.start = false; //将ptz命令转换成天地伟业的命令 string name = Enum.GetName(typeof(PtzCommandType), ptzCommand); if (Enum.IsDefined(typeof(TiandyPtzCommandType), name)) { TiandyPtzCommandType tiandyPtzCommandType = (TiandyPtzCommandType)Enum.Parse(typeof(TiandyPtzCommandType), name); client_ptz_command.cmd = (int)tiandyPtzCommandType; } else { err.SetErrorNo(CgwError.STOP_CONTROL_PTZ_FAILED); logEx.Error("The tiandy monitor is not support the command.ptzCommand:{0}.", ptzCommand); return err; } bool result = this.sdkClient.ControlPtz(handel, client_ptz_command); if (result) { logEx.Info("Stop control camera ptz success.Camera No:{0}.", cameraNo); } else { err.SetErrorNo(CgwError.STOP_CONTROL_PTZ_FAILED); logEx.Error("Stop control camera ptz failed.Camera No:{0}.", cameraNo); } } else { err.SetErrorNo(CgwError.STOP_CONTROL_PTZ_FAILED); logEx.Error("Handel is not found. Stop control camera ptz failed. Camera No:{0}.", cameraNo); return err; } return err; }
/// <summary> /// 释放所有实况通道,释放NETSOURCE资源 /// </summary> public IVS_NETSOURCE_RESULT IVS_NETSOURCE_UnInit() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: SipStackAdapter.IVS_NETSOURCE_UnInit."); //IVS_NETSOURCE_RESULT iRet = IVS_NETSOURCE_RESULT.FAILURE; IVS_NETSOURCE_RESULT iRet = IVS_NETSOURCE_RESULT.SUCCESS; try { foreach (KeyValuePair<UInt32, int> kvp in channelResponseIDDic) { UInt32 channel = kvp.Key; iRet = NetSourcedInterface.IVS_NETSOURCE_CloseNetStream(channel); if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.IVS_NETSOURCE_CloseNetStream channelResponseIDDic = {0}.", channel); //注销return,避免返回,不实现IVS_NETSOURCE_UnInit //return iRet; } iRet = NetSourcedInterface.IVS_NETSOURCE_FreeChannel(channel); if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) { logEx.Error("SipStackAdapter.IVS_NETSOURCE_FreeChannel channelResponseIDDic = {0}.", channel); //注销return,避免返回,不实现IVS_NETSOURCE_UnInit //return iRet; } } //iRet = NetSourcedInterface.IVS_NETSOURCE_UnInit(); //if (iRet != IVS_NETSOURCE_RESULT.SUCCESS) //{ // logEx.Error("SipStackAdapter.IVS_NETSOURCE_UnInit failed."); //} NetSourcedInterface.IVS_NETSOURCE_UnInit(); logEx.Info("Leave: SipStackAdapter.IVS_NETSOURCE_UnInit."); } catch (System.Exception ex) { logEx.Error("SipStackAdapter.IVS_NETSOURCE_UnInit Error = {0}.", ex.ToString()); iRet = IVS_NETSOURCE_RESULT.FAILURE; } return iRet; }
/// <summary> /// 注销天地伟业监控平台资源 /// </summary> /// <returns></returns> public SmcErr Unload() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: TiandyVideoMonitor.Unload()."); SmcErr err = new CgwError(); //停止定时器 this.updateCameraTimer.Stop(); if (this.sdkClient.Unload()) { logEx.Info("Unload video monitor success.Monitor id:{0}.", this.monitorId); } else { err.SetErrorNo(CgwError.UNLOAD_MONITOR_FAILED); logEx.Error("Unload video monitor failed.Monitor id:{0}.", this.monitorId); } return err; }
/// <summary> /// 获取摄像头列表及分组信息 /// </summary> private void GetAllCamerasMethod() { NLogEx.LoggerEx logEx = new NLogEx.LoggerEx(log); logEx.Trace("Enter: IvsVideoMonitor.GetAllCamerasMethod()."); try { //1、获取系统中所有的域 List <IvsDomainRoute> ivsDomainRouteList; logEx.Trace("Call ivsSdkClient.GetDomainRoute()."); int result = this.ivsSdkClient.GetDomainRoute(out ivsDomainRouteList); if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("GetDomainRoute success.List count:{0}", ivsDomainRouteList.Count); } else { logEx.Error("GetDomainRoute failed.Ivs sdk error code:{0}", result); ClearCamera(); isRefreshSucess = false; return; } List <Camera> cameraListTemp = new List <Camera>(); List <CameraGroup> groupListTemp = new List <CameraGroup>(); List <NodeRelation> nodeRelationListTemp = new List <NodeRelation>(); Dictionary <string, NodeRelation> nodeRelationDicTemp = new Dictionary <string, NodeRelation>(); foreach (IvsDomainRoute route in ivsDomainRouteList) { //加上此判断条件的话,子域将不会作查目录处理,不合理,故注释掉 //if (route.ParentDomain != "") //{ // continue; //} Dictionary <string, IvsCameraGroup> ivsCameraGroupDic; logEx.Trace("Call ivsSdkClient.GetDeviceGroupList({0},{1},out groupCount, out ivsCameraGroupDic).", route.DomainCode, CgwConst.IVS_SDK_ROOTGROUP_TAG); result = this.ivsSdkClient.GetDeviceGroupList(route.DomainCode, CgwConst.IVS_SDK_ROOTGROUP_TAG, out ivsCameraGroupDic); if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("GetDeviceGroupList success.Current group count:{0}", ivsCameraGroupDic.Count); } else { logEx.Error("GetDeviceGroupList failed.Ivs sdk error code:{0}", result); ClearCamera(); isRefreshSucess = false; return; } //域也当做分组使用 string encodeDomainNo = CgwConst.IVS_SDK_ROOTGROUP_TAG + CgwConst.IVS_SDK_DOMAINCODE_SEPARATOR_TAG + route.DomainCode; CameraGroup domainGroup = new CameraGroup(encodeDomainNo, route.DomainName); groupListTemp.Add(domainGroup); List <string> pathDomainList = new List <string>(); RecursionGroupPath(route.DomainCode, ivsDomainRouteList, ref pathDomainList); NodeRelation nodeDomainRelation = new NodeRelation(encodeDomainNo, pathDomainList, CgwMonitorManage.Common.NodeType.GROUP); nodeRelationDicTemp.Add(encodeDomainNo, nodeDomainRelation); foreach (KeyValuePair <string, IvsCameraGroup> ivsCameraGroupKeyValue in ivsCameraGroupDic) { IvsCameraGroup group = ivsCameraGroupKeyValue.Value; string encodeGroupNo = group.GroupNo + CgwConst.IVS_SDK_DOMAINCODE_SEPARATOR_TAG + group.DomainCode; //添加组信息 CameraGroup cameraGroup = new CameraGroup(encodeGroupNo, group.GroupName); groupListTemp.Add(cameraGroup); List <string> pathList = new List <string>(); RecursionPath(group.GroupNo, ivsCameraGroupDic, ref pathList); NodeRelation nodeRelation = new NodeRelation(encodeGroupNo, pathList, CgwMonitorManage.Common.NodeType.GROUP); nodeRelationDicTemp.Add(encodeGroupNo, nodeRelation); } } //添加所有组节点 nodeRelationListTemp.AddRange(nodeRelationDicTemp.Values); List <IvsCamera> ivsCameraPageList = new List <IvsCamera>(); int cameraCount = 0; logEx.Trace("Call ivsSdkClient.GetDeviceList"); //查询第一页记录,同时获取摄像头个数 result = this.ivsSdkClient.GetDeviceList(CgwConst.PAGE_FIRST_INDEX, CgwConst.PAGE_LAST_INDEX, out cameraCount, out ivsCameraPageList); List <IvsCamera> ivsCameraLeaveList = new List <IvsCamera>(); //如果总记录大于一页的总记录数 if (cameraCount > CgwConst.PAGE_LAST_INDEX) { //一次将剩下所有记录查询出来 result = this.ivsSdkClient.GetDeviceList(CgwConst.PAGE_LAST_INDEX + 1, cameraCount, out cameraCount, out ivsCameraLeaveList); } if (result == CgwConst.IVS_SDK_SUCCESS_TAG) { logEx.Info("GetDeviceList success.Current group count:{0}", cameraCount); ivsCameraPageList.AddRange(ivsCameraLeaveList); } else { logEx.Error("GetDeviceList failed.Ivs sdk error code:{0}", result); ClearCamera(); isRefreshSucess = false; return; } foreach (IvsCamera ivsCamera in ivsCameraPageList) { Camera camera = new Camera(ivsCamera.No, ivsCamera.Name); camera.Status = ivsCamera.Status; List <string> cameraPathList = new List <string>(); //string encodeGroupNo = ivsCamera.GroupNo + CgwConst.IVS_SDK_DOMAINCODE_SEPARATOR_TAG + ivsCamera.DomainCode;//摄像头所属组号错误(与群组组号混淆了)。 string encodeGroupNo = ivsCamera.GroupNo; if (nodeRelationDicTemp.ContainsKey(encodeGroupNo)) { //如果自定义分组里面包含该摄像头的父节点,需要设置分组路径 cameraPathList.AddRange(nodeRelationDicTemp[encodeGroupNo].Path); cameraPathList.Add(encodeGroupNo); } NodeRelation nodeRelation = new NodeRelation(camera.No, cameraPathList, CgwMonitorManage.Common.NodeType.CAMERA); //解决问题单DTS2013080201001,规避因IVS服务器存在摄像头重复的bug导致融合网关异常的问题 if (!nodeRelationDicTemp.ContainsKey(camera.No)) { cameraListTemp.Add(camera); nodeRelationDicTemp.Add(camera.No, nodeRelation); } nodeRelationListTemp.Add(nodeRelation); } //nodeRelationListTemp.AddRange(nodeRelationDicTemp.Values); DateTime dtStart = DateTime.Now; DateTime dtNow = new DateTime(); while (!isGetDevicesFinish) { dtNow = DateTime.Now; if ((dtNow - dtStart).TotalSeconds > refreshDeviceListOverTime) { isRefreshSucess = false; return; } Thread.Sleep(1); continue; } //将实时获取的值放到缓存 if (this.cameraOperateLock.TryEnterWriteLock(CgwConst.ENTER_LOCK_WAIT_TIME)) { try { this.cameraList = cameraListTemp; this.groupList = groupListTemp; this.nodeRelationList = nodeRelationListTemp; isRefreshSucess = true; } catch (Exception ex) { isRefreshSucess = false; logEx.Error("Set the list to the buffer failed. ", ex.Message); } finally { this.cameraOperateLock.ExitWriteLock(); } } else { isRefreshSucess = false; } } catch (System.Exception ex) { logEx.Error("GetAllCamerasMethod failed.Exception message:{0}", ex.Message); isRefreshSucess = false; } }