void ConnectionModule::PerformProjectSupplyQuery(ProjectSupplyQuery &psq)
{
	if(p_critical_section==NULL)
	{
		return;
	}

	// Tell the thread to connect to these hosts
	CSingleLock singleLock(p_critical_section);
	singleLock.Lock();
	if(singleLock.IsLocked())
	{
		p_thread_data->p_project_supply_queries->push_back(psq);
		WSASetEvent(p_thread_data->m_reserved_events[1]);	// vector data
		singleLock.Unlock();
	}
}
void ProcessManager::InitThreadData(WPARAM wparam,LPARAM lparam)
{
	p_critical_section=(CCriticalSection *)wparam;
	p_thread_data=(ProcessManagerThreadData *)lparam;

	if(p_critical_section!=NULL)
	{
		CSingleLock singleLock(p_critical_section);
		singleLock.Lock();
		if(singleLock.IsLocked())
		{
			p_thread_data->Clear();
			p_thread_data->p_projects = &v_projects;
			singleLock.Unlock();
		}
		SetEvent(p_thread_data->m_events[1]);	// start the process
	}
}
Beispiel #3
0
CClientContext::~CClientContext()
{
	////发送数据锁,如果在准备析构时还有发送数据操作,等待
	CSingleLock singleLock(&m_SendLock, TRUE);
	
	closesocket(m_s);
	m_pGTMIOCP = NULL;

	//if(m_pRecvBufferCell != NULL)
	//{
	//	m_pMemPool->ReleaseBuffer(m_pRecvBufferCell,1);
	//	m_pRecvBufferCell = NULL;
	//}	

	UnlockClient();



}
void ConnectionModule::ReConnectAll()
{
	if(p_critical_section==NULL)
	{
		return;
	}

    v_connected_host_ips.clear();
	v_connect_to_ips.clear();
	// Tell the thread to reconnect to supernodes
	CSingleLock singleLock(p_critical_section);
	singleLock.Lock();
	if(singleLock.IsLocked())
	{
		p_thread_data->m_reconnect_to_hosts = true;
		WSASetEvent(p_thread_data->m_reserved_events[1]);	// vector data
		singleLock.Unlock();
	}
}
Beispiel #5
0
void CManageRecord::StopRecordThread()
{
	m_brun = false;
	for ( std::vector<CameraRecordPtr>::size_type i = 0; i < m_threadptr_array.size(); i++ )
	{
		m_threadptr_array[i]->join();
	}
	for ( std::vector<CameraRecordPtr>::size_type i = 0; i < m_camera_recode_array.size(); i++)
	{
		m_camera_recode_array[i]->StopRecord();
	}
	if( m_httpServerPtr != NULL )
	{
		m_httpServerPtr->Stop();
		m_ManualThreadPtr->join();
		boost::unique_lock<boost::mutex> singleLock(m_ManualCamArrayMutex);
		std::list<CameraRecordPtr>::iterator it = m_ManualCamReclist.begin();
		for ( ; it != m_ManualCamReclist.end(); it++ ) {
			(*it)->StopRecord();
		}
	}
}
Beispiel #6
0
int CManageRecord::AddManualCameraRecord( char* url, int recordType )
{
	CameraRecordPtr camera_record_ptr(new CCameraRecord(this, recordType));
	int iRet = camera_record_ptr->InitCameraRecordByURL( url );
	if( iRet < 0 ) return iRet;

	CameraRecordPtr have_Camera_ptr = GetCameraRecordPtr( camera_record_ptr->GetCameraID() );
	if( have_Camera_ptr != NULL ){
		have_Camera_ptr->ResetStartRecordTime();
		if( !have_Camera_ptr->GetCameraRecordIsOpen() )
			return -1;
		return 1;
	} else {
		int iret = camera_record_ptr->StartRecord();
		//if( iret < 0 ) return -1;
		boost::unique_lock<boost::mutex> singleLock(m_ManualCamArrayMutex);
		m_ManualCamReclist.push_back( camera_record_ptr );
		if( iret >= 0 ) return 2;
		return iret;
	}
	return -1;
}
Beispiel #7
0
CManageRecord::CameraRecordPtr CManageRecord::GetCameraRecordPtr(int CameraID)
{
	CameraRecordPtr camera_record_ptr;
	for ( std::vector<CameraRecordPtr>::size_type i = 0; i < m_camera_recode_array.size(); i++ )
	{
		if( m_camera_recode_array[i]->GetCameraID() == CameraID )
		{
			camera_record_ptr = m_camera_recode_array[i];
			return camera_record_ptr;
		}
	}

	boost::unique_lock<boost::mutex> singleLock( m_ManualCamArrayMutex );
	std::list<CameraRecordPtr>::iterator it = m_ManualCamReclist.begin();
	for ( ; it != m_ManualCamReclist.end(); it++ ) {
		if( (*it)->GetCameraID() == CameraID ) {
			camera_record_ptr = *it;
			return camera_record_ptr;
		}
	}
	return camera_record_ptr;
}
UINT SynchroFunction2(LPVOID param)
{
	int Data[5],i;
	CSingleLock singleLock(sema);
	singleLock.Lock();
	for(i=0;i<3;i++)
	{
		count++;
		::Sleep(50);
		Data[i]=count;
	}
	TCHAR str[50];
	str[0]=0;
	for(i=0;i<3;i++)
	{
		int len=lstrlen((LPTSTR)str);
		wsprintf((LPTSTR)&str[len],_T("%d"),Data[i]);
	}
	::Sleep(5000);
	singleLock.Unlock();
	::MessageBox((HWND)param,str,_T("synchro Thread"),MB_OK);
	return 0;
}
UINT SynchroFunction1(LPVOID param)	//同步线程控制函数
{
	CSingleLock singleLock(&mutex);	//用互斥对象保护数据
	singleLock.Lock();
	int Data[5],i;
	//critical.Lock();
	for(i=0;i<3;i++)
	{
		count++;
		::Sleep(50);
		Data[i]=count;
	}
	TCHAR str[50];
	str[0]=0;
	for(i=0;i<3;i++)
	{
		int len=lstrlen((LPTSTR)str);
		wsprintf((LPTSTR)&str[len],_T("%d"),Data[i]);
	}
	singleLock.Unlock();
	//critical.Unlock();		//释放该线程对临界区的控制权
	::MessageBox((HWND)param,str,_T("synchro Thread"),MB_OK);
	return 0;
}
void ConnectionModule::ConnectToHosts(vector<SupernodeHost> &hosts)
{
	
	if(p_critical_section==NULL)
	{
		return;
	}

	int i;

	// Tell the thread to connect to these hosts
	CSingleLock singleLock(p_critical_section);
	singleLock.Lock();
	if(singleLock.IsLocked())
	{
		*p_thread_data->p_connect_hosts=hosts;
		WSASetEvent(p_thread_data->m_reserved_events[1]);	// vector data
		singleLock.Unlock();
	}

	// Keep track of the connect to hosts for when we are checking to see if we can add an ip to the cache
	v_connect_to_ips.clear();
	for(i=0;i<(int)hosts.size();i++)
	{
		v_connect_to_ips.push_back(hosts[i].m_ip);
	}
	
	sort(v_connect_to_ips.begin(),v_connect_to_ips.end());

	// Add these hosts to the connected hosts vector, just so that another mod won't connect to them since i am connecting to them
//	for(i=0;i<hosts.size();i++)
//	{
//		v_connected_host_ips.push_back(hosts[i].IP());
//	}

}
Beispiel #11
0
void DBManager::WriteDataToDemandDatabase()
{
	UINT i;

	if(p_demand_critical_section==NULL)
	{
		return;
	}

	// If there are no project query hits to send to the thread to be written to database, then return
	if(v_project_queries.size()==0)
//	if((v_project_query_hits.size()==0) && (v_project_queries.size()==0))
	{
		return;
	}

	if(m_ready_to_write_to_demand_db==false)
	{
		return;
	}

	m_ready_to_write_to_demand_db=false;

	// Tell the thread to connect to these hosts
//	p_parent->m_log_window_manager.Log("LogfileManager::TimerHasFired() - Before LOCK\n",0,false,true);	// black italic
	CSingleLock singleLock(p_demand_critical_section);
	singleLock.Lock();
	if(singleLock.IsLocked())
	{
/*
		// Supply
		if(v_project_query_hits.size()>0)
		{
			// If the vector is empty, then just copy. Else, add the correct items to the appropriate project
			if(m_thread_data.p_project_query_hits->size()==0)
			{
				*m_thread_data.p_project_query_hits=v_project_query_hits;
			}
			else
			{
				// For each of the project query hits, find the project in the thread, and if it can't be found, then create it
				for(i=0;i<v_project_query_hits.size();i++)
				{
					m_thread_data.p_project_query_hits->push_back(v_project_query_hits[i]);
				}
			}

			v_project_query_hits.clear();	// clear the vector
		}
*/
		// Demand
		if(v_project_queries.size()>0)
		{
			// If the vector is empty, then just copy. Else, add the correct items to the appropriate project
			if(m_demand_thread_data.p_project_queries->size()==0)
			{
				*m_demand_thread_data.p_project_queries=v_project_queries;
			}
			else
			{
				// For each of the project queries, find the project in the thread, and if it can't be found, then create it
				for(i=0;i<v_project_queries.size();i++)
				{
					m_demand_thread_data.p_project_queries->push_back(v_project_queries[i]);
				}
			}

			v_project_queries.clear();	// clear the vector
		}

		SetEvent(m_demand_thread_data.m_events[1]);	// vector data

		singleLock.Unlock();
	}
//	p_parent->m_log_window_manager.Log("LogfileManager::TimerHasFired() - After LOCK\n",0,false,true);	// black italic
}
Beispiel #12
0
QUERYRESPONSE ProRbtDb::HandleCounterIdEntry(PRORBTCOUNTERSESSION * pCounterSession, CPharmaRobot10Dlg* pdialog)
{
	QUERYRESPONSE returnvalue = Q_NOACK;
	size_t retsize, len, convertedChars;
	int MessageLength, NumTenBatches;
	char numart[3];
	aConsisReplyHeader *paMesHeader;
	aConsisReplyDispensedOcc* aocc;
	REQUESTINTERMEIDATEDB InterMDb;
	CString StringFromProRbt, st;

	if (pCounterSession->ExpectedNumLines == pCounterSession->ReceivedNumLines)
	{

		if (pdialog->Consis.ConnectionStarted == FALSE)
		{
			if (pdialog->Consis.ConnectToConsis("ShorT", &(pdialog->m_listBoxMain), &(pdialog->m_CheckBoxRemoteSvr)))
				pdialog->EnableCondsisTab();
		}

		if (pdialog->Consis.ConnectionStarted == TRUE)
		{ 
			//Clean intermideate database
			memset (&InterMDb, 0, sizeof(InterMDb));
			InterMDb.firstIndexToStartfrom = INITIAL;

			int l = 0;
			//build intermediate database that agregates identical article IDs (barcodes)
			for (int j = 0 ; j < pCounterSession->ExpectedNumLines ; j++)
			{
				bool entryfound = false;
				while (InterMDb.Entry[l].NumReq != 0) //search for an empty entry indicating the last entry in database
				{
					if (wcscmp(InterMDb.Entry[l].ArctileIdRequested, pCounterSession->RbtParamLinesArr[j + 1].Barcode) == 0)
					{
						InterMDb.Entry[l].NumReq += _wtoi(pCounterSession->RbtParamLinesArr[j+1].Qty); //aggregate number of requested articles
						entryfound = true;
					}
					l++;//Check next entry in intermediate database
				}
				if(entryfound == false)
				{//barcode not found in any of the entries in the database. 
					//Create new entry - copy Barcode number and requested quantity to inetrmediate database.
					StringFromProRbt = pCounterSession->RbtParamLinesArr[j + 1].Barcode;
					len = StringFromProRbt.GetLength();
					memcpy(&(InterMDb.Entry[l].ArctileIdRequested),pCounterSession->RbtParamLinesArr[j+1].Barcode,len*sizeof(wchar_t));
					InterMDb.Entry[l].ArctileIdRequested[len] = L'\0';//insure string ends with a null
					InterMDb.Entry[l].NumReq = _wtoi(&(pCounterSession->RbtParamLinesArr[j+1].Qty[0])); //insert numer of requested articles
					//Check if Item is in Stock
					char BarcodeString[31];	memset(BarcodeString, 0, 30);
					wcstombs(BarcodeString, InterMDb.Entry[l].ArctileIdRequested, len);
					int TotalStock;
					if (CheckAmountInStock(&TotalStock, BarcodeString, pdialog) == FALSE)
					{
						//Error with Consis, Init entire Database
						InitProRbtDb();
						memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
						wsprintf(ackemessage.Message,L"תקלה בשליחת שאילתת כמות במלאי לשרת קונסיס");
						return Q_ERROR;
					}
					if (TotalStock >= InterMDb.Entry[l].NumReq) 
					{
						InterMDb.Entry[l].NumInStock = InterMDb.Entry[l].NumReq;
					}
					else
					{
						InterMDb.Entry[l].NumInStock = TotalStock;
					}
					//the Item is in stock and may be dispensed
					if (InterMDb.Entry[l].NumInStock > 0) 
					{
						InterMDb.sizeInStock += 1;
						if (InterMDb.firstIndexToStartfrom == INITIAL)
						{
							InterMDb.firstIndexToStartfrom = l;
						}
					}
				}
				//record intermediate database size for all items inserted to it
				InterMDb.sizeRequested = l + 1;
				l = 0;
			}

			//Handling 'A' dialogue is done in a batches of 10
			NumTenBatches = 1 + (InterMDb.sizeInStock / 10);

			//Try to catch the Mutex for CONSIS Access
			//Protect with Mutex the CONSIS resource
			CSingleLock singleLock(&(pdialog->m_MutexAMessage));

			// Attempt to lock the shared resource
			if (singleLock.Lock(INFINITE))
			{
				//log locking success
			}

			while (NumTenBatches !=0)
			{
				//Build 'A' Message with Barcode from RBT parameters only if there are items left to send
				if (InterMDb.sizeInStock > 0)
				{
					//This function will send the following 10 items in the database that are in stock
					if (BuildAndSendACommand(&InterMDb, pdialog, &(pCounterSession->RbtParamLinesArr[1])) == FALSE)
					{
						//Error with Consis, Init entire Database
						InitProRbtDb();
						singleLock.Unlock();
						memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
						wsprintf(ackemessage.Message,L"תקלה בשליחת בקשת ניפוק לשרת קונסיס");
						return Q_ERROR;
					}		

					if (InterMDb.sizeInStock >= 10) InterMDb.sizeInStock -= 10; //10 less in stock

					//Session state depends on the order state
					//Last message Should be '4' - Ready, but Server returns '5', so that's what we'll wait for
					char orderState[3];
					memset(&(orderState[2]),'\0',1);
					memset(orderState,'0',2);

					//clear message buffer to be received from consis
					memset(pdialog->Consis.amessageBuffer, 0 ,sizeof(pdialog->Consis.amessageBuffer));
					MessageLength = sizeof(pdialog->Consis.amessageBuffer);
					paMesHeader = (aConsisReplyHeader *)pdialog->Consis.amessageBuffer;
					do
					{
						/* Infinitly wait for the reply to arrive from CONSIS by means of AsynchDialogue listener*/
						::WaitForSingleObject(pdialog->Consis.aMessageEvent.m_hObject, INFINITE);

						pdialog->Consis.amessageBuffer[pdialog->Consis.aMessageLength] = '\0';

						memcpy(orderState, paMesHeader->OrderState, sizeof(paMesHeader->OrderState));
						orderState[2] = '\0';

						//Print the reply of CONSIS 'a' to the dialog box
						size_t origsize = strlen(pdialog->Consis.amessageBuffer) + 1;
						wchar_t wcstring[1000];
						mbstowcs_s(&convertedChars, wcstring, origsize, pdialog->Consis.amessageBuffer, _TRUNCATE);
						st = wcstring; pdialog->m_listBoxMain.AddString(st);

					}while ((paMesHeader->OrderState[1] != '4') && (paMesHeader->OrderState[1] != '3'));
					//If Cancelled stop all.
					if (paMesHeader->OrderState[1] == '3')
					{//We checked that all the items are in stock. If Cancelled somthing is wrong in CONSIS
						//Error with Consis, Init entire Database
						InitProRbtDb();
						singleLock.Unlock();
						memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
						wsprintf(ackemessage.Message,L"תקלה בקבלת תשובה לבקשת ניפוק לשרת קונסיס");
						return Q_ERROR;
					}
					else//The 'A' request was not cancelled but finished, go through the reply
					{
						//Extract number of locations
						memcpy(numart, paMesHeader->NumberOfArticles, sizeof(paMesHeader->NumberOfArticles));
						numart[2] = '\0';
						int numArticles =  atoi(numart);

						//TEMP RANM DEBUG
						wchar_t Stringnumdif1f[3]; _itow_s(numArticles,Stringnumdif1f,10);
						Stringnumdif1f[2] = '\0';
						st = L"numArticles = "; st += Stringnumdif1f; pdialog->m_listBoxMain.AddString(st);
						//TEMP RANM DEBUG

						for (int i = 0 ; i < numArticles ; i++ )
						{
							//Extract Article ID and Dispensed quantity from Occupancy entry in 'a' message occupany entry
							char* address = (char*)paMesHeader + sizeof(aConsisReplyHeader) + (i * 42);
							aocc = (aConsisReplyDispensedOcc*)address;

							//Get article ID from 'a' response
							wchar_t articleID[31];
							articleID[30] = '\0';
							mbstowcs_s(&retsize, articleID, sizeof(aocc->ArticleId) + 1, aocc->ArticleId, _TRUNCATE);

							//Clean leading zeroes
							CString cleanArticleID;
							cleanArticleID.SetString(articleID);
							cleanArticleID.TrimLeft(L'0');
							cleanArticleID.TrimLeft(L' ');
							wsprintf(articleID,cleanArticleID.GetString());
							articleID[cleanArticleID.GetLength()] = L'\0';

							//find article ID in intermediate database
							int k = 0;
							while (InterMDb.Entry[k].NumReq != 0)
							{
								if (wcscmp(articleID, InterMDb.Entry[k].ArctileIdRequested) == 0)
								{//found the entry accoridng to barcode in intermedeate database
									//Dispensed quantity handling. Fill intermediate database for handling at the end.
									char dispenssedQuantity[6];
									memcpy(dispenssedQuantity, aocc->DispensedQuantity, sizeof(aocc->DispensedQuantity));
									dispenssedQuantity[5] = '\0';
									InterMDb.Entry[k].NumDis += atoi(dispenssedQuantity);
									//IF NO CANCELLED STATE RECEIVED, THEN ALL ITEMS WERE DISPENSSED
									//	InterMDb.Entry[k].NumDis = InterMDb.Entry[k].NumInStock;
								}
								k++;//serach for article ID in the intermediate database further
							}
						}

					}

				}
				NumTenBatches--;
			}

			singleLock.Unlock();
		}
		else
		{
			//Error with Consis, Init entire Database
			InitProRbtDb();
			memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
			wsprintf(ackemessage.Message,L"תקלה בתקשורת לשרת קונסיס");
			return Q_ERROR;
		}


		//CONSIS Completed, Build Ack from intermediate database. Check if all entries in the aggregated database were dispensed.
		int m = 0;
		bool missingitems = false;
		CString AckedString = L"מבקשת הניפוק חסרים הפריטים הבאים"; AckedString += L":";AckedString += L"\n";
		while (InterMDb.Entry[m].NumReq != 0)
		{
			if (InterMDb.Entry[m].NumReq != InterMDb.Entry[m].NumDis)
			{
				missingitems = true;
				wchar_t description[256];
				//Get Description from Yarpa SQL. If failed publish back to Client the Barcode
				if (!pdialog->GetItemDescFromBarcode(InterMDb.Entry[m].ArctileIdRequested, description))
					wsprintf(description,  InterMDb.Entry[m].ArctileIdRequested);
				AckedString += L"סוג פריט"; AckedString += L":"; AckedString += L" ";
				AckedString += description; AckedString += L"\n";
				AckedString += L"חסרים"; AckedString += L":"; AckedString += L" ";
				wchar_t Stringnumdiff[3]; _itow_s(InterMDb.Entry[m].NumReq - InterMDb.Entry[m].NumDis,Stringnumdiff,10);
				AckedString += Stringnumdiff;
				AckedString += L"\n\n";
			}
			m++;//Go on to next item in intermediate databse.
		}

		if (missingitems)
		{
			memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
			memcpy(ackemessage.Message, AckedString.GetString(), AckedString.GetLength() * sizeof(wchar_t));
			returnvalue = Q_SENDACK;
		}
		else
		{
			returnvalue = Q_NOACK;
		}

		//Prepare Database Line Entry for next Session
		pCounterSession->PreviousSessionId = pCounterSession->CurrentSessionId;
		pCounterSession->ExpectedNumLines = -1;
		pCounterSession->ReceivedNumLines = -1;
		pCounterSession->CurrentSessionId = -1;

	}
	return returnvalue;
}
Beispiel #13
0
UINT DBManagerSupplyThreadProc(LPVOID pParam)
{
	UINT i;

	// Init message window handle
	HWND hwnd=(HWND)pParam;

	// Init the message data structure and send it
	CCriticalSection critical_section;
	DBManagerThreadData thread_data;
	vector<QueryHit *> project_query_hits;
//	vector<Query *> project_queries;

	// Create the events
	HANDLE events[DBManagerThreadData::NumberOfEvents];
	for(i=0;i<sizeof(events)/sizeof(HANDLE);i++)
	{
		events[i]=CreateEvent(NULL,TRUE,FALSE,NULL);
		thread_data.m_events[i]=events[i];
	}

	thread_data.p_project_query_hits=&project_query_hits;
//	thread_data.p_project_queries=&project_queries;
	
	PostMessage(hwnd,WM_INIT_DB_MANAGER_SUPPLY_THREAD_DATA,(WPARAM)&critical_section,(LPARAM)&thread_data);	// the thread data is ready
	PostMessage(hwnd,WM_READY_TO_WRITE_DATA_TO_SUPPLY_DB,1,1);	// the thread is now ready to write into the database

	vector<QueryHit *> project_query_hits_cache;
//	vector<Query *> project_queries_cache;

	// Start the thread
	DWORD num_events=2;
	BOOL wait_all=FALSE;
	DWORD timeout=INFINITE;
	DWORD event;	// which event fired

	while(1)
	{
		event=WaitForMultipleObjects(num_events,events,wait_all,timeout);

		// Check to see if this is the kill thread events (event 0)
		if(event==0)
		{
			ResetEvent(events[event]);
			break;
		}

		// There is new data to be written to database
		if(event==1)
		{
			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				ResetEvent(events[event]);	// reset event

				// Cache the hits
				for(i=0;i<project_query_hits.size();i++)
				{
					project_query_hits_cache.push_back(project_query_hits[i]);
				}

				project_query_hits.clear();	// don't free the memory yet
/*			
				// Cache the queries
				for(i=0;i<project_queries.size();i++)
				{
					project_queries_cache.push_back(project_queries[i]);
				}

				project_queries.clear();	// don't free the memory yet
*/

				singleLock.Unlock();
			}
		}

		// If there are cached hits to process, then process them
		while(project_query_hits_cache.size() > 0)
		{
			//in each loop, it goes throught the vector and finds all entries belongs to the same project
			//and put them into query_hits vector and passes them the DB insert function

			vector<QueryHit> query_hits;
			vector<QueryHit*>::iterator iter = project_query_hits_cache.begin();
			//CString project = (*iter)->m_project;
			UINT project_id = (*iter)->m_project_id;
			query_hits.push_back(*(project_query_hits_cache[0]));
			delete *iter;
			project_query_hits_cache.erase(iter);
			iter = project_query_hits_cache.begin();
			while(iter != project_query_hits_cache.end())
			{
				//if(strcmp(project, (*iter)->m_project)==0)
				if(project_id == (*iter)->m_project_id)
				{
					query_hits.push_back(*(*iter));
					delete *iter;
					project_query_hits_cache.erase(iter);
				}
				else
					iter++;
			}
			WriteProjectSupplyToDatabase(query_hits);
		}
/*
		// If there are cached queries to process, then process them
		if(project_queries_cache.size()>0)
		{
			// Write out to database for each quries
			for(i=0;i<project_queries_cache.size();i++)
			{
				WriteProjectDemandToDatabase(project_queries_cache[i]);
				delete project_queries_cache[i];	// now free the memory
			}
			
			project_queries_cache.clear();
		}
*/

		// We've written all of the cached data to file...tell the logfile manager that we are ready to write more logfile data to file
		PostMessage(hwnd,WM_READY_TO_WRITE_DATA_TO_SUPPLY_DB,0,0);
	}

	// Close the events
	for(i=0;i<sizeof(events)/sizeof(HANDLE);i++)
	{
		CloseHandle(events[i]);
	}
	TRACE("Terminating DBManagerSupplyThreadProc\n");

	return 0;	// exit the thread
}
Beispiel #14
0
UINT ProcessManagerThreadProc(LPVOID pParam)
{
	CTime current_time = CTime::GetCurrentTime();
	UINT i;
	// Init message window handle
	HWND hwnd=(HWND)pParam;

	// Init the message data structure and send it
	
	CCriticalSection critical_section;
	ProcessManagerThreadData thread_data;
	

	// Create the events
	
	HANDLE events[ProcessManagerThreadData::NumberOfEvents];
	for(i=0;i<sizeof(events)/sizeof(HANDLE);i++)
	{
		events[i]=CreateEvent(NULL,TRUE,FALSE,NULL);
		thread_data.m_events[i]=events[i];
	}
	
	PostMessage(hwnd,WM_INIT_PROCESS_MANAGER_THREAD_DATA,(WPARAM)&critical_section,(LPARAM)&thread_data);	// the thread data is ready
	

	// Start the thread
	
	DWORD num_events=2;
	BOOL wait_all=FALSE;
	DWORD timeout=INFINITE;
	DWORD event;	// which event fired

	while(1)
	{
		event=WaitForMultipleObjects(num_events,events,wait_all,timeout);

		// Check to see if this is the kill thread events (event 0)
		if(event==0)
		{
			ResetEvent(events[event]);
			break;
		}

		// start the raw data processing
		if(event==1)
		{
			DWORD new_event = -1;

			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				thread_data.m_demand_progress=0;
				//thread_data.m_supply_progress=0;

				//process raw spoof data
				for(i=0; i<(UINT)thread_data.p_projects->size(); i++)
				{
					::PostMessage(hwnd, WM_DEMAND_PROCESS_PROJECT, (WPARAM)(*thread_data.p_projects)[i].m_project_name.c_str(),0);
					char date[32];
					char start_timestamp[32];
					char end_timestamp[32];
					int year,month,day;
					bool more_demand = true;
					bool first_round = true;

                    //while(more_demand)
					//{
					memset(&date, 0, sizeof(date));
					memset(&start_timestamp, 0, sizeof(start_timestamp));
					memset(&end_timestamp, 0, sizeof(end_timestamp));
					year=month=day=0;
					ProcessManager::g_db_interface.GetLastProcessedDateForSpoof((*thread_data.p_projects)[i].m_project_name.c_str(),date);
					if(strlen(date) == 0) //no previous results in processed database
					{
						ProcessManager::g_db_interface.GetFirstSpoofDataInsertionTimestamp(
							(*thread_data.p_projects)[i].m_project_name.c_str(),date);
						if(strlen(date) == 0) //no results in raw database
							continue;
						else
						{
							char tmp[32];
							strncpy(tmp, date, 4);
							year = atoi(tmp);
							char* ptr = date;
							ptr+=4;
							strncpy(tmp, ptr, 2);
							tmp[2]='\0';
							month = atoi(tmp);
							ptr+=2;
							strncpy(tmp, ptr, 2);
							tmp[2]='\0';
							day = atoi(tmp);							
							strcpy(start_timestamp, date);
						}
					}
					else
					{
						sscanf(date, "%d-%d-%d", &year, &month, &day);
						CTime time(year, month, day, 0,0,0);
						time += CTimeSpan(1,0,0,0);
						if(time.GetHour() == 23)
							time += CTimeSpan(0,1,0,0); //winter time
						else if(time.GetHour() == 1)
							time -= CTimeSpan(0,1,0,0); // summer time
						strcpy(start_timestamp, time.Format("%Y%m%d%H%M%S"));
						year = time.GetYear();
						month = time.GetMonth();
						day = time.GetDay();
					}
					while(more_demand)
					{
						if(!first_round)
						{
							CTime time(year, month, day, 0,0,0);
							time += CTimeSpan(1,0,0,0);
							if(time.GetHour() == 23)
								time += CTimeSpan(0,1,0,0); //winter time
							else if(time.GetHour() == 1)
								time -= CTimeSpan(0,1,0,0); // summer time
							strcpy(start_timestamp, time.Format("%Y%m%d%H%M%S"));
							year = time.GetYear();
							month = time.GetMonth();
							day = time.GetDay();
						}
						//check to see if we have reached today, then stop demand process for this project
						if(year == current_time.GetYear() && month == current_time.GetMonth() && day == current_time.GetDay())
							break;

						//get the end timestamp
						sprintf(end_timestamp, "%d%.2d%.2d%.2d%.2d%.2d", year,month,day,23,59,59);
						
						//get demand query and insert to processed database
						char on_date[32];
						sprintf(on_date, "%d-%.2d-%.2d", year, month, day);
						ProcessManager::g_db_interface.ProcessSpoof((*thread_data.p_projects)[i].m_project_name.c_str(),
											start_timestamp, end_timestamp, on_date);
						first_round = false;
					}

					thread_data.m_demand_progress = (int)((float)i/(float)thread_data.p_projects->size()*(float)100);

					//check if the program is exiting
					new_event = WaitForMultipleObjects(num_events,events,wait_all,0);
					if(new_event==0)
					{
						ResetEvent(events[event]);
						break;
					}
				}
				thread_data.m_demand_progress = (int)((float)i/(float)thread_data.p_projects->size()*(float)100);
				if(new_event==0)
				{
					singleLock.Unlock();
					break;
				}
				singleLock.Unlock();
				break;
			}
		}
	}

	// Close the events
	for(i=0;i<sizeof(events)/sizeof(HANDLE);i++)
	{
		CloseHandle(events[i]);
	}
	
	thread_data.m_demand_progress = 100;

	if(event!=0)
		::PostMessage(hwnd, WM_PROCESST_MANAGER_DONE,0,0);
	
	return 0;	// exit the thread
}
Beispiel #15
0
int CClientContext::SendData( const BYTE* pBuf, DWORD dwSize )
{	
	CSingleLock singleLock(&m_SendLock, TRUE);
	//return SyncSendData(pBuf, dwSize);
	return AsynSendData(pBuf, dwSize);
}
UINT ConnectionModuleThreadProc(LPVOID pParam)
{
	UINT i;
	// Init message window handle
	HWND hwnd=(HWND)pParam;

	// Init the message data structure and send it
	CCriticalSection critical_section;
	ConnectionModuleThreadData thread_data;
	ConnectionModuleStatusData status_data;
	vector<SupernodeHost> connect_hosts;
	vector<ProjectSupplyQuery> project_supply_queries;
	vector<ProjectKeywords> keywords;
	//vector<SupplyProject> supply;

	// Create the sockets for this module
	ConnectionSockets sockets;
	sockets.m_dlg_hwnd = hwnd;
	memcpy(&thread_data.m_reserved_events[0],&sockets.m_events[0],sizeof(WSAEVENT)*5);
	thread_data.p_status_data=&status_data;
	thread_data.p_connect_hosts=&connect_hosts;
	thread_data.p_project_supply_queries=&project_supply_queries;
	thread_data.p_keywords=&keywords;
	//thread_data.p_supply=&supply;
	SendMessage(hwnd,WM_INIT_THREAD_DATA,(WPARAM)&critical_section,(LPARAM)&thread_data);
	sockets.p_file_sharing_manager = thread_data.p_file_sharing_manager;

	int num_reserved_events=sockets.ReturnNumberOfReservedEvents();

	WSANETWORKEVENTS events;	// what the fired event data was

	DWORD num_events=sockets.ReturnNumberOfEvents();	// 64
	BOOL wait_all=FALSE;
	DWORD timeout=WSA_INFINITE;
	BOOL alertable=FALSE;
	DWORD event;	// which event fired
	
	// Seed random number generator
	srand((unsigned)time(NULL));

/*
#ifdef SHARING_ENABLED
		sockets.CreateSpoofShares();
#endif
*/
	while(1)
	{
		event=WSAWaitForMultipleEvents(num_events,&sockets.m_events[0],wait_all,timeout,alertable);
		
		char buf[16];
		_itoa(event,buf,10);
		
		if(event==WSA_WAIT_FAILED)
		{
			::MessageBox(NULL,"Wait Failed.","Error",MB_OK);
			break;
		}

		// Check to see if this is the kill thread event (reserved event 0)
		if(event==0)
		{
			WSAResetEvent(sockets.m_events[event]);	// reset event
			break;
		}

		// Process all the items in the process queue and cancel all the transfers in the cancel queue
		if(event==1)
		{
			// Temp variables
			vector<SupernodeHost> tmp_connect_hosts;
			vector<ProjectSupplyQuery> tmp_project_supply_queries;
			vector<ProjectKeywords> tmp_keywords;
			//vector<SupplyProject> tmp_supply;
			
			// Copy the critical data to the temp variables
			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				WSAResetEvent(sockets.m_events[event]);	// reset event

				if(connect_hosts.size()>0)
				{
					tmp_connect_hosts=connect_hosts;
					connect_hosts.clear();
				}
				if(project_supply_queries.size()>0)
				{
					tmp_project_supply_queries=project_supply_queries;
					project_supply_queries.clear();
				}
				if(keywords.size()>0)
				{
					tmp_keywords=keywords;
					keywords.clear();
				}
				/*
				if(supply.size()>0)
				{
					tmp_supply=supply;
					supply.clear();
				}
				*/

				singleLock.Unlock();
			}

			// Call the functions, passing the temp data
			if(tmp_connect_hosts.size()>0)
			{
				if(!thread_data.m_disconnect_to_hosts)
					sockets.ConnectToHosts(tmp_connect_hosts);
			}
			if(tmp_project_supply_queries.size()>0)
			{
				for(i=0;i<(int)tmp_project_supply_queries.size();i++)
				{
					sockets.PerformProjectSupplyQuery(tmp_project_supply_queries[i]);
				}
			}
			
			if(tmp_keywords.size()>0)
			{
				sockets.UpdateKeywords(tmp_keywords);
			}
			/*
			if(tmp_supply.size()>0)
			{
				sockets.UpdateSupply(tmp_supply);
			}
			*/
			if(thread_data.m_reconnect_to_hosts)
			{
				thread_data.m_reconnect_to_hosts = false;
				sockets.ReConnectAll();
			}
			if(thread_data.m_disconnect_to_hosts)
			{
				sockets.ReConnectAll();
			}
		}

		// The Timer has fired...tell the mod our latest info.
		if(event==2)
		{
			// Extract the status data from the sockets as temp data
			//ConnectionModuleStatusData tmp_status_data=sockets.ReportStatus();

			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				WSAResetEvent(sockets.m_events[event]);	// reset event
				
				//status_data=tmp_status_data;	 // copy the temp data
				sockets.ReportStatus(status_data);

				singleLock.Unlock();
			}
			
			PostMessage(hwnd,WM_STATUS_READY,0,0);
		}

		// Event 3
		if(event==3)
		{
			vector<VendorCount> *tmp_vendor_counts=sockets.ReturnVendorCounts();

			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				WSAResetEvent(sockets.m_events[event]);	// reset event

				// Do nothing else

				singleLock.Unlock();
			}

			PostMessage(hwnd,WM_VENDOR_COUNTS_READY,(WPARAM)tmp_vendor_counts,(LPARAM)0);
		}
/*	
		if(event==4) //searching
		{
			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				WSAResetEvent(sockets.m_events[event]);	// reset event

				// Do nothing else
				sockets.Search(thread_data.m_search_string);

				singleLock.Unlock();
			}
		}
*/
		// Else it is a socket event
		if(event>3)
		{
			WSAResetEvent(sockets.m_events[event]);	// reset event

			int index=event-num_reserved_events;
			
			events=sockets.m_sockets[index].ReturnNetworkEvents();
			
			if(events.lNetworkEvents & FD_CONNECT)
			{
				sockets.m_sockets[index].OnConnect(events.iErrorCode[FD_CONNECT_BIT]);
			}
			if(events.lNetworkEvents & FD_READ)
			{
				sockets.m_sockets[index].OnReceive(events.iErrorCode[FD_READ_BIT]);
			}
			if(events.lNetworkEvents & FD_WRITE)
			{
				sockets.m_sockets[index].OnSend(events.iErrorCode[FD_WRITE_BIT]);
			}
			if(events.lNetworkEvents & FD_CLOSE)
			{
				sockets.m_sockets[index].OnClose(events.iErrorCode[FD_CLOSE_BIT]);
			}
			if(events.lNetworkEvents & FD_ACCEPT)
			{
				sockets.m_sockets[index].OnAccept(events.iErrorCode[FD_ACCEPT_BIT]);
			}
		}
	}
	TRACE("Terminating ConnectionModuleThreadProc\n");
	return 0;	// exit the thread
}
/****** C_Communication::DoComm() const ****************************************
*  NAME
*     C_Communication::DoComm() const -- does the communication
*
*  SYNOPSIS
*     int C_Communication::DoComm() const
*
*  FUNCTION
*     Does the communication with sge_shepherd. I.e. whenever a sge_shepherd
*     connects to the server, it receives the request, does what is requested
*     and then shuts down the connection.
*
*  RESULT
*     int - 0 if command was successfully received and processed, 1 else
*
*  NOTES
*******************************************************************************/
int C_Communication::DoComm() const
{
   int                ret = 1;
   int                idx = 0;
   SOCKET             comm_sock;
   int                remote_saddr_len;
   struct sockaddr_in remote_saddr;
   char               szMessage[1024];
   char               command[COMMAND_SIZE];
   const int          commandsize = sizeof(command);
   C_Job              Job;
   C_Job              *pJob = NULL;
   en_request_type    request_type;

   remote_saddr_len = sizeof(remote_saddr);
   comm_sock = accept(m_ListenSocket, 
                     (struct sockaddr*)&remote_saddr, &remote_saddr_len);
   if(comm_sock == INVALID_SOCKET) {
      return WSAGetLastError();
   }

   ZeroMemory(command, COMMAND_SIZE);
   while((ret=recv(comm_sock, command+idx, commandsize-idx, 0))>0) {
      idx += ret;
      if(command[idx-1] == EOF) {
         break;
      }
   }
   if(ret == -1) {
      ret = WSAGetLastError();
      ShutdownSocket(&comm_sock);
      return ret;
   }
   ret = 0;

   request_type = Job.ParseCommand(command);

   switch(request_type) {
      case req_job_start:
         POSITION Pos;
         HANDLE   hThread;

         if(g_bAcceptJobs) {
            Job.m_comm_sock = comm_sock;

            sprintf(szMessage, "Starting job %lu.%lu %s", 
               Job.m_job_id, Job.m_ja_task_id,
               Job.m_pe_task_id ? Job.m_pe_task_id : "<null>");
            WriteToLogFile(szMessage);

            // try to put job in job list
            pJob = new C_Job(Job);
            Pos = g_JobList.AddJobToList(pJob);
         }

         if(Pos != NULL) {
            // job is not already in job list, send ACK and start worker thread
            hThread = CreateThread(NULL, 0, JobStarterThread, 0, 0, 0);
            CloseHandle(hThread);
         } else {
            // job is already in job list, send NACK and delete job object
            strcpy(szMessage, "NAK");
            szMessage[strlen(szMessage)+1] = (char)EOF;
            send(comm_sock, szMessage, (int)strlen(szMessage)+2, 0);
            ShutdownSocket(&comm_sock);
            delete pJob;
            pJob = NULL;
         }
         break;

      case req_send_job_usage:
         pJob = g_JobList.RemoveJobFromList(Job);
         if(pJob) {
            pJob->m_comm_sock = comm_sock;
            SendJobUsage(*pJob);
            delete pJob;
            pJob = NULL;
            sprintf(szMessage, "Sending usage of job %lu.%lu %s",
                        Job.m_job_id, Job.m_ja_task_id,
                        Job.m_pe_task_id ? Job.m_pe_task_id : "<null>");
         } else {
            sprintf(szMessage, "Warning: Job %lu.%lu %s not found!",
                        Job.m_job_id, Job.m_ja_task_id,
                        Job.m_pe_task_id ? Job.m_pe_task_id : "<null>");
         }
         WriteToLogFile(szMessage);
         ShutdownSocket(&comm_sock);
         break;

      case req_forward_signal:
         // lock access to job list
         CSingleLock singleLock(&g_JobList.m_JobListMutex);
         singleLock.Lock();
         pJob = g_JobList.FindJobInList(Job);
         if(pJob
            && pJob->m_JobStatus != js_Finished
            && pJob->m_JobStatus != js_Failed
            && pJob->m_JobStatus != js_Deleted) {
            BOOL bRet = FALSE;
            char szAnswer[100];
            int  sent;

            if(pJob->m_hProcess != INVALID_HANDLE_VALUE
               && pJob->m_hJobObject != INVALID_HANDLE_VALUE) {
               bRet = TerminateJobObject(pJob->m_hJobObject, 0);
               if(bRet) {
                  pJob->m_JobStatus = js_Deleted;
               }
            }
            singleLock.Unlock();
            
            sprintf(szAnswer, "%s", bRet ? "ACK" : "NAK");
            szAnswer[strlen(szAnswer)+1] = (char)EOF;
            sent = send(comm_sock, szAnswer, (int)strlen(szAnswer)+2, 0);
            if(sent >= 0) {
               ret = 0;
            }
         } else {
            singleLock.Unlock();
         }
         ShutdownSocket(&comm_sock);
         break;
   }
   return ret;
}
UINT FTConnectionModuleThreadProc(LPVOID pParam)
{
//	int i;

	// Init message window handle
	FTConnectionModule* pConnectionModule = (FTConnectionModule*)pParam;
	HWND hwnd=pConnectionModule->m_hwnd;

	CCriticalSection critical_section;
//	ConnectionModuleStatusData status_data;
	vector<SOCKET> incoming_connection_socket_handles;
	FTConnectionModuleThreadData thread_data;
//	vector<ProjectKeywords> keywords;
	//vector<SupplyProject> supply;
//	vector<ProjectSupplyQuery> project_supply_queries;
//	UINT max_host = 0;
//	UINT max_host_cache = 0;

//	thread_data.p_status_data=&status_data;
//	thread_data.p_keywords=&keywords;
//	thread_data.p_project_supply_queries=&project_supply_queries;
//	thread_data.p_max_host=&max_host;
//	thread_data.p_max_host_cache=&max_host_cache;

	thread_data.p_incoming_connection_socket_handles=&incoming_connection_socket_handles;
	ConnectionSockets m_socket;
	memcpy(&thread_data.m_reserved_events[0],&m_socket.m_events[0],sizeof(WSAEVENT)*4);


	//	m_socket.InitHwnd(hwnd);
	//m_socket.InitParent((FTConnectionModule*)pParam);

	WSANETWORKEVENTS events;	// what the fired event data was

	DWORD num_events=m_socket.ReturnNumberOfEvents();	// 64
	BOOL wait_all=FALSE;
	DWORD timeout=WSA_INFINITE;
	BOOL alertable=FALSE;
	DWORD event;	// which event fired

//	thread_data.p_vendor_counts = m_socket.ReturnVendorCountsPointer();
	int num_reserved_events=m_socket.ReturnNumberOfReservedEvents();


	// Init the message data and send it
	LRESULT ret = ::SendMessage(hwnd,WM_FT_INIT_THREAD_DATA,(WPARAM)&critical_section,(LPARAM)&thread_data);

	// Seed random number generator
	srand((unsigned)time(NULL));

	while(1)
	{
		event=WSAWaitForMultipleEvents(num_events,&m_socket.m_events[0],wait_all,timeout,alertable);
		
		char buf[16];
		_itoa(event,buf,10);
		
		if(event==WSA_WAIT_FAILED)
		{
			::MessageBox(NULL,"Wait Failed.","Error",MB_OK);
			break;
		}

		// Check to see if this is the kill thread event (reserved event 0)
		if(event==0)
		{
			WSAResetEvent(m_socket.m_events[event]);	// reset event
			break;
		}

		// Process all the items in the process queue and cancel all the transfers in the cancel queue
		if(event==1)
		{
			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				WSAResetEvent(m_socket.m_events[event]);
				char ip[32];
				strcpy(ip, thread_data.m_ip.c_str());
				//m_socket.ConnectToHost(ip, thread_data.m_port, thread_data.m_file_length, thread_data.m_md5.c_str());
				//m_socket.AcceptConnection(thread_data.m_socket,ip, thread_data.m_port, thread_data.m_file_length, thread_data.m_md5.c_str());
				// Incoming connection queue
				if(incoming_connection_socket_handles.size()>0)
				{
					for(UINT i=0;i<incoming_connection_socket_handles.size();i++)
					{
						m_socket.AcceptConnection(incoming_connection_socket_handles[i],ip, thread_data.m_port, thread_data.m_file_length, thread_data.m_md5.c_str());
					}

					incoming_connection_socket_handles.clear();
				}
				singleLock.Unlock();
			}

			/*
			// Temp variables
			vector<ProjectKeywords> tmp_keywords;
			//vector<SupplyProject> tmp_supply;
			vector<ProjectSupplyQuery> tmp_project_supply_queries;
			UINT tmp_max_host = 0;
			UINT tmp_max_host_cache = 0;

			// Copy the critical data to the temp variables
			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				WSAResetEvent(events[event]);	// reset event
				if(keywords.size()>0)
				{
					tmp_keywords=keywords;
					keywords.clear();
				}
				if(project_supply_queries.size()>0)
				{
					tmp_project_supply_queries=project_supply_queries;
					project_supply_queries.clear();
				}
				if(max_host > 0)
				{
					tmp_max_host = max_host;
					max_host = 0;
				}
				if(max_host_cache > 0)
				{
					tmp_max_host_cache = max_host_cache;
					max_host_cache = 0;
				}
				singleLock.Unlock();
			}

			// Call the functions, passing the temp data
			
			if(tmp_keywords.size()>0)
			{
				m_socket.UpdateProjectKeywords(tmp_keywords);
			}
			if(tmp_project_supply_queries.size()>0)
			{
				for(i=0;i<(int)tmp_project_supply_queries.size();i++)
				{
					m_socket.PerformProjectSupplyQuery(tmp_project_supply_queries[i]);
				}
			}
			if(tmp_max_host > 0)
			{
				m_socket.UpdateHostLimit(tmp_max_host);
			}
			if(tmp_max_host_cache > 0)
			{
				m_socket.UpdateHostCacheLimit(tmp_max_host_cache);
			}
			*/
		}

		// The Timer has fired...tell the mod our latest info.
		if(event==2)
		{
			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				WSAResetEvent(m_socket.m_events[event]);
				
				thread_data.m_num_idle_sockets=m_socket.GetNumIdleSockets();

				singleLock.Unlock();
			}
			/*
			// Extract the status data from the sockets as temp data
			ConnectionModuleStatusData tmp_status_data=pConnectionModule->ReportStatus();

			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				WSAResetEvent(events[event]);	// reset event
				
				status_data=tmp_status_data;	 // copy the temp data
				m_socket.TimerHasFired();				

				singleLock.Unlock();
			}

			PostMessage(hwnd,WM_SPOOF_DATA_READY,0,0);
			*/
		}

		// Event 3
		if(event==3)
		{
			
			CSingleLock singleLock(&critical_section);
			singleLock.Lock();
			if(singleLock.IsLocked())
			{
				WSAResetEvent(m_socket.m_events[event]);	// reset event

				m_socket.CloseIdleSockets();

				singleLock.Unlock();
			}
			
		}
	
		// Else it is a socket event
		if(event>3)
		{
			WSAResetEvent(m_socket.m_events[event]);	// reset event

			int index=event-num_reserved_events;

			events=m_socket.m_sockets[index].ReturnNetworkEvents();
			
			if(events.lNetworkEvents & FD_CONNECT)
			{
				m_socket.m_sockets[index].OnConnect(events.iErrorCode[FD_CONNECT_BIT]);
			}
			if(events.lNetworkEvents & FD_READ)
			{
				m_socket.m_sockets[index].OnReceive(events.iErrorCode[FD_READ_BIT]);
			}
			if(events.lNetworkEvents & FD_WRITE)
			{
				m_socket.m_sockets[index].OnSend(events.iErrorCode[FD_WRITE_BIT]);
			}
			if(events.lNetworkEvents & FD_CLOSE)
			{
				m_socket.m_sockets[index].OnClose(events.iErrorCode[FD_CLOSE_BIT]);
			}
			if(events.lNetworkEvents & FD_ACCEPT)
			{
				m_socket.m_sockets[index].OnAccept(events.iErrorCode[FD_ACCEPT_BIT]);
			}
		}
	}

	/*
	// Close the reserved events
	for(int i=0;i<num_reserved_events;i++)
	{
		if(WSACloseEvent(events[i])==FALSE)
		{
			char msg[1024];
			strcpy(msg,"Could not close reserved event ");
			_itoa(i,&msg[strlen(msg)],10);
			::MessageBox(NULL,msg,"Error",MB_OK);
		}
	}
	*/

	return 0;	// exit the thread
}
/* Low priority task checks if there's a message to be received from CONSIS and then sleeps for 200 msec */
DWORD WINAPI AsynchDialogueListenerThread(CPharmaRobot10Dlg* pdialog)
{
	int MessageLength, MessagePSize = 114, MessageISize = 67, lisRobotItem;
	char buffer[MAX_CONSIS_MESSAGE_SIZE];
	size_t retsize,	convertedChars = 0;;
	pConsisRequestMessage * ppRequestMessage;
	PConsisPmsResponseMessage PResponseToConsis;
	iConsisRequestMessage * piRequestMessage;
	IConsisPmsResponseMessage IResponseToConsis;
	wchar_t description[256], wcstring[256];

	for (;;) //Run forever
	{
		//Perform Message checking only if CONSIS is connected
		if (pdialog->Consis.ConnectionStarted == TRUE)
		{

			//Try to catch the Mutex for CONSIS Access
			//Protect with Mutex the CONSIS resource
			CSingleLock singleLock(&(pdialog->m_Mutex));

			// Attempt to lock the shared resource
			if (singleLock.Lock(INFINITE))
			{
				//log locking success
			}

			//clear buffer
			memset(buffer, 0, MAX_CONSIS_MESSAGE_SIZE);

			MessageLength = sizeof(buffer);
			pdialog->Consis.ReceiveConsisMessage(buffer, &MessageLength, 0 ); //no timeout

			//Check if we received a 'p' request and handle it
			if (buffer[0] == 'p')
			{//handle a 'p' message here
				mbstowcs_s(&convertedChars, wcstring, sizeof(pConsisRequestMessage) + 1, buffer, _TRUNCATE);
				wcstring[sizeof(pConsisRequestMessage)] = L'\0';
				pdialog->m_listBoxMain.AddString(wcstring);

				ppRequestMessage = (pConsisRequestMessage *)buffer;
				//Extract Article ID
				wchar_t articleID[31];
				articleID[30] = '\0';
				mbstowcs_s(&retsize, articleID, sizeof(ppRequestMessage->ArticleId) + 1, ppRequestMessage->ArticleId, _TRUNCATE);

				//Clean leading zeroes
				CString cleanArticleID;
				cleanArticleID.SetString(articleID);
				cleanArticleID.TrimLeft(L' ');
				cleanArticleID.TrimLeft(L'0');
				wsprintf(articleID,cleanArticleID.GetString());

				//clean the message to CONSIS
				memset ((void*)&PResponseToConsis, '0',sizeof(PResponseToConsis));
				memset (&(PResponseToConsis.ArticleName),' ',sizeof(PResponseToConsis.ArticleName));

				//Get Description from Yarpa SQL
				if (pdialog->GetItemDescFromBarcode(articleID, description))
				{//Got a description
					char DescriptionInChar[40];
					wcstombs(DescriptionInChar, description, 39);
					sprintf(PResponseToConsis.ArticleName,DescriptionInChar);
				}
				else
				{
					sprintf(PResponseToConsis.ArticleName, "Name Missing");
				}
				PResponseToConsis.RecordType = 'P';
				memcpy(&(PResponseToConsis.ArticleId), ppRequestMessage->ArticleId, sizeof(PResponseToConsis.ArticleId));

				mbstowcs_s(&convertedChars, wcstring, sizeof(PResponseToConsis) + 1, (char*)&PResponseToConsis, _TRUNCATE);
				wcstring[sizeof(PResponseToConsis)] = L'\0';
				pdialog->m_listBoxMain.AddString(wcstring);
				//Send a response to CONSIS
				pdialog->Consis.SendConsisMessage((char*)&PResponseToConsis, MessagePSize);
			}

			//Check if we received an 'i' request and handle it
			if (buffer[0] == 'i')
			{//handle an 'i' message here
				mbstowcs_s(&convertedChars, wcstring, sizeof(iConsisRequestMessage) + 1, buffer, _TRUNCATE);
				wcstring[sizeof(iConsisRequestMessage)] = L'\0';
				pdialog->m_listBoxMain.AddString(wcstring);

				piRequestMessage = (iConsisRequestMessage *)buffer;

				//Extract Article ID
				wchar_t articleID[31];
				articleID[30] = '\0';
				mbstowcs_s(&retsize, articleID, sizeof(piRequestMessage->ArticleId) + 1, piRequestMessage->ArticleId, _TRUNCATE);

				//Clean leading zeroes
				CString cleanArticleID;
				cleanArticleID.SetString(articleID);
				cleanArticleID.TrimLeft(L'0');
				cleanArticleID.TrimLeft(L' ');
				wsprintf(articleID,cleanArticleID.GetString());

				//clean the message to CONSIS
				//State will be set to '00' by this action
				memset ((void*)&IResponseToConsis, '0',sizeof(IResponseToConsis));

				//check if message is '04-New article (return) '05-New article (goods receipt) type.
				if ((piRequestMessage->OrderState[1] == '4') || (piRequestMessage->OrderState[1] == '5'))
				{
					//Check if TA is 999 in Yarpa DB for this Barcode number
					if (pdialog->GetTaFromYarpaByBarcode(articleID, &lisRobotItem))
					{//Got a TA from SQL
						if(lisRobotItem != 999)
							IResponseToConsis.State[1]='1';//Article may not be stored as its not a ROBOT item according to YARPA DB
					}
					else
					{
						IResponseToConsis.State[1]='1';//Article may not be stored as not found in YARPA DB
					}
				}

				IResponseToConsis.RecordType = 'I';
				//Get Article ID from request
				memset((char*)(&(IResponseToConsis.ArticleId[0])), ' ', 30);
				memcpy(&(IResponseToConsis.ArticleId), piRequestMessage->ArticleId, sizeof(IResponseToConsis.ArticleId));

				//Get Order number from request
				memcpy(&(IResponseToConsis.OrderNumber), piRequestMessage->OrderNumber, sizeof(IResponseToConsis.OrderNumber));

				//Get Demanding Counetr ID from request
				memcpy(&(IResponseToConsis.DemandingCounterUnitId), piRequestMessage->DemandingCounterUnitId, 
					sizeof(IResponseToConsis.DemandingCounterUnitId));

				//IResponseToConsis.Text[3] = '/0'; //Null terminator at the end of no text string
				IResponseToConsis.Text[3] = ' ';
				
				mbstowcs_s(&convertedChars, wcstring, sizeof(IResponseToConsis) + 1, (char*)&IResponseToConsis, _TRUNCATE);
				wcstring[sizeof(IResponseToConsis)] = L'\0';
				pdialog->m_listBoxMain.AddString(wcstring);
				//Send a response to CONSIS
				pdialog->Consis.SendConsisMessage((char*)&IResponseToConsis, MessageISize);
			}

			//Ignore all other messages

			singleLock.Unlock();
		
		}//CONSIS connected if statement context

		Sleep(200);
	}
	// NOT REACHED

	return 0;
}
Beispiel #20
0
UINT ClientReceiverThreadProc(LPVOID pParam)
{
	// Init message window handle
	if( pParam == NULL )
		return (UINT)-1;

	seedRand();

	// Copy data from the param to the locals
	HWND hwnd = (HWND)pParam;

	// Create the listening socket, but do not open it
	ListeningSocket listener( hwnd );

	// Link event into events array
	WSAEVENT aEvents[CLIENTRECEIVER_RESERVED_EVENTS+1];
	for( int i = 0; i < CLIENTRECEIVER_RESERVED_EVENTS; i++ )
	{
		aEvents[i] = WSACreateEvent();
		if( aEvents[i] == WSA_INVALID_EVENT )
			return (UINT)-1;
	}
	aEvents[CLIENTRECEIVER_RESERVED_EVENTS] = listener.ReturnEventHandle();

	// Critical variables
	ListeningSocket::ListenerStatus eCriticalStatus;

	// Threaddata variables
	ClientReceiverThreadData threadData;
	memcpy( threadData.m_aReservedEvents, aEvents, sizeof(WSAEVENT) * CLIENTRECEIVER_RESERVED_EVENTS );
	threadData.m_peStatus = &eCriticalStatus;

	CCriticalSection criticalSection;

	// request initialization of the thread data
	::PostMessage( hwnd, WM_LISTENER_INIT_THREAD_DATA, (WPARAM)&criticalSection, (LPARAM)&threadData );

	WSANETWORKEVENTS events;			// what the fired event data was
	DWORD event;						// which event fired
	char *pLogMsg = NULL;
	
	while(true)
	{
		event = WSAWaitForMultipleEvents( (CLIENTRECEIVER_RESERVED_EVENTS + 1), aEvents, false, WSA_INFINITE, false );
		
		char buf[16];
		_itoa( event, buf, 10 );

		if( event == WSA_WAIT_FAILED )
			AfxAbort();

		// exit event
		if( event == 0 )
		{
			CSingleLock singleLock( &criticalSection, true );
			WSAResetEvent( aEvents[event] );
			break;
		}

		// change status
		if( event == 1 )
		{
			CSingleLock singleLock( &criticalSection, true );

			switch( eCriticalStatus )
			{
			case ListeningSocket::OPEN:
				listener.Open();
				break;
			case ListeningSocket::CLOSED:
				listener.Close();
				break;
			}

			WSAResetEvent( aEvents[event] );
		}

		// socket event
		if( event >= CLIENTRECEIVER_RESERVED_EVENTS )
		{
			WSAResetEvent( aEvents[event] );

			events = listener.ReturnNetworkEvents();
			
			if(events.lNetworkEvents & FD_CONNECT)
			{
				listener.OnConnect(events.iErrorCode[FD_CONNECT_BIT]);
			}
			if(events.lNetworkEvents & FD_READ)
			{
				while( listener.OnReceive(events.iErrorCode[FD_READ_BIT]) );
			}
			if(events.lNetworkEvents & FD_WRITE)
			{
				listener.OnSend(events.iErrorCode[FD_WRITE_BIT]);
			}
			if(events.lNetworkEvents & FD_CLOSE)
			{
				listener.OnClose(events.iErrorCode[FD_CLOSE_BIT]);
			}
			if(events.lNetworkEvents & FD_ACCEPT)
			{
				listener.OnAccept(events.iErrorCode[FD_ACCEPT_BIT]);
			}
		}

	}	// end while(1)

	// Close the reserved events
	for( int i = 0; i < CLIENTRECEIVER_RESERVED_EVENTS; i++ )
		WSACloseEvent( aEvents[i] );

	// close the socket
	listener.Close();

	return 0;	// exit the thread
}