/// <summary> /// Named pipe server through P/Invoke-ing the native APIs /// </summary> static void PInvokeNativePipeServer() { ///////////////////////////////////////////////////////////////////// // Create a named pipe. // // Prepare the pipe name String strPipeName = String.Format(@"\\{0}\pipe\{1}", ".", // Server name "HelloWorld" // Pipe name ); // Prepare the security attributes IntPtr pSa = IntPtr.Zero; // NULL SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); SECURITY_DESCRIPTOR sd; SecurityNative.InitializeSecurityDescriptor(out sd, 1); // DACL is set as NULL to allow all access to the object. SecurityNative.SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false); sa.lpSecurityDescriptor = Marshal.AllocHGlobal(Marshal.SizeOf( typeof(SECURITY_DESCRIPTOR))); Marshal.StructureToPtr(sd, sa.lpSecurityDescriptor, false); sa.bInheritHandle = false; // Not inheritable sa.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); pSa = Marshal.AllocHGlobal(sa.nLength); Marshal.StructureToPtr(sa, pSa, false); // Create the named pipe. IntPtr hPipe = PipeNative.CreateNamedPipe( strPipeName, // The unique pipe name. PipeOpenMode.PIPE_ACCESS_DUPLEX, // The pipe is bi-directional PipeMode.PIPE_TYPE_MESSAGE | // Message type pipe PipeMode.PIPE_READMODE_MESSAGE | // Message-read mode PipeMode.PIPE_WAIT, // Blocking mode is on PipeNative.PIPE_UNLIMITED_INSTANCES, // Max server instances BUFFER_SIZE, // Output buffer size BUFFER_SIZE, // Input buffer size PipeNative.NMPWAIT_USE_DEFAULT_WAIT, // Time-out interval pSa // Pipe security attributes ); if (hPipe.ToInt32() == PipeNative.INVALID_HANDLE_VALUE) { Console.WriteLine("Unable to create named pipe {0} w/err 0x{1:X}", strPipeName, PipeNative.GetLastError()); return; } Console.WriteLine("The named pipe, {0}, is created.", strPipeName); ///////////////////////////////////////////////////////////////////// // Wait for the client to connect. // Console.WriteLine("Waiting for the client's connection..."); bool bConnected = PipeNative.ConnectNamedPipe(hPipe, IntPtr.Zero) ? true : PipeNative.GetLastError() == PipeNative.ERROR_PIPE_CONNECTED; if (!bConnected) { Console.WriteLine( "Error occurred while connecting to the client: 0x{0:X}", PipeNative.GetLastError()); PipeNative.CloseHandle(hPipe); // Close the pipe handle. return; } ///////////////////////////////////////////////////////////////////// // Read client requests from the pipe and write the response. // // A byte buffer of BUFFER_SIZE bytes. The buffer should be big // enough for ONE request from a client. string strMessage; byte[] bRequest = new byte[BUFFER_SIZE];// Client -> Server uint cbBytesRead, cbRequestBytes; byte[] bReply; // Server -> Client uint cbBytesWritten, cbReplyBytes; bool bResult; while (true) { // Receive one message from the pipe. cbRequestBytes = BUFFER_SIZE; bResult = PipeNative.ReadFile( // Read from the pipe. hPipe, // Handle of the pipe bRequest, // Buffer to receive data cbRequestBytes, // Size of buffer in bytes out cbBytesRead, // Number of bytes read IntPtr.Zero); // Not overlapped I/O if (!bResult /*Failed*/ || cbBytesRead == 0 /*Finished*/) { break; } // Unicode-encode the byte array and trim all the '\0' chars at // the end. strMessage = Encoding.Unicode.GetString(bRequest).TrimEnd('\0'); Console.WriteLine("Receives {0} bytes; Message: \"{1}\"", cbBytesRead, strMessage); // Prepare the response. // '\0' is appended in the end because the client may be a native // C++ program. strMessage = "Default response from server\0"; bReply = Encoding.Unicode.GetBytes(strMessage); cbReplyBytes = (uint)bReply.Length; // Write the response to the pipe. bResult = PipeNative.WriteFile( // Write to the pipe. hPipe, // Handle of the pipe bReply, // Buffer to write to cbReplyBytes, // Number of bytes to write out cbBytesWritten, // Number of bytes written IntPtr.Zero); // Not overlapped I/O if (!bResult /*Failed*/ || cbReplyBytes != cbBytesWritten /*Failed*/) { Console.WriteLine("WriteFile failed w/err 0x{0:X}", PipeNative.GetLastError()); break; } Console.WriteLine("Replies {0} bytes; Message: \"{1}\"", cbBytesWritten, strMessage.TrimEnd('\0')); } ///////////////////////////////////////////////////////////////////// // Flush the pipe to allow the client to read the pipe's contents // before disconnecting. Then disconnect the pipe, and close the // handle to this pipe instance. // PipeNative.FlushFileBuffers(hPipe); PipeNative.DisconnectNamedPipe(hPipe); PipeNative.CloseHandle(hPipe); }
public void init() { SYSTEM_INFO sys_info = new SYSTEM_INFO(); PipeNative.GetSystemInfo(out sys_info); sizeObjInfo = (uint)Marshal.SizeOf(cDataInfo); sizeObjData = (uint)Marshal.SizeOf(cinData); NUMBER_OF_MAP_VIEW = 5; uint FILE_MAP_START = 65536; uint sysGran = sys_info.allocationGranularity; uint fileMapStart = (FILE_MAP_START / sysGran) * sysGran; uint mapViewSize1 = (FILE_MAP_START % sysGran) + sizeObjInfo; uint mapViewSize = (FILE_MAP_START % sysGran) + sizeObjData * 2; uint fileMapSize = FILE_MAP_START + sizeObjData; int iViewDelta = (int)(FILE_MAP_START - fileMapStart); /// CHAI3D mapping create // outmap coutFileMap = PipeNative.CreateFileMapping(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Zero, FileMapProtection.PageReadWrite | FileMapProtection.SectionCommit, 0, 139264, "chai3d2manager"); if (coutFileMap == IntPtr.Zero) { errMsg = "outFile (Recving) CreateFileMapping() Error."; } else { coutMapAddress = PipeNative.MapViewOfFile(coutFileMap, FileMapAccess.FILE_MAP_ALL_ACCESS, 0, 0, 0); if (coutMapAddress == IntPtr.Zero) { errMsg = "outFile (Recving) MapViewOfFile() Error."; // tell it's an error } else { errMsg = "Recving No Problem!"; //initialAngles = gimbalModule.getAngle(); coutData.currentHIPX = 0.0f; coutData.currentHIPY = 0.0f; coutData.currentHIPZ = 0.0f; Marshal.StructureToPtr(coutData, coutMapAddress, false); } } // inmap cinFileMap = PipeNative.CreateFileMapping(IntPtr.Subtract(IntPtr.Zero, 1), IntPtr.Zero, FileMapProtection.PageReadWrite | FileMapProtection.SectionCommit, 0, sysGran * NUMBER_OF_MAP_VIEW, "HDhaptics"); if (cinFileMap == IntPtr.Zero) { errMsg = "inFile (Sending) CreateFileMapping() Error."; } else { //uint sizeObjNum = (uint) Marshal.SizeOf(cinDataNum); //uint sizeObjData = (uint) Marshal.SizeOf(cinData); cinMapAddress = PipeNative.MapViewOfFile(cinFileMap, FileMapAccess.FILE_MAP_ALL_ACCESS, 0, 0, sysGran); if (cinMapAddress == IntPtr.Zero) { errMsg = "inFile (Sending) MapViewOfFile() Error."; // tell it's an error } else { errMsg = "No Sending Problem!"; // TODO: Sending Information Initialization //cinData.numberOfObject = 10; cDataInfo.sysGran = (int)sysGran; cDataInfo.HIPx = 0f; cDataInfo.HIPy = 0f; cDataInfo.HIPz = 0f; cDataInfo.numberOfView = (int)NUMBER_OF_MAP_VIEW - 1; //cDataInfo.sizeOfView = new int[4] { (int)sysGran, (int)sysGran, (int)sysGran, (int)sysGran }; //cinData.objectPositionX = new float[10] { 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f }; //cinData.objectPositionY = new float[10] { 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f }; //cinData.objectPositionZ = new float[10] { 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f }; Marshal.StructureToPtr(cDataInfo, cinMapAddress, false); //Marshal.StructureToPtr() int[] sizeOfViews = new int[4] { (int)sysGran, (int)sysGran, (int)sysGran, (int)sysGran }; //Marshal.Copy(sizeOfViews, 0, cinMapAddress + (int)sizeObjInfo, sizeOfViews.Length); for (int i = 0; i < sizeOfViews.Length; i++) { Marshal.WriteInt32(cinMapAddress + (int)sizeObjInfo + i * 4, sizeOfViews[i]); } //numberOfMapView = Marshal.AllocHGlobal((int) NUMBER_OF_MAP_VIEW * 4); } //////// cinMapAddressData = PipeNative.MapViewOfFile(cinFileMap, FileMapAccess.FILE_MAP_ALL_ACCESS, 0, fileMapStart, sysGran); if (cinMapAddressData == IntPtr.Zero) { errMsg = PipeNative.GetLastError() + " // inFile (Sending) MapViewOfFile() Error."; // tell it's an error } else { errMsg = "No Sending Problem!"; // TODO: Sending Information Initialization //cinData.numberOfObject = 10; ObjectNum objectNum; objectNum.numberOfObject = 0; Marshal.StructureToPtr(objectNum, cinMapAddressData, false); //int sizeObjNum = Marshal.SizeOf(objectNum); //cinData.objectPosX = 1f; //cinData.objectPosY = 1f; //cinData.objectPosZ = 1f; //cinData.objectRotX = 0f; //cinData.objectRotY = 0f; //cinData.objectRotZ = 0f; //Marshal.StructureToPtr(cinData, cinMapAddressData + sizeObjNum, false); ////Marshal.StructureToPtr() //cinData2.objectPosX = 2f; //cinData2.objectPosY = 2f; //cinData2.objectPosZ = 2f; //cinData2.objectRotX = 0f; //cinData2.objectRotY = 0f; //cinData2.objectRotZ = 0f; //Marshal.StructureToPtr(cinData2, cinMapAddressData + (int) sizeObjData + sizeObjNum, false); } //////// /* * cinMapAddressData2 = PipeNative.MapViewOfFile(cinFileMap, FileMapAccess.FILE_MAP_ALL_ACCESS, 0, fileMapStart, sizeObjData); * if (cinMapAddressData2 == IntPtr.Zero) * { * errMsg = PipeNative.GetLastError() + " // inFile (Sending) MapViewOfFile() Error."; * // tell it's an error * } * else * { * * errMsg = "No Sending Problem!"; * // TODO: Sending Information Initialization * cinData2.objectPosX = 2f; * cinData2.objectPosY = 2f; * cinData2.objectPosZ = 2f; * cinData2.objectRotX = 0f; * cinData2.objectRotY = 0f; * cinData2.objectRotZ = 0f; * * Marshal.StructureToPtr(cinData2, cinMapAddressData2, false); * //Marshal.StructureToPtr() * } */ } CHAI3Dthread = new Thread(CHAI3dThread); CHAI3Dthread.Start(); }
public void runing(object param) { try { bool calculate_flag = true; byte[] writebuffer = new byte[20480]; //String strPipeName = @"\\.\pipe\myPipe2"; string g_czPipName_Base = "\\\\.\\pipe\\HST_Output_Pip_Gpu_%d"; //0~3 string strPipeName = "\\\\.\\pipe\\HST_Output_Pip_Gpu_0"; Console.WriteLine(strPipeName); DataRec dr = new DataRec(Convert.ToInt32(param)); while (true) { Thread.Sleep(1000); if (dr.PipeFlag) { while (true)//连接管道 { //dr.hPipe = PipeNative.WaitNamedPipe dr.hPipe = PipeNative.CreateFile( strPipeName, //管道名称 FileDesiredAccess.GENERIC_READ | FileDesiredAccess.GENERIC_WRITE, //访问模式,读模式或写模式 FileShareMode.Zero, //0表示不共享,共享模式 IntPtr.Zero, //一个只读字段,代表已初始化为零的指针或句柄。指向安全属性的指针 FileCreationDisposition.OPEN_EXISTING, //如何创建。文件必须已经存在。由设备提出要求 0, //文件属性 0); //用于复制文件句柄,不使用模板 if (dr.hPipe.ToInt32() != PipeNative.INVALID_HANDLE_VALUE) { break; //PipeNative.INVALID_HANDLE_VALUE = -1.管道创建失败 } if (PipeNative.GetLastError() != PipeNative.ERROR_PIPE_BUSY || //PipeNative.ERROR_PIPE_BUSY = 231 PipeNative.WaitNamedPipe(strPipeName, 5 * 1000)) //在超时时间前管道的一个实例有效则返回非0,在超时时间内没有一个有效的实例,则返回0 { Console.WriteLine("无法连接管道:{0} ERROR:{1}", strPipeName, PipeNative.GetLastError()); continue; } else { Console.WriteLine("管道连接成功:{0}", strPipeName); } } while (dr.PipeFlag) { #region [接收数据] SHstPipeInfo sPipeInfo = new SHstPipeInfo(); MyPipPersistane myPipPersistane = new MyPipPersistane(); int iRes = myPipPersistane.ReadPipeInfo(dr.hPipe, ref sPipeInfo); if (iRes == 0) { //todo 参数处理 Console.WriteLine("\r ReadPipeInfo videocount: {0} time: {1} \t v0:{2}:{3} \t v1:{4}:{5} \t v2:{6}:{7} \t v3:{8}:{9} \t" , sPipeInfo.iVideoCount, sPipeInfo.szVideoInfo[0].i64Time , sPipeInfo.szVideoInfo[0].iVideoID, sPipeInfo.szVideoInfo[0].iObjCount , sPipeInfo.szVideoInfo[1].iVideoID, sPipeInfo.szVideoInfo[1].iObjCount , sPipeInfo.szVideoInfo[2].iVideoID, sPipeInfo.szVideoInfo[2].iObjCount , sPipeInfo.szVideoInfo[3].iVideoID, sPipeInfo.szVideoInfo[3].iObjCount ); continue; //测试用,需删除 吴超 //Console.WriteLine("{0},{1}", sPipeInfo.szVideoInfo[0].iVideoID, sPipeInfo.szVideoInfo[0].szObjInfo[0].center_x); //Console.WriteLine("***********{0}************",sPipeInfo.szVideoInfo[0].szObjInfo[0].ID); bool caculateflag = true; //Console.WriteLine("{0} ready to caculate", param.ToString()); if (simulation_flag) { //模拟计算 calculate2();//模拟数据计算 } else { //实际计算 //if (sPipeInfo.szVideoInfo[0].iObjCount != 0) //{ // Console.WriteLine(""); // caculateflag = pcalculate.calculate(sPipeInfo); //} //for (int i = 0; i < pcalculate.AllOutputData.Count; i++) //{ // resultParam.CamID = pcalculate.AllOutputData[i].CamID; // //if (pcalculate.AllOutputData[i].CamID==) // resultParam.CPos = pcalculate.AllOutputData[i].UpHumanVolume; // resultParam.CNeg = pcalculate.AllOutputData[i].DownHumanVolume; // resultParam.CPos_incr = pcalculate.AllOutputData[i].DeltUpHuman; // resultParam.CNeg_incr = pcalculate.AllOutputData[i].DeltDownHuman; // resultParam.DetectTime = DateTime.Now; // resultParam.Speed = pcalculate.AllOutputData[i].AverageSpeed; // resultParam.Density = pcalculate.AllOutputData[i].AverageDensity; //} } if (caculateflag) { if (simulation_flag) { //模拟参数插入数据库 resultParam.CamID = 123; resultParam.CPos += 1; resultParam.CNeg += 1; resultParam.CPos_incr = 1; resultParam.CNeg_incr = 1; Random rad = new Random(); double d = rad.NextDouble(); //double本来就是产生0-1之间小数的 resultParam.Density = Convert.ToDouble(d.ToString("#0.00")); //这里输出是控制输出几位数,0.00表示小数点后两位! resultParam.Speed = rad.Next(5, 10); resultParam.DetectTime = DateTime.Now; } mp.insertData(resultParam); } ///////////////////////////插入原始数据//////////////////////// for (int i = 0; i < sPipeInfo.szVideoInfo.Length; i++) //第i个摄像头 { for (int j = 0; j < sPipeInfo.szVideoInfo[i].iObjCount; j++) //第j个轨迹点 { if (lastCarId == sPipeInfo.szVideoInfo[i].szObjInfo[j].ID) { result.center_x = sPipeInfo.szVideoInfo[i].szObjInfo[j].center_x; result.center_y = sPipeInfo.szVideoInfo[i].szObjInfo[j].center_y; //listinfo.Add(result); str += result.center_x.ToString() + "," + result.center_y.ToString() + "|"; } if (lastCarId != 999 && lastCarId != sPipeInfo.szVideoInfo[i].szObjInfo[j].ID && sPipeInfo.szVideoInfo[i].szObjInfo[j].ID != 0)//不同ID表示轨迹信息为下一辆车的,则开始计算上一辆车的轨迹数据 { //if (listinfo.Count != 0) //{ //tracker.Add(listinfo); //listinfo.Clear(); //flag_2 = 1; Points point = new Points(); point.points = str; point.DetectTime = DateTime.Now; point.track_id = lastCarId; if (str != "") { //mp.insertPoint(point); } str = ""; tracker.Clear(); //} } if (sPipeInfo.szVideoInfo[i].szObjInfo[j].ID != 0) { lastCarId = sPipeInfo.szVideoInfo[i].szObjInfo[j].ID;//替换上一个carID } } } } else { Console.WriteLine("参数接收失败"); } } } } } catch (Exception ex) { //Log.WriteLog(ex, "");//往TXT写入异常信息 throw; } }
public void runing(object param) { //try { ///初始化 for (int n = 0; n < 20; n++) { CollectData colle = new CollectData(); collectData.Add(colle); last_onehr_index_CPos.Add(0); last_onehr_index_CNeg.Add(0); last_onehr_index_Speed.Add(0); last_onehr_index_Speed_up.Add(0); last_onehr_index_Speed_down.Add(0); last_onehr_index_Density.Add(0); last_i64time.Add(0); last_detetime.Add(DateTime.Now.Second * 1000 + DateTime.Now.Millisecond); last_detetime_min.Add(DateTime.Now.Minute); } int last_min = DateTime.Now.Minute; bool calculate_flag = true; byte[] writebuffer = new byte[20480]; string strPipeName = "\\\\.\\pipe\\HST_Output_Pip_Gpu_1"; Console.WriteLine(strPipeName); DataRec dr = new DataRec(Convert.ToInt32(param)); while (true) { Thread.Sleep(1000); if (dr.PipeFlag) { while (true)//连接管道 { //dr.hPipe = PipeNative.WaitNamedPipe dr.hPipe = PipeNative.CreateFile( strPipeName, //管道名称 FileDesiredAccess.GENERIC_READ | FileDesiredAccess.GENERIC_WRITE, //访问模式,读模式或写模式 FileShareMode.Zero, //0表示不共享,共享模式 IntPtr.Zero, //一个只读字段,代表已初始化为零的指针或句柄。指向安全属性的指针 FileCreationDisposition.OPEN_EXISTING, //如何创建。文件必须已经存在。由设备提出要求 0, //文件属性 0); //用于复制文件句柄,不使用模板 if (dr.hPipe.ToInt32() != PipeNative.INVALID_HANDLE_VALUE) { break; //PipeNative.INVALID_HANDLE_VALUE = -1.管道创建失败 } if (PipeNative.GetLastError() != PipeNative.ERROR_PIPE_BUSY || //PipeNative.ERROR_PIPE_BUSY = 231 PipeNative.WaitNamedPipe(strPipeName, 5 * 1000)) //在超时时间前管道的一个实例有效则返回非0,在超时时间内没有一个有效的实例,则返回0 { Console.WriteLine("无法连接管道:{0} ERROR:{1}", strPipeName, PipeNative.GetLastError()); continue; } else { Console.WriteLine("管道连接成功:{0}", strPipeName); } } //start read pipe thread ThreadStart childref = new ThreadStart(ReadPipeThread); Thread childThread = new Thread(childref); m_bExitReadPipe = false; m_hPipe = dr.hPipe; childThread.Start(); while (dr.PipeFlag) { #region [接收数据] //通过线程异步读取 SHstPipeInfo sPipeInfo = null; int iRes = 0; lock (m_oReadPipeLock) { if (m_pipeInfoQueue.Count > 0) { sPipeInfo = (SHstPipeInfo)m_pipeInfoQueue.Dequeue(); } } if (sPipeInfo == null) { Thread.Sleep(10); continue; } //////////////////////////// string mtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); Log log = new Log(); string msg = "ID:" + sPipeInfo.szVideoInfo[0].szObjInfo[0].ID + "读取时间:" + DateTime.Now + "毫秒:" + mtime; //log.WriteLog(msg); //////////////////////////// //continue; //测试用,需删除 吴超 if (iRes == 0) { //todo 参数处理 //Console.WriteLine("\r ReadPipeInfo videocount: {0} time: {1} \t v0:{2}:{3} \t v1:{4}:{5} \t v2:{6}:{7} \t v3:{8}:{9} \t" // , sPipeInfo.iVideoCount, sPipeInfo.szVideoInfo[0].i64Time // , sPipeInfo.szVideoInfo[0].iVideoID, sPipeInfo.szVideoInfo[0].iObjCount // , sPipeInfo.szVideoInfo[1].iVideoID, sPipeInfo.szVideoInfo[1].iObjCount // , sPipeInfo.szVideoInfo[2].iVideoID, sPipeInfo.szVideoInfo[2].iObjCount // , sPipeInfo.szVideoInfo[3].iVideoID, sPipeInfo.szVideoInfo[3].iObjCount // ); //管道收发同步机制 for (int l = 0; l < sPipeInfo.iVideoCount; l++) { int misec = DateTime.Now.Second * 1000 + DateTime.Now.Millisecond; int dif_time_stamp = Convert.ToInt32(sPipeInfo.szVideoInfo[l].i64Time - last_i64time[l]); int dif_time_detect = misec - last_detetime[l]; if (dif_time_detect - dif_time_stamp > 500) { i64time_flag = false; Console.WriteLine("计算时长超时,处理下一组数据"); Console.WriteLine("时间间隔为:{0}", dif_time_detect - dif_time_stamp); last_i64time[l] = sPipeInfo.szVideoInfo[l].i64Time; last_detetime[l] = misec; last_detetime_min[l] = DateTime.Now.Minute; break; } else { i64time_flag = true; } } if (i64time_flag) { bool caculateflag = true; if (simulation_flag) { //模拟计算 calculate2();//模拟数据计算 } else { //实际计算 caculateflag = pcalculate.calculate(sPipeInfo); } if (caculateflag) { bool statistical_flage = false; int now_min = DateTime.Now.Minute; int now_hour = DateTime.Now.Hour; if ((now_min == 0) && (now_min != last_min)) { statistical_flage = true; } else { statistical_flage = false; } for (int i = 0; i < pcalculate.AllOutputData.Count; i++) { resultParam.CamID = pcalculate.AllOutputData[i].CamID; resultParam.CPos = pcalculate.AllOutputData[i].UpHumanVolume; resultParam.CNeg = pcalculate.AllOutputData[i].DownHumanVolume; resultParam.CPos_incr = pcalculate.AllOutputData[i].DeltUpHuman; resultParam.CNeg_incr = pcalculate.AllOutputData[i].DeltDownHuman; resultParam.DetectTime = DateTime.Now; resultParam.Speed = pcalculate.AllOutputData[i].AverageSpeed; resultParam.AverageUpSpeed = pcalculate.AllOutputData[i].AverageUpSpeed; resultParam.AverageDownSfpeed = pcalculate.AllOutputData[i].AverageDownSfpeed; resultParam.Density = pcalculate.AllOutputData[i].AverageDensity; if (resultParam.CamID != 0) { mp.insertData(resultParam);//5s插入数据库 } //存储历史数据,第i路数据 collectData[i].list_sec_CPos.Add(resultParam.CPos); collectData[i].list_sec_CNeg.Add(resultParam.CNeg); collectData[i].list_sec_Speed.Add(resultParam.Speed); collectData[i].list_sec_Speed_up.Add(resultParam.AverageUpSpeed); collectData[i].list_sec_Speed_down.Add(resultParam.AverageDownSfpeed); collectData[i].list_sec_Density.Add(resultParam.Density); ////////统计一小时数据//////// if (statistical_flage) { if ((now_hour == 0) && (now_min == 0)) { statistical.oneHorSta(2, resultParam.CamID, collectData[i], last_onehr_index_CPos[i], last_onehr_index_CNeg[i], last_onehr_index_Speed[i], last_onehr_index_Speed_up[i], last_onehr_index_Speed_down[i], last_onehr_index_Density[i]); } else { statistical.oneHorSta(1, resultParam.CamID, collectData[i], last_onehr_index_CPos[i], last_onehr_index_CNeg[i], last_onehr_index_Speed[i], last_onehr_index_Speed_up[i], last_onehr_index_Speed_down[i], last_onehr_index_Density[i]); } last_onehr_index_CPos[i] = collectData[i].list_sec_CPos.Count; last_onehr_index_CNeg[i] = collectData[i].list_sec_CNeg.Count; last_onehr_index_Speed[i] = collectData[i].list_sec_Speed.Count; last_onehr_index_Speed_up[i] = collectData[i].list_sec_Speed_up.Count; last_onehr_index_Speed_down[i] = collectData[i].list_sec_Speed_down.Count; last_onehr_index_Density[i] = collectData[i].list_sec_Density.Count; collectData[i].list_sec_CPos.Clear(); collectData[i].list_sec_CNeg.Clear(); collectData[i].list_sec_Speed.Clear(); collectData[i].list_sec_Speed_up.Clear(); collectData[i].list_sec_Speed_down.Clear(); collectData[i].list_sec_Density.Clear(); last_onehr_index_CPos[i] = 0; last_onehr_index_CNeg[i] = 0; last_onehr_index_Speed[i] = 0; last_onehr_index_Speed_up[i] = 0; last_onehr_index_Speed_down[i] = 0; last_onehr_index_Density[i] = 0; } ////////统计一天数据//////// if ((now_hour == 23) && (now_min == 50) && (now_min != last_min)) { CollectData cData = new CollectData();//不存储23-00数据 mp.loadHorData(cData, resultParam.CamID); string table = "pflow_tb_data_day"; statistical.Sta(resultParam.CamID, cData, table); //数据库表的状态检测 CreatTable dt_man = new CreatTable(); dt_man.creat_table(); if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)//周日汇总本周的数据 { CollectData cseveData = new CollectData(); mp.load7DayData(cseveData, resultParam.CamID); table = "pflow_tb_data_week"; statistical.Sta(resultParam.CamID, cseveData, table); } if (DateTime.Now.AddDays(1).Day == 1)//每月一号汇总前一个月的数据 { CollectData cseveData = new CollectData(); mp.load1MonthData(cseveData, resultParam.CamID);//会查询到后于当前时间的数据 table = "pflow_tb_data_month"; statistical.Sta(resultParam.CamID, cseveData, table); } if ((DateTime.Now.Month == 12) && (DateTime.Now.AddDays(1).Day == 1))//每年12月最后一天汇总当年的数据 { CollectData cseveData = new CollectData(); mp.load1YearData(cseveData, resultParam.CamID); table = "pflow_tb_data_year"; statistical.Sta(resultParam.CamID, cseveData, table); } } last_min = DateTime.Now.Minute;//reset last time } if (simulation_flag) { //模拟参数插入数据库 //resultParam.CamID = 123; //resultParam.CPos += 1; //resultParam.CNeg += 1; //resultParam.CPos_incr = 1; //resultParam.CNeg_incr = 1; //Random rad = new Random(); //double d = rad.NextDouble();//double本来就是产生0-1之间小数的 //resultParam.Density = Convert.ToDouble(d.ToString("#0.00"));//这里输出是控制输出几位数,0.00表示小数点后两位! //resultParam.Speed = rad.Next(5, 10); //resultParam.DetectTime = DateTime.Now; //mp.insertData(resultParam);//5s插入数据库 } } /////////////////////////////插入原始数据//////////////////////// for (int i = 0; i < sPipeInfo.szVideoInfo.Length; i++) //第i个摄像头 { for (int j = 0; j < sPipeInfo.szVideoInfo[i].iObjCount; j++) //第j个轨迹点 { if (lastCarId == sPipeInfo.szVideoInfo[i].szObjInfo[j].ID) { result.center_x = sPipeInfo.szVideoInfo[i].szObjInfo[j].center_x; result.center_y = sPipeInfo.szVideoInfo[i].szObjInfo[j].center_y; //listinfo.Add(result); str += result.center_x.ToString() + "," + result.center_y.ToString() + "|"; } if (lastCarId != 999 && lastCarId != sPipeInfo.szVideoInfo[i].szObjInfo[j].ID && sPipeInfo.szVideoInfo[i].szObjInfo[j].ID != 0)//不同ID表示轨迹信息为下一辆车的,则开始计算上一辆车的轨迹数据 { //if (listinfo.Count != 0) //{ //tracker.Add(listinfo); //listinfo.Clear(); //flag_2 = 1; Points point = new Points(); point.CamID = sPipeInfo.szVideoInfo[i].iVideoID; point.points = str; point.DetectTime = DateTime.Now; point.track_id = lastCarId; if (str != "") // { //mp.insertPoint(point); } str = ""; tracker.Clear(); //} } if (sPipeInfo.szVideoInfo[i].szObjInfo[j].ID != 0) { lastCarId = sPipeInfo.szVideoInfo[i].szObjInfo[j].ID;//替换上一个carID } } } } } else { Console.WriteLine("参数接收失败"); } sPipeInfo = null; } //stop read pipe thread m_bExitReadPipe = true; } } } //catch (Exception ex) //{ // //Log.WriteLog(ex, "");//往TXT写入异常信息 // throw; //} }
static void PInvokeNativePipeClient() { ///////////////////////////////////////////////////////////////////// // Try to open a named pipe. // // Prepare the pipe name String strPipeName = String.Format(@"\\{0}\pipe\{1}", ".", // Server name "HelloWorld" // Pipe name ); IntPtr hPipe; while (true) { hPipe = PipeNative.CreateFile( strPipeName, // Pipe name FileDesiredAccess.GENERIC_READ | // Read and write access FileDesiredAccess.GENERIC_WRITE, FileShareMode.Zero, // No sharing IntPtr.Zero, // Default security attributes FileCreationDisposition.OPEN_EXISTING, // Opens existing pipe 0, // Default attributes 0); // No template file // Break if the pipe handle is valid. if (hPipe.ToInt32() != PipeNative.INVALID_HANDLE_VALUE) { break; } if (// Exit if an error other than ERROR_PIPE_BUSY occurs PipeNative.GetLastError() != PipeNative.ERROR_PIPE_BUSY || // All pipe instances are busy, so wait for five seconds !PipeNative.WaitNamedPipe(strPipeName, 5000)) { Console.WriteLine("Unable to open named pipe {0} w/err 0x{1:X}", strPipeName, PipeNative.GetLastError()); return; } } Console.WriteLine("The named pipe, {0}, is connected.", strPipeName); ///////////////////////////////////////////////////////////////////// // The pipe connected; change to message-read mode. // PipeMode mode = PipeMode.PIPE_READMODE_MESSAGE; bool bResult = PipeNative.SetNamedPipeHandleState( hPipe, ref mode, IntPtr.Zero, IntPtr.Zero); if (!bResult) { Console.WriteLine("SetNamedPipeHandleState failed w/err 0x{0:X}", PipeNative.GetLastError()); return; } ///////////////////////////////////////////////////////////////////// // Send a message to the pipe server and receive its response. // // A byte buffer of BUFFER_SIZE bytes. The buffer should be big // enough for ONE request to the server. string strMessage; byte[] bRequest; // Client -> Server uint cbBytesWritten, cbRequestBytes; byte[] bReply = new byte[BUFFER_SIZE]; // Server -> Client uint cbBytesRead, cbReplyBytes; // Send one message to the pipe. // '\0' is appended in the end because the client may be a native // C++ program. strMessage = "Default request from client\0"; bRequest = Encoding.Unicode.GetBytes(strMessage); cbRequestBytes = (uint)bRequest.Length; bResult = PipeNative.WriteFile( // Write to the pipe. hPipe, // Handle of the pipe bRequest, // Message to be written cbRequestBytes, // Number of bytes to write out cbBytesWritten, // Number of bytes written IntPtr.Zero); // Not overlapped if (!bResult /*Failed*/ || cbRequestBytes != cbBytesWritten /*Failed*/) { Console.WriteLine("WriteFile failed w/err 0x{0:X}", PipeNative.GetLastError()); return; } Console.WriteLine("Sends {0} bytes; Message: \"{1}\"", cbBytesWritten, strMessage.TrimEnd('\0')); // Receive the response from the server. cbReplyBytes = BUFFER_SIZE; do { bResult = PipeNative.ReadFile( // Read from the pipe. hPipe, // Handle of the pipe bReply, // Buffer to receive the reply cbReplyBytes, // Size of buffer out cbBytesRead, // Number of bytes read IntPtr.Zero); // Not overlapped if (!bResult && PipeNative.GetLastError() != PipeNative.ERROR_MORE_DATA) { Console.WriteLine("ReadFile failed w/err 0x{0:X}", PipeNative.GetLastError()); break; } strMessage = Encoding.Unicode.GetString(bReply).TrimEnd('\0'); Console.WriteLine("Receives {0} bytes; Message: \"{1}\"", cbBytesRead, strMessage); } while (!bResult); // Repeat loop if ERROR_MORE_DATA ///////////////////////////////////////////////////////////////////// // Close the pipe. // PipeNative.CloseHandle(hPipe); }