// Start the server. This blocks until the server stops.
void AgentConfigurationEx::start ( )
{
  GLogger.Fatal("AgentConfigurationEx::start\n");

  for ( int i = 0; i < _devices.size( ); i++ )
  {
    ABBAdapter *_cmdHandler = new ABBAdapter(this, config, _devices[i]);
    _cncHandlers.push_back(_cmdHandler);
    _group.create_thread(boost::bind(&ABBAdapter::Cycle, _cncHandlers[i]) );
  }

  if ( Globals.ResetAtMidnight )
  {
    COleDateTime     now          = COleDateTime::GetCurrentTime( );
    COleDateTimeSpan tilnextreset = COleDateTimeSpan(0, 1, 0, 0);
    GLogger.Fatal(StdStringFormat("Agent will Reset from now  %8.4f\n", ( tilnextreset.GetTotalSeconds( ) / 3600.00 ) ) );

    _resetthread.Initialize( );

    _resetthread.AddTimer(
      (long) tilnextreset.GetTotalSeconds( ) * 1000,
      &_ResetThread,
      ( DWORD_PTR ) this,
      &_ResetThread._hTimer        // stored newly created timer handle
      );
  }

  AgentConfigurationT::start( );  // does not return
}
// NOTE: Windows SCM more tolerant of slow starting processes than terminating processes.
void MtcOpcAdapter::start()
{
 	static char name[] = "MtcOpcAdapter::start";
	_bRunning=true; 
	if(_bResetAtMidnight)
	{
		COleDateTime now = COleDateTime::GetCurrentTime();
		COleDateTime date2 =  COleDateTime(now.GetYear(), now.GetMonth(), now.GetDay(), 0, 0, 0) +  COleDateTimeSpan(1, 0, 0, 1);
		//COleDateTime date2 =  now +  COleDateTimeSpan(0, 0, 2, 0); // testing reset time - 2 minutes

		COleDateTimeSpan tilmidnight = date2-now;
		_resetthread.Initialize();
		_resetthread.AddTimer(
			(long) tilmidnight.GetTotalSeconds() * 1000,
			&_ResetThread,
			(DWORD_PTR) this,
			&_ResetThread._hTimer  // stored newly created timer handle
			) ;

		GLogger << INFO << "Adapter will Reset At Midnight " << date2.Format() << std::endl;
	}

	if(_bOPCEnabled)
	{
		_workerthread.Initialize();
		::SetEvent (_StartThread._hEvent); // start OPC thread
		_workerthread.AddHandle(_StartThread._hEvent, &_StartThread,(DWORD_PTR) this);
	}

	// This goes last... never returns
	startServer();
}
// Start the server. This blocks until the server stops.
void AgentConfigurationEx::start()
{
	GLogger.LogMessage(StdStringFormat("AgentConfigurationEx::start()\n"));
	getAgent()->set_listening_port(Globals.HttpPort);
	MTConnectService::setName(Globals.ServerName);

	for(int i=0; i< _ipaddrs.size(); i++)
	{
		COpcAdapter *  _cmdHandler = new COpcAdapter(this, config, _ipaddrs[i], _devices[i], _tags[i]);
		_cncHandlers.push_back(_cmdHandler);
		GLogger.LogMessage(StdStringFormat("AgentConfigurationEx::start COpcAdapter::Cycle() %x\n",_ipaddrs[i]), DBUG);
		_group.create_thread(boost::bind(&COpcAdapter::Cycle, _cncHandlers[i]));
	}
	GLogger.LogMessage(StdStringFormat("Call AgentConfiguration::start() ed \n"));

	if(Globals.ResetAtMidnight)
	{
		COleDateTime now = COleDateTime::GetCurrentTime();
		COleDateTime date2 =  COleDateTime(now.GetYear(), now.GetMonth(), now.GetDay(), 0, 0, 0) +  COleDateTimeSpan(1, 0, 0, 1);
		//COleDateTime date2 =  now +  COleDateTimeSpan(0, 0, 2, 0); // testing reset time - 2 minutes
		COleDateTimeSpan tilmidnight = date2-now;
		_resetthread.Initialize();
		_resetthread.AddTimer(
			(long) tilmidnight.GetTotalSeconds() * 1000,
			&_ResetThread,
			(DWORD_PTR) this,
			&_ResetThread._hTimer  // stored newly created timer handle
			) ;

		GLogger.LogMessage(StdStringFormat("Agent will Reset At Midnight %s \n", (LPCSTR) date2.Format()), DBUG);
	}

	AgentConfiguration::start(); // does not return
}
Esempio n. 4
0
//------------------------------------------------------------------------------------
bool CAutoRegisterConfig::SetTimeRange( 
	CDateTimeCtrl& start, CDateTimeCtrl& end, 
	CString& strStartMin, CString& strEndMin, 
	int nStartHour, int nEndHour )
{
	SYSTEMTIME smStart, smEnd;
	start.GetTime(&smStart);
	end.GetTime(&smEnd);
	
	m_startTime.SetDateTime(smStart.wYear, smStart.wMonth, smStart.wDay,nStartHour,
		_ttoi(strStartMin), 0);

	m_endTime.SetDateTime(smEnd.wYear, smEnd.wMonth, smEnd.wDay,nEndHour,
		_ttoi(strEndMin), 0);

	COleDateTimeSpan dtSpan = m_endTime - m_startTime;

	if (dtSpan.GetTotalSeconds() <= 0)
	{
		AfxMessageBox(_T("结束时间不得小于起始时间"));
		return false;
	}
	COleDateTime dtEnd, dtStart;
	dtStart.SetDate(m_startTime.GetYear(), m_startTime.GetMonth(), m_startTime.GetDay());
	dtEnd.SetDate(m_endTime.GetYear(), m_endTime.GetMonth(), m_endTime.GetDay());
	COleDateTimeSpan dtSpan2;
	if(dtSpan2.GetTotalDays() > m_array24Amount.size())
	{
		AfxMessageBox(_T("开始时间和结束时间之间的天数不能大于每天开户金额的天数"));
		return false;
	}
	
	return true;
}
Esempio n. 5
0
/**
 *	Generates a display string showing the relative time between the two given times as COleDateTimes
 */
CString CLoglistUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
{
	COleDateTimeSpan ts = RelativeTo - time;

	//years
	if(fabs(ts.GetTotalDays()) >= 3 * 365)
		return ExpandRelativeTime((int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO);

	//Months
	if(fabs(ts.GetTotalDays()) >= 60)
		return ExpandRelativeTime((int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO);

	//Weeks
	if(fabs(ts.GetTotalDays()) >= 14)
		return ExpandRelativeTime((int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO);

	//Days
	if(fabs(ts.GetTotalDays()) >= 2)
		return ExpandRelativeTime((int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO);

	//hours
	if(fabs(ts.GetTotalHours()) >= 2)
		return ExpandRelativeTime((int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO);

	//minutes
	if(fabs(ts.GetTotalMinutes()) >= 2)
		return ExpandRelativeTime((int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO);

	//seconds
	return ExpandRelativeTime((int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO);
}
bool AgentConfigurationEx::ResetAtMidnite ( )
{
	COleDateTime now   = COleDateTime::GetCurrentTime( );
#ifndef RESETTEST
	COleDateTime date2 = COleDateTime(now.GetYear( ), now.GetMonth( ), now.GetDay( ), 0, 0, 0) + COleDateTimeSpan(1, 0, 0, 1);
#else
	COleDateTime date2 =  now +  COleDateTimeSpan(0, 0, 2, 0); // testing reset time - 2 minutes
#endif
	COleDateTimeSpan tilmidnight = date2 - now;
	GLogger.Fatal(StdStringFormat("Agent will Reset at  %s\n", date2.Format("%A, %B %d, %Y %H:%M:%S")  ) );
	GLogger.Fatal(StdStringFormat("Agent will Reset %8.4f hours::min from now\n", ( tilmidnight.GetTotalSeconds( ) / 3600.00 ) ) );

	_resetthread.Initialize( );
	_resetthread.AddTimer(
		(long) tilmidnight.GetTotalSeconds( ) * 1000,
		&_ResetThread,
		( DWORD_PTR ) this,
		&_ResetThread._hTimer      // stored newly created timer handle
		);
	return true;
}
Esempio n. 7
0
BOOL CActiveMember::IsOffLinePossibility()
{
	if ( GetIsOnLine() )
	{
		COleDateTimeSpan dtSpan = COleDateTime::GetCurrentTime() - UpdateDataTime;

		// 2014-1-10-qsc 把6m30s改成2m30s
		return dtSpan.GetTotalSeconds() > (2 * 60 + 30); //上一次的更新时间和当前时间的间隔>2m30s
		// 可以认为可能离线了。
	}
	
	return FALSE;
}
Esempio n. 8
0
void CSystemTray::OnTimer(UINT nIDEvent) 
{
    ASSERT(nIDEvent == m_nIDEvent);

    COleDateTime CurrentTime = COleDateTime::GetCurrentTime();
    COleDateTimeSpan period = CurrentTime - m_StartTime;
    if (m_nAnimationPeriod > 0 && m_nAnimationPeriod < period.GetTotalSeconds())
    {
        StopAnimation();
        return;
    }

    StepAnimation();
}
bool AgentConfigurationEx::ResetAtMidnite ( )
{
  COleDateTime now   = COleDateTime::GetCurrentTime( );
  COleDateTime date2 = COleDateTime(now.GetYear( ), now.GetMonth( ), now.GetDay( ), 0, 0, 0) + COleDateTimeSpan(1, 0, 0, 1);

  // COleDateTime date2 =  now +  COleDateTimeSpan(0, 0, 2, 0); // testing reset time - 2 minutes
  COleDateTimeSpan tilmidnight = date2 - now;

  _resetthread.Initialize( );
  _resetthread.AddTimer(
    (long) tilmidnight.GetTotalSeconds( ) * 1000,
    &_ResetThread,
    ( DWORD_PTR ) this,
    &_ResetThread._hTimer      // stored newly created timer handle
    );
  return true;
}
Esempio n. 10
0
void VirtualMeasurement::FinishMeasurement(COleDateTime odtMTime)
{

	_iMPMeasurementDateYear = odtMTime.GetYear();
	_iMPMeasurementDateMonth = odtMTime.GetMonth();
	_iMPMeasurementDateDay = odtMTime.GetDay();

	_fMPNChanA = (float)_dAve.val[NeutA];
	_fMPNChanB = (float)_dAve.val[NeutB];
	_fMPNChanC = (float)_dAve.val[NeutC];
	_fMPGDose1 = (float)_dAve.val[Gamma1];
	_fMPGDose2 = (float)_dAve.val[Gamma2];

	COleDateTimeSpan delta = odtMTime;
	delta -= delta.GetDays();

	_fMPNChanBThresh = (float)delta.GetTotalSeconds();

	CalcCoolingTime();
	ApplyAdjustments();
	//SetDetectorID();

	Certify();
}
Esempio n. 11
0
void CRecordingManagerWnd::OnTimer(UINT nIDEvent) 
{
	ASSERT(m_pRM != NULL);
	if (CRecordingManager::TIMER_ID_RECORDING_TIMEOUT == nIDEvent)
	{
		if (!m_pRM->m_bRecording)
		{
			DebugTell(_T("CRecordingManagerWnd[%d]::OnTimer: Fallible timer TIMER_ID_RECORDING_TIMEOUT ticking when there is no recording. Tossing tick."),
				m_pRM->m_pRoomObj->m_pRoom->ID);
			CWnd::OnTimer(nIDEvent);
			return;
		}
		COleDateTimeSpan odts = COleDateTime::GetCurrentTime() - m_pRM->m_odtLastRecordingTimeoutCheck;
		m_pRM->m_odtLastRecordingTimeoutCheck = COleDateTime::GetCurrentTime();
		if (odts.GetTotalSeconds() >= 60) /* this will put a message in the log every minute */
		{
			DebugTell(_T("CRecordingManagerWnd[%d]::OnTimer: Recording has %d seconds before timing out."),
				m_pRM->m_pRoomObj->m_pRoom->ID,m_pRM->m_uiRemainingTimerTicks);
		}
		if (--m_pRM->m_uiRemainingTimerTicks <= 0)
		{
			DebugTell(_T("CRecordingManagerWnd[%d]::OnTimer: Recording timeout for non-activity."),m_pRM->m_pRoomObj->m_pRoom->ID);
			KillTimer(nIDEvent);

			m_pRM->m_bBusy = true;
			m_pRM->m_dwBusySwipeCount = 0;
			m_pRM->m_odtLastBusySetTime = COleDateTime::GetCurrentTime();
			if (m_pRM->m_pStateCurrentRecording->m_sStateName != "CStateRecording")
			{	// uh oh... this is in an unrecognized state...
				DebugTell(_T("CRecordingManagerWnd[%d]::OnTimer: System is in the wrong state (%s) -- forcing recording reset."),m_pRM->m_pRoomObj->m_pRoom->ID,
					m_pRM->m_pStateCurrentRecording->m_sStateName);
				m_pRM->m_bRecording = true;
			}
			// set the system to busy so that card swipes will be ignored until
			// the stop recording command is complete.
			m_pRM->QueueCommand(CSSM_MESSAGE_STATECHANGE,CStateBaseRecording::eStateStopping);
		}
		else if (m_pRM->m_uiRemainingTimerTicks <= 15)
		{
			m_pRM->ReportElapsedTime(true);	// display remaining time
		}
	}

	if (CRecordingManager::TIMER_ID_RECORDING_COMPLETE_SCREEN_RESET == nIDEvent)
	{
		KillTimer(CRecordingManager::TIMER_ID_RECORDING_COMPLETE_SCREEN_RESET);
		m_pRM->RecordingCompleteScreenReset();
	}
	
	if (CRecordingManager::TIMER_ID_RECORDING_DISPLAY_TIME == nIDEvent)
	{
		if (!m_pRM->m_bRecording)
		{
			DebugTell(_T("CRecordingManagerWnd[%d]::OnTimer: Fallible timer TIMER_ID_RECORDING_DISPLAY_TIME ticking when there is no recording. Tossing tick."),
				m_pRM->m_pRoomObj->m_pRoom->ID);
			CWnd::OnTimer(nIDEvent);
			return;
		}
		m_pRM->ReportElapsedTime();
	}
	
	if (CRecordingManager::TIMER_ID_IDLE_DISPLAY_TIME == nIDEvent)
	{
		m_pRM->ReportTime();
	}

	if (CRecordingManager::TIMER_ID_RECORDING_STARTUP_TIMEOUT == nIDEvent)
	{
		m_pRM->KillTimerAndMessages(CRecordingManager::TIMER_ID_RECORDING_STARTUP_TIMEOUT);
		m_pRM->AbortRecording();
	}

	CWnd::OnTimer(nIDEvent);
}
Esempio n. 12
0
void CChartAxis::CalculateTickIncrement()
{
	if (!m_bAutoTicks)
		return;

	if (m_MaxValue == m_MinValue)
	{
		m_iDTTickIntervalMult = 0;
		m_TickIncrement = 0;
		return;
	}

	int PixelSpace;
	if (m_bIsHorizontal)
	{
		if (m_AxisType == atDateTime)
			PixelSpace = 60;
		else
			PixelSpace = 30;
	}
	else
		PixelSpace = 20;

	int MaxTickNumber = (int)fabs((m_EndPos-m_StartPos)/PixelSpace * 1.0);

	//Calculate the appropriate TickSpace (1 tick every 30 pixel +/-)
	switch (m_AxisType)
	{
	case atLogarithmic:
	   m_TickIncrement = 10;
	   break;

	case atStandard:
		{
	   		//Temporary tick increment
    		double TickIncrement = (m_MaxValue-m_MinValue)/MaxTickNumber;
	    
    		// Calculate appropriate tickSpace (not rounded on 'strange values' but 
    		// on something like 1, 2 or 5*10^X  where X is optimalized for showing the most
    		// significant digits)
    		int Zeros = (int)floor(log10(TickIncrement));
    		double MinTickIncrement = pow(10.0,Zeros);
	    
    		int Digits = 0;
    		if (Zeros<0)		
    		{
				//We must set decimal places. In the other cases, Digits will be 0.
    			Digits = (int)fabs(Zeros*1.0);
    		}
	    
    		if (MinTickIncrement>=TickIncrement)
    		{
    			m_TickIncrement = MinTickIncrement;
    			SetDecimals(Digits);
    		}
    		else if (MinTickIncrement*2>=TickIncrement)
    		{
    			m_TickIncrement = MinTickIncrement*2;
    			SetDecimals(Digits);
    		}
    		else if (MinTickIncrement*5>=TickIncrement)
    		{
    			m_TickIncrement = MinTickIncrement*5;
    			SetDecimals(Digits);
    		}
    		else if (MinTickIncrement*10>=TickIncrement)
    		{
    			m_TickIncrement = MinTickIncrement*10;
    			if (Digits)
    				SetDecimals(Digits-1);
    			else
    				SetDecimals(Digits);
    		}
		}
		break;

	case atDateTime:
		{
			COleDateTime StartDate(m_MinValue);
			COleDateTime EndDate(m_MaxValue);

			COleDateTimeSpan minTickInterval = (EndDate - StartDate)/MaxTickNumber;
			double Seconds = minTickInterval.GetTotalSeconds();
			double Minutes = minTickInterval.GetTotalMinutes();
			double Hours = minTickInterval.GetTotalHours();
			double Days = minTickInterval.GetTotalDays();
			if (Seconds < 60)
			{
				m_BaseInterval = tiSecond;
				if (Seconds > 30)
				{
					m_BaseInterval = tiMinute;
					m_iDTTickIntervalMult = 1;
				}
				else if (Seconds > 10)
					m_iDTTickIntervalMult = 30;
				else if (Seconds > 5)
					m_iDTTickIntervalMult = 10;
				else if (Seconds > 2)
					m_iDTTickIntervalMult = 5;
				else 
					m_iDTTickIntervalMult = 1;
			}
			else if (Minutes < 60)
			{
				m_BaseInterval = tiMinute;
				if (Minutes > 30)
				{
					m_BaseInterval = tiHour;
					m_iDTTickIntervalMult = 1;
				}
				else if (Minutes > 10)
					m_iDTTickIntervalMult = 30;
				else if (Minutes > 5)
					m_iDTTickIntervalMult = 10;
				else if (Minutes > 2)
					m_iDTTickIntervalMult = 5;
				else 
					m_iDTTickIntervalMult = 2;
			}
			else if (Hours < 24)
			{
				m_BaseInterval = tiHour;
				if (Hours > 12)
				{
					m_BaseInterval = tiDay;
					m_iDTTickIntervalMult = 1;
				}
				else if (Hours > 6)
					m_iDTTickIntervalMult = 12;
				else if (Hours > 2)
					m_iDTTickIntervalMult = 6;
				else 
					m_iDTTickIntervalMult = 2;
			}
			else if (Days < 31)
			{
				m_BaseInterval = tiDay;
				if (Days > 7)
				{
					m_BaseInterval = tiMonth;
					m_iDTTickIntervalMult = 1;
				}
				else if (Days > 2)
				{
					m_BaseInterval = tiDay;
					m_iDTTickIntervalMult = 7;
				}
				else 
					m_iDTTickIntervalMult = 2;
			}
			else if (Days < 365)
			{
				m_BaseInterval = tiMonth;
				if (Days > 186)	 // Approx 6 months
				{
					m_BaseInterval = tiYear;
					m_iDTTickIntervalMult = 1;
				}
				else if (Days > 124)
					m_iDTTickIntervalMult = 6;
				else if (Days > 62)
					m_iDTTickIntervalMult = 4;
				else
					m_iDTTickIntervalMult = 2;
			}
			else
			{
				m_BaseInterval = tiYear;
				m_iDTTickIntervalMult = (int)Days/365 + 1;
			}

			if (m_bAutoTickFormat)
				RefreshDTTickFormat();
		}
		break;
	}
}
Esempio n. 13
0
UINT CActiveMember::GetLocalExpense(BOOL bFilter)
{
	if (PolicyInfo.IsEmpty())
	{
		return GetAmount();
	}
	if (PolicyInfo.GetLength() != 24*4)
	{
		IBA_ASSERT2(FALSE, "warning:扣率信息有误");
		CIBALog::GetInstance()->WriteFormat(_T("本地用户扣率信息有误,netId=%s, 扣率=%s"), NetId, PolicyInfo);
		return GetAmount();
	}
	if (CheckInTime.GetStatus() != COleDateTime::valid || CheckInTime == 0)
	{
		return GetAmount();
	}
	COleDateTime timeNow = COleDateTime::GetCurrentTime();
	COleDateTimeSpan timeSpan = timeNow - CheckInTime;

	UINT nPolicyHours[24] = {0};
	for (int i = 0; i < 96; i+=4)
	{
		nPolicyHours[i/4] = (UINT)_ttoi(PolicyInfo.Mid(i, 4));
	}

	double dExp = 0.0;
	int iStartHour = CheckInTime.GetHour();
	int iStartSecond = CheckInTime.GetSecond()+ CheckInTime.GetMinute()*60;
	int nTotalSecond = (int)timeSpan.GetTotalSeconds();
	for(int iSecond = nTotalSecond; iSecond > 0; )
	{
		if (nPolicyHours[iStartHour] == 0)
		{
			IBA_ASSERT2(FALSE,"warning:扣率信息有误,扣率为0");
			CIBALog::GetInstance()->WriteFormat(_T("本地用户扣率信息有误,netId=%s, 扣率=%s"), NetId, PolicyInfo);
			return GetAmount();
		}
		double dSecondPolicy = nPolicyHours[iStartHour%24] / 3600.0;

		int nSeconds = 3600 - iStartSecond;
		if (nSeconds >= iSecond)
		{
			nSeconds = iSecond;
		}
		
		dExp += dSecondPolicy * nSeconds;
		iSecond -= nSeconds;
		iStartHour ++;
		iStartSecond = 0; // 第一次循环以后,起始秒都为0
	}

	if (bFilter)
	{
		UINT nExp = UINT(dExp+49)/50*50;
		return nExp;
	}
	else
	{
		return UINT(dExp);
	}
	
}
Esempio n. 14
0
int LandSimulation(int landfg,char* strInputFilePath,CProgressWnd* pwndProgress)
{
	CString ReportFilePath(strInputFilePath);
	ReportFilePath.TrimRight("inp");
	CString OutputFilePath = ReportFilePath;
	ReportFilePath += "rpt";
	OutputFilePath += "out";
	char* strReportFilePath = ReportFilePath.GetBuffer(ReportFilePath.GetLength());
	char* strOutputFilePath = OutputFilePath.GetBuffer(OutputFilePath.GetLength());
	
	// initialize progress bar
	pwndProgress->SetRange(0, 100);			 
	pwndProgress->SetText("");
	CString strMsg, strForDdg, strE;

	COleDateTime time_i;		// time at the beginning of the simulation
	COleDateTime time_f;		// time at the end of the simulation
	COleDateTimeSpan time_dif;	// simulation run time
	SYSTEMTIME tm;				// system time
	GetLocalTime(&tm);
	time_i = COleDateTime(tm);

	long newHour, oldHour = 0;
	DateTime elapsedTime = 0.0;

	// --- open the files & read input data
	ErrorCode = 0;
	swmm_open(strInputFilePath,strReportFilePath,strOutputFilePath);

	// --- run the simulation if input data OK
	if ( !ErrorCode )
	{
		// --- initialize values
		swmm_start(TRUE);

		// --- execute each time step until elapsed time is re-set to 0
		if ( !ErrorCode )
		{
			int y, m, d;
			datetime_decodeDate(StartDateTime, &y, &m, &d);
			COleDateTime tStart(y,m,d,0,0,0);
			datetime_decodeDate(EndDateTime, &y, &m, &d);
			COleDateTime tEnd(y,m,d,0,0,0);
			COleDateTimeSpan span0 = tEnd - tStart;

			do
			{
				swmm_step(&elapsedTime);
				newHour = elapsedTime * 24.0;

				COleDateTimeSpan span = COleDateTimeSpan(0,newHour,0,0);
				COleDateTime tCurrent = tStart + span;

				int nSYear = tCurrent.GetYear();
				int nSMonth = tCurrent.GetMonth();
				int nSDay = tCurrent.GetDay();
				int nSHour = tCurrent.GetHour();

				GetLocalTime(&tm);
				time_f = COleDateTime(tm);
				time_dif = time_f - time_i;

				int dd_elap = int(time_dif.GetDays());
				int hh_elap = int(time_dif.GetHours());
				int mm_elap = int(time_dif.GetMinutes());
				int ss_elap = int(time_dif.GetSeconds());

				if ( newHour > oldHour )
				{
					oldHour = newHour;

					if (landfg == 0)
						strMsg.Format("Land Simulation:\t Pre-Development Scenario\n");
					else
						strMsg.Format("Land Simulation:\t Post-Development Scenario\n");
					strForDdg = strMsg;

					strMsg.Format("Calculating:\t %02d-%02d-%04d\n", nSMonth, nSDay, nSYear);
					strForDdg += strMsg;
					
					strE.Format("\nTime Elapsed:\t %02d:%02d:%02d:%02d\n", dd_elap, hh_elap, mm_elap, ss_elap);
					strForDdg += strE;

					double lfPart = span.GetTotalSeconds();
					double lfAll  = span0.GetTotalSeconds();
					double lfPerc = lfPart/lfAll;

					if(pwndProgress->GetSafeHwnd() != NULL && nSHour == 0)
					{
						pwndProgress->SetText(strForDdg);
						pwndProgress->SetPos((int)(lfPerc*100));
						pwndProgress->PeekAndPump();
					}

					if (pwndProgress->Cancelled())
					{
						pwndProgress->DestroyWindow();
						AfxMessageBox("BMP simulation is cancelled");
						break;
					}
				}
			} while ( elapsedTime > 0.0 && !ErrorCode );
		}

		// --- clean up
		swmm_end();
	}

	// --- report results
	swmm_report();

	// --- close the system
	swmm_close();

	//return ErrorCode;
	return ErrorCode;
}
Esempio n. 15
0
void CVideoPlayBack::AddToListEnglish()
{
	int j = m_iBeginNode;

	
	for(int i = 0; i< (int)m_storeLog.node_count; i++)
	{
		CString strId(_T(""));
		strId.Format(_T("%d"),j+1);

		CString strType = _T("");
		if(m_SerachRecodeByType == ALL_RECODE)
		{
			if(m_storeLog.store[i].rec_type & TIMER_RECODE)
			{
				strType += _T(",TIMER_RECODE");
			}
			if(m_storeLog.store[i].rec_type & ALARM_RECODE)
			{
				strType += _T(",ALARM_RECODE");
			}
			if(m_storeLog.store[i].rec_type & MOVE_RECODE)
			{
				strType += _T(",MOVE_RECODE");
			}
			if(m_storeLog.store[i].rec_type & MANUAL_RECODE)
			{
				strType += _T(",MANUAL_RECODE");
			}
			if(m_storeLog.store[i].rec_type & LOST_RECODE)
			{
				strType += _T(",LOST_RECODE");
			}
			if(m_storeLog.store[i].rec_type & HIDE_RECODE)
			{
				strType += _T(",HIDE_RECODE");
			}
			if(m_storeLog.store[i].rec_type & NET_FAULT_RECODE)
			{
				strType += _T(",NET_FAULT_RECODE");
			}
			if(m_storeLog.store[i].rec_type & PIR_RECODE)
			{
				strType += _T(",PIR_RECODE");
			}
			strType = strType.Right(strType.GetLength() - 1 );
		}
		else
		{
			if(m_storeLog.store[i].rec_type & TIMER_RECODE)
			{
				strType = _T("TIMER_RECODE");
			}
			if(m_storeLog.store[i].rec_type & ALARM_RECODE)
			{
				strType = _T("ALARM_RECODE");
			}
			if(m_storeLog.store[i].rec_type & MOVE_RECODE)
			{
				strType = _T("MOVE_RECODE");
			}
			if(m_storeLog.store[i].rec_type & MANUAL_RECODE)
			{
				strType = _T("MANUAL_RECODE");
			}
			if(m_storeLog.store[i].rec_type & LOST_RECODE)
			{
				strType = _T("LOST_RECODE");
			}
			if(m_storeLog.store[i].rec_type & HIDE_RECODE)
			{
				strType = _T("HIDE_RECODE");
			}
			if(m_storeLog.store[i].rec_type & NET_FAULT_RECODE)
			{
				strType = _T("NET_FAULT_RECODE");
			}
			if(m_storeLog.store[i].rec_type & PIR_RECODE)
			{
				strType += _T("PIR_RECODE");
			}
		}
	
	


		CString strStartTime = _T("");
		CString strEndTime =_T("");
		CString StartTime = _T("");
		CString EndTime = _T("");

		strStartTime.Format(_T("%d-%02d-%02d-%02d:%02d:%02d"),m_storeLog.store[i].beg_time.year+1900,m_storeLog.store[i].beg_time.month,
			m_storeLog.store[i].beg_time.date, m_storeLog.store[i].beg_time.hour ,
			m_storeLog.store[i].beg_time.minute, m_storeLog.store[i].beg_time.second);

		strEndTime.Format(_T("%d-%02d-%02d-%02d:%02d:%02d"),m_storeLog.store[i].end_time.year+1900,m_storeLog.store[i].end_time.month,
			m_storeLog.store[i].end_time.date, m_storeLog.store[i].end_time.hour ,
			m_storeLog.store[i].end_time.minute, m_storeLog.store[i].end_time.second);
		//计算时间段的差
		COleDateTime  tStartDateTime;
		COleDateTime  tEndDateTime;
		tStartDateTime.SetDateTime(m_storeLog.store[i].beg_time.year+1900,m_storeLog.store[i].beg_time.month,
			m_storeLog.store[i].beg_time.date, m_storeLog.store[i].beg_time.hour ,
			m_storeLog.store[i].beg_time.minute, m_storeLog.store[i].beg_time.second);
		tEndDateTime.SetDateTime(m_storeLog.store[i].end_time.year+1900,m_storeLog.store[i].end_time.month,
			m_storeLog.store[i].end_time.date, m_storeLog.store[i].end_time.hour ,
			m_storeLog.store[i].end_time.minute, m_storeLog.store[i].end_time.second);


		m_lRecFileSize[j] = m_storeLog.store[i].file_size;  //保存录像文件的大小  下载时计算进度


		COleDateTimeSpan tMinute = tEndDateTime - tStartDateTime;  // 计算两个日期时间的差值
		DOUBLE dMinute = tMinute.GetTotalSeconds();
		CString strFileTimes = _T("");
		strFileTimes.Format(_T("%ld"), (LONG)dMinute);

		CString strFileSize = _T("");//录像大小
		strFileSize.Format(_T("%d"), m_storeLog.store[i].file_size/(1024*1024));

		m_VideoPlayBack.InsertItem(j,strId );
		m_VideoPlayBack.SetItemText(j, 1, strType);
		m_VideoPlayBack.SetItemText(j, 2, strStartTime);
		m_VideoPlayBack.SetItemText(j, 3, strEndTime);
		m_VideoPlayBack.SetItemText(j, 4, strFileTimes);
		m_VideoPlayBack.SetItemText(j, 5, strFileSize);
		j++;
	}
	}
// Start the server. This blocks until the server stops.
void AgentConfigurationEx::start()
{


	if (Globals._bResetAtMidnight)
	{
		COleDateTime now = COleDateTime::GetCurrentTime();
		COleDateTimeSpan tilnextreset = COleDateTimeSpan(0, 1, 0, 0);;
#if 0
		COleDateTime today = COleDateTime(now.GetYear(), now.GetMonth(), now.GetDay(), 0, 0, 0);
		COleDateTime tomorrow = COleDateTime(now.GetYear(), now.GetMonth(), now.GetDay() + 1, 0, 0, 0);
		//COleDateTime date2 =  COleDateTime(now.GetYear(), now.GetMonth(), now.GetDay(), 0, 0, 0)
		//	+  COleDateTimeSpan(1, 0, 0, 1);
		//COleDateTimeSpan tilmidnight = date2-now;
		//	COleDateTimeSpan tilmidnight = date2-now;
		//COleDateTime date2 =  now +  COleDateTimeSpan(0, 0, 2, 0); // testing reset time - 2 minutes
		COleDateTimeSpan dt3 = COleDateTimeSpan(1, 0, 0, 1);
		COleDateTimeSpan dt4 = dt3; //(0, 0, _shiftchanges[1], 1);
		COleDateTimeSpan dt5 = dt3; // (0, 0, _shiftchanges[2], 1);
		COleDateTimeSpan dt6 = dt3; // (0, 0, _shiftchanges[2], 1);


		if (_shiftchanges.size() < 1)
			dt3 = COleDateTimeSpan(1, 0, 0, 1);
		if (_shiftchanges.size() >= 1)
			dt3 = COleDateTimeSpan(0, 0, _shiftchanges[0], 0);
		if (_shiftchanges.size() >= 2)
			dt4 = COleDateTimeSpan(0, 0, _shiftchanges[1], 0);
		if (_shiftchanges.size() >= 3)
			dt5 = COleDateTimeSpan(0, 0, _shiftchanges[2], 0);

		COleDateTime date3 = today + dt3;
		COleDateTime date4 = today + dt4;
		COleDateTime date5 = today + dt5;
		COleDateTime date6 = tomorrow + dt3;

		COleDateTimeSpan tilnextreset = date6;

		if (date6 > now)
			tilnextreset = date6 - now;
		if (date5 > now)
			tilnextreset = date5 - now;
		if (date4 > now)
			tilnextreset = date4 - now;
		if (date3 > now)
			tilnextreset = date3 - now;
#endif
		GLogger.Fatal(StrFormat("Agent will Reset from now  %8.4f\n", (tilnextreset.GetTotalSeconds() / 3600.00)));

		_resetthread.Initialize();

		// Call this method to add a periodic waitable timer to the list maintained by the worker thread.
		// Parameters
		/*	dwInterval	Specifies the period of the timer in milliseconds.
		pClient	The pointer to the IWorkerThreadClient interface on the object to be called when the handle is signaled.
		dwParam	The parameter to be passed to IWorkerThreadClient::Execute when the handle is signaled.
		phTimer	[out] Address of the HANDLE variable that, on success, receives the handle to the newly created timer.
		Return Value Returns S_OK on success, or an error HRESULT on failure.
		*/

		_resetthread.AddTimer(
			(long)tilnextreset.GetTotalSeconds() * 1000,
			&_ResetThread,
			(DWORD_PTR) this,
			&_ResetThread._hTimer  // stored newly created timer handle
		);

	}
	CCmdHandler * _cmdHandler;

	for (int i = 0; i < Globals.fanucips.size(); i++)
	{
		_cmdHandler = new CCmdHandler(this);
		_cmdHandlers.push_back(_cmdHandler);
		_cmdHandler->Configure(config, "FanucCNC" + ConvertToString(i + 1), Globals.fanucips[i], ConvertToString(Globals.FanucPort));
		//		_group.create_thread(std::bind(&CCmdHandler::Cycle, _cmdHandler));
		_group.emplace_back(std::thread(std::bind(&CCmdHandler::Cycle, _cmdHandler)));
	}
	AgentConfiguration::start();
}
Esempio n. 17
0
double CChartDateTimeAxis::GetTickBeforeVal(double dValue) const
{
	double precision = 0.0000000001;
	if (dValue < 0)
		precision = -0.0000000001;

	COleDateTime tickBefore;
	COleDateTime valueTime = COleDateTime(DATE(dValue+precision));
	COleDateTimeSpan dtSpan = valueTime - m_ReferenceTick;
	switch (m_BaseInterval)
	{
	case tiSecond:
		{
			int totalSecs = (int)dtSpan.GetTotalSeconds();
			totalSecs = (totalSecs/m_iDTTickIntervalMult) * m_iDTTickIntervalMult;
			int Days = totalSecs/86400;					// 86400 seconds in one day
			int Hours = (totalSecs%86400)/3600;			// 3600 seconds in one hour
			int Minutes = ((totalSecs%86400)%3600)/60;	// 60 seconds in one minute
			int Seconds = ((totalSecs%86400)%3600)%60;
			dtSpan.SetDateTimeSpan(Days, Hours, Minutes, Seconds);
			tickBefore = m_ReferenceTick + dtSpan;
		}
		break;
	case tiMinute:
		{
			int totalMinutes = (int)dtSpan.GetTotalMinutes();
			totalMinutes = (totalMinutes/m_iDTTickIntervalMult) * m_iDTTickIntervalMult;
			int Days = totalMinutes/1440;			// 1440 minutes in one day
			int Hours = (totalMinutes%1440)/60;		// 60 minutes in one hour
			int Minutes = (totalMinutes%1440)%60;
			dtSpan.SetDateTimeSpan(Days, Hours, Minutes, 0);
			tickBefore = m_ReferenceTick + dtSpan;
		}
		break;
	case tiHour:
		{
			int totalHours = (int)dtSpan.GetTotalHours();
			totalHours = (totalHours/m_iDTTickIntervalMult) * m_iDTTickIntervalMult;
			int Days = totalHours/24;			// 24 hours in one day
			int Hours = totalHours%24;
			dtSpan.SetDateTimeSpan(Days, Hours, 0, 0);
			tickBefore = m_ReferenceTick + dtSpan;
		}
		break;
	case tiDay:
		{
			int totalDays = (int)dtSpan.GetTotalDays();
			totalDays = (totalDays/m_iDTTickIntervalMult) * m_iDTTickIntervalMult;
			dtSpan.SetDateTimeSpan(totalDays, 0, 0, 0);
			tickBefore = m_ReferenceTick + dtSpan;
		}
		break;
	case tiMonth:
		{
			int yearDiff = valueTime.GetYear() - m_ReferenceTick.GetYear();
			int monthDiff = valueTime.GetMonth() - m_ReferenceTick.GetMonth();
			int totalMonths = ((yearDiff*12+monthDiff)/m_iDTTickIntervalMult) * m_iDTTickIntervalMult;
			tickBefore = AddMonthToDate(m_ReferenceTick,totalMonths);
		}
		break;
	case tiYear:
		{
			int yearDiff = valueTime.GetYear() - m_ReferenceTick.GetYear();
			int year = ((yearDiff)/m_iDTTickIntervalMult) * m_iDTTickIntervalMult;
			tickBefore = AddMonthToDate(m_ReferenceTick,year*12);
		}
		break;
	}

	return (DATE)tickBefore;
}
Esempio n. 18
0
void CChartDateTimeAxis::RefreshTickIncrement()
{
	if (!m_bAutoTicks)
		return;

	if (m_MaxValue == m_MinValue)
	{
		m_iDTTickIntervalMult = 1;
		return;
	}

	int PixelSpace;
	if (m_bIsHorizontal)
		PixelSpace = 60;
	else
		PixelSpace = 20;

	int MaxTickNumber = (int)fabs((m_EndPos-m_StartPos)/PixelSpace * 1.0);
	if (MaxTickNumber == 0)
		MaxTickNumber = 1;

	COleDateTime StartDate(m_MinValue);
	COleDateTime EndDate(m_MaxValue);

	COleDateTimeSpan minTickInterval = (EndDate - StartDate)/MaxTickNumber;
	double Seconds = minTickInterval.GetTotalSeconds();
	double Minutes = minTickInterval.GetTotalMinutes();
	double Hours = minTickInterval.GetTotalHours();
	double Days = minTickInterval.GetTotalDays();
	if (Seconds < 60)
	{
		m_BaseInterval = tiSecond;
		if (Seconds > 30)
		{
			m_BaseInterval = tiMinute;
			m_iDTTickIntervalMult = 1;
		}
		else if (Seconds > 10)
			m_iDTTickIntervalMult = 30;
		else if (Seconds > 5)
			m_iDTTickIntervalMult = 10;
		else if (Seconds > 2)
			m_iDTTickIntervalMult = 5;
		else
			m_iDTTickIntervalMult = 1;
	}
	else if (Minutes < 60)
	{
		m_BaseInterval = tiMinute;
		if (Minutes > 30)
		{
			m_BaseInterval = tiHour;
			m_iDTTickIntervalMult = 1;
		}
		else if (Minutes > 10)
			m_iDTTickIntervalMult = 30;
		else if (Minutes > 5)
			m_iDTTickIntervalMult = 10;
		else if (Minutes > 2)
			m_iDTTickIntervalMult = 5;
		else
			m_iDTTickIntervalMult = 2;
	}
	else if (Hours < 24)
	{
		m_BaseInterval = tiHour;
		if (Hours > 12)
		{
			m_BaseInterval = tiDay;
			m_iDTTickIntervalMult = 1;
		}
		else if (Hours > 6)
			m_iDTTickIntervalMult = 12;
		else if (Hours > 2)
			m_iDTTickIntervalMult = 6;
		else
			m_iDTTickIntervalMult = 2;
	}
	else if (Days < 31)
	{
		m_BaseInterval = tiDay;
		if (Days > 7)
		{
			m_BaseInterval = tiMonth;
			m_iDTTickIntervalMult = 1;
		}
		else if (Days > 2)
		{
			m_BaseInterval = tiDay;
			m_iDTTickIntervalMult = 7;
		}
		else
			m_iDTTickIntervalMult = 2;
	}
	else if (Days < 365)
	{
		m_BaseInterval = tiMonth;
		if (Days > 186)	 // Approx 6 months
		{
			m_BaseInterval = tiYear;
			m_iDTTickIntervalMult = 1;
		}
		else if (Days > 124)
			m_iDTTickIntervalMult = 6;
		else if (Days > 62)
			m_iDTTickIntervalMult = 4;
		else
			m_iDTTickIntervalMult = 2;
	}
	else
	{
		m_BaseInterval = tiYear;
		m_iDTTickIntervalMult = (int)Days/365 + 1;
	}
}
   COleDateTime t1(1999, 3, 19, 22, 15, 0); // 10:15PM March 19, 1999
   COleDateTime t2(1999, 3, 20, 22, 15, 0); // 10:15PM March 20, 1999

   // Subtract 2 COleDateTimes
   COleDateTimeSpan ts = t2 - t1;

   // one day is 24 * 60 * 60 == 86400 seconds
   ASSERT(ts.GetTotalSeconds() == 86400L);

   // Add a COleDateTimeSpan to a COleDateTime.
   ASSERT((t1 + ts) == t2);

   // Subtract a COleDateTimeSpan from a COleDateTime.
   ASSERT((t2 - ts) == t1);   
Esempio n. 20
0
BOOL CWebGrab::GetFile(LPCTSTR szURL, CString& strBuffer, 
                       LPCTSTR szAgentName /*=NULL*/, CWnd* pWnd /*=NULL*/)
{
	CString strBuffer2;

  //  TRACE1("URL is %s\n", szURL);
	m_rawHeaders ="";
	m_infoStatusCode=0;
	strBuffer.Empty();

    if (!m_pSession && !Initialise(szAgentName, pWnd))
        return FALSE;

    if (pWnd)
        m_pSession->SetStatusWnd(pWnd);

    //m_pSession->SetStatus("Downloading file...");

    DWORD dwCount = 0;
    CHttpFile* pFile = NULL;
    try
    {
        pFile = (CHttpFile*) m_pSession->OpenURL(szURL, 1,
                                                 INTERNET_FLAG_TRANSFER_BINARY 
                                                 //| INTERNET_OPEN_FLAG_USE_EXISTING_CONNECT |
                                                 | INTERNET_FLAG_DONT_CACHE
                                                 //| INTERNET_FLAG_RELOAD
                                                 );
	}
    catch (CInternetException* e)
    {
        TCHAR   szCause[255];
        e->GetErrorMessage(szCause, 255);
        m_pSession->SetStatus(szCause);
        // e->ReportError();
        e->Delete();
        delete pFile;
        pFile = NULL;
        return FALSE;
    }
    
    COleDateTime startTime = COleDateTime::GetCurrentTime();
    LPSTR pBuf = NULL;
    if (pFile)
    {
        pBuf = (LPSTR) ::GlobalAlloc(GMEM_FIXED, BUFFER_SIZE+1);
        if (!pBuf)
        {
            pFile->Close();
            delete pFile;
            return FALSE;
        }

        BYTE buffer[BUFFER_SIZE+1];
        try {
            UINT nRead = 0;
            dwCount = 0;
            do
            {
                nRead = pFile->Read(buffer, BUFFER_SIZE);
                if (nRead > 0)
                {
                    buffer[nRead] = 0;

					// JT origional code works in sample but produces Gibber here...
                    //LPTSTR ptr = strBuffer.GetBufferSetLength(dwCount + nRead + 1);
                    //memcpy(ptr+dwCount, buffer, nRead);
                    dwCount += nRead;
                    //strBuffer.ReleaseBuffer(dwCount+1);

					// My alternate
					CString str( (LPCSTR) &buffer, sizeof(buffer) );  // Convert byte array to CString
					strBuffer.Append(str);	// append CString.

                    COleDateTimeSpan elapsed = COleDateTime::GetCurrentTime() - startTime;
                    double dSecs = elapsed.GetTotalSeconds();
                    if (dSecs > 0.0)
					{
                        m_transferRate = (double)dwCount / 1024.0 / dSecs;
						//m_pSession->SetStatus("Read %d bytes (%0.1f Kb/s)", 
                        //                     dwCount, m_transferRate );
						
					}
					else
					{
                        //m_pSession->SetStatus("Read %d bytes", dwCount);
						m_transferRate = dwCount;
					}
                }
            }
            while (nRead > 0);
        }
        catch (CFileException *e)
        {
            TCHAR   szCause[255];
            e->GetErrorMessage(szCause, 255);
			m_ErrorMessage = szCause;
            m_pSession->SetStatus(szCause);
            //e->ReportError();
            e->Delete();
            delete pFile;
            ::GlobalFree(pBuf);	// mem leak fix by Niek Albers 
            return FALSE;
        }
        pFile->QueryInfoStatusCode(m_infoStatusCode);       
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS ,m_rawHeaders);
        pFile->Close();
	  ::GlobalFree(pBuf);	// mem leak fix by Niek Albers 
        delete pFile;
    }

    //m_pSession->SetStatus("");

    return TRUE;
}
Esempio n. 21
0
void
CEOSSPropertySheet::WriteToFile(int ToWhom, int Type, CJulianTime* Time, char* Msg)
{
	FILE *File;
	char Message[256];
	fpos_t position;
	Message[0] = NULL;
	COleDateTime TC = COleDateTime::GetCurrentTime();
	COleDateTime TG;
	COleDateTimeSpan TS;
	CString ArchiveFileName;

//	if (m_pParent->m_bBlockWrite) 
//		return;

	//default to the provided EOSS time
	if (Time)
	{
		int Year,Month,Day,Hour,Minute,Second;
		Year = Time->Year();
		Month = Time->Month();
		Day = Time->Day();
		Hour = Time->Hour();
		Minute = Time->Minute();
		Second = Time->Second();
		if (Year	< 100)  Year	= 1900;//COleDateTime limits year 100-9999
		if (Year    > 9999) Year    = 9999;//COleDateTime limits year 100-9999
		if (Month	< 1)	Month	= 1;
		if (Day		< 1)	Day		= 1;
		if (Hour	< 0)	Hour	= 0;
		if (Minute	< 0)	Minute	= 0;
		if (Second	< 0)	Second	= 0;
		TG = COleDateTime(Year, Month, Day, Hour, Minute, Second);
	}
	//if that wasn't available then get the computer time
	//this is the case in all TYPE_COMP messages
	else
	{
		TG = COleDateTime::GetCurrentTime();
	}

	if (ToWhom == TO_DMP)
	{
		//	build new file name and save it
		if (m_pParent->m_bUseShortFilename)
		{
			char cYear;
			int iYear = TC.GetYear();
			if ((iYear < 1990) || (iYear > 2025))
				cYear = '#';
			else if (iYear < 2000)
				cYear = (char)('0' + iYear - 1990);
			else 
				cYear = (char)('A' + iYear - 2000);

			sprintf(m_szCurrentFileName,"%s\\%s%c%c%c%c%02d.",
				m_pParent->m_szSaveLoc,	
				m_pParent->m_pID,
	//			((TC.GetYear()-1990)<10)?
	//				((TC.GetYear()-1990<0)?'#':'0'+(TC.GetYear()-1990)):
	//				'A'+(TC.GetYear()-2000),
				cYear,
				((TC.GetMonth()<10)?
					'0'+(TC.GetMonth()):
					'A'+(TC.GetMonth()-10)),
				((TC.GetDay()  <10)?
					'0'+(TC.GetDay()):
					'A'+(TC.GetDay()  -10)),
				'A',0);
		}
		else
		{
			CString cResult;
			BuildFileName(cResult,
				m_pParent->m_csLongNameFormatString,
				m_pParent->m_szSaveLoc,"EO",
				m_pParent->m_pID,TC.GetYear(),TC.GetMonth(),TC.GetDay(),0,0,0,"",".");
			strcpy(m_szCurrentFileName,cResult);
		}
	}
	else
	{
		if (m_pParent->m_bUseShortFilename)
		{
			//	build new file name and save it
			char cYear;
			int iYear = TG.GetYear();
			if ((iYear < 1990) || (iYear > 2025))
				cYear = '#';
			else if (iYear < 2000)
				cYear = (char)('0' + iYear - 1990);
			else 
				cYear = (char)('A' + iYear - 2000);

			sprintf(m_szCurrentFileName,"%s\\%s%c%c%c%c%02d.",
				((CEOSSInstrument*)m_pParent)->m_szSaveLoc,	
				((CEOSSInstrument*)m_pParent)->m_pID,
				cYear,
				((TG.GetMonth()<10)?
					'0'+(TG.GetMonth()):
					'A'+(TG.GetMonth()-10)),
				((TG.GetDay()  <10)?
					'0'+(TG.GetDay()):
					'A'+(TG.GetDay()  -10)),
				'A',0);
		}
		else
		{
			CString cResult;
			BuildFileName(cResult,
				m_pParent->m_csLongNameFormatString,
				m_pParent->m_szSaveLoc,"EO",
				m_pParent->m_pID,TG.GetYear(),TG.GetMonth(),TG.GetDay(),0,0,0,"",".");
			strcpy(m_szCurrentFileName,cResult);
		}

	}	

	//format string to send
	switch (Type){

	case TYPE_DUMP:
		sprintf(Message,"%4d.%02d.%02d %02d:%02d:%02d %s\n",
			TC.GetYear(),TC.GetMonth(),TC.GetDay(),
			TC.GetHour(),TC.GetMinute(),TC.GetSecond(),
			Msg);
//		strcpy(Message,Msg);
		break;

	case TYPE_INST:
		//	message = Time::YY.MM.DD HH:MM:SS G (MESSAGE==NULL)?\r:MESSAGE

		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d E %s\n",
			TG.GetYear(),
			TG.GetMonth(),	TG.GetDay(),
			TG.GetHour(),	TG.GetMinute(),	TG.GetSecond(),
			Msg[0]==NULL?"":Msg);
		break;

	case TYPE_COMP:
		//	message = MICTIME::YY.MM.DD HH:MM:SS C (MESSAGE==NULL)?\r:MESSAGE
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C %s\n",
			TC.GetYear(),
			TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),TC.GetMinute(),TC.GetSecond(),Msg[0]==NULL?"":Msg);
		break;

	case TYPE_GID2:
	case TYPE_TIME:
		//	message = Time::YY.MM.DD HH:MM:SS EOSS Time   "+
		//					"YY.MM.DD HH:MM:SS Computer Time   C - E = xxxx\r"
		//computer time
		//EOSS time
		TS = TC - TG;  // Subtract 2 COleDateTimes
		TS += HALF_SECOND;
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d E 47326 EOSS Time %04d.%02d.%02d %02d:%02d:%02d Computer Time   C - E = %.0f seconds\n",
			TG.GetYear(),	TG.GetMonth(),	TG.GetDay(),
			TG.GetHour(),	TG.GetMinute(),	TG.GetSecond(),
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			TS.GetTotalSeconds());
		break;

	case TYPE_INVTIME:
		//	message = "INVALID TIME  "+
		//		"Previous Record Time Saved::YY.MM.DD HH:MM:SS "+
		//		"Current Record Time Time::YY.MM.DD HH:MM:SS\r"
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d I 47327 EOSS INVALID TIME %04d.%02d.%02d %02d:%02d:%02d\n",
			((CJulianTime*)Msg)->Year(),	((CJulianTime*)Msg)->Month(),	((CJulianTime*)Msg)->Day(),
			((CJulianTime*)Msg)->Hour(),		((CJulianTime*)Msg)->Minute(),	((CJulianTime*)Msg)->Second(),
			TG.GetYear(),	TG.GetMonth(),	TG.GetDay(),
			TG.GetHour(),	TG.GetMinute(),	TG.GetSecond());
		break;

	case TYPE_START:
	//  message = MICTIME::YY.MM.DD HH:MM:SS C EOSS COLLECT Version %s<VERSION> started\r"
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C 47411 EOSS COLLECT Version %s started\n",
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			m_pParent->m_csVersion);
		break;

	case TYPE_ABNORMAL:
	//  message = MICTIME::YY.MM.DD HH:MM:SS C EOSS COLLECT Version %s<VERSION> started\r"
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C 47412 EOSS COLLECT Version %s started from abnormal shutdown\n",
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			m_pParent->m_csVersion);
		break;

	case TYPE_DELETE:
	//	message = MICNOW::YY.MM.DD HH:MM:SS C file %s<MESSAGE> deleted\r"
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C 47413 EOSS File %s deleted\n",
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			Msg);
		break;

	//just in case
	default:
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C 47328 EOSS Unknown TYPE %s\n",
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			Msg);
	}

	//if to dmp do the write to todays file and get out
	if (ToWhom == TO_DMP)
	{
		//	open filename+dmp
		CString fn(m_szCurrentFileName);
		fn += DMP_SUFFIX;
//		CString ArchiveFileNameEx = ArchiveFileName + DMP_SUFFIX;
		if (_access(fn,0) != 0)
		{
//			if (_access(ArchiveFileNameEx,0)!=-1)
//				MoveFileEx(ArchiveFileNameEx,fn,
//					MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH );
			//make sure path exists
			MakeMyPath(fn);
		}

		if ((File = fopen(fn,"at+")) != NULL)
		{
			//	send string
			fprintf(File,Message);
			//	close cev
			fclose(File);
		}
		return;
	}

	//if to cev
	if (ToWhom & TO_CEV)
	{
		//	open filename+cev
		CString fn(m_szCurrentFileName);
		fn += CEV_SUFFIX;

		//if fn does not exist (it may have been moved or we have a new day)
		if (_access(fn,0) != 0)
		{
			//make sure path exists
			MakeMyPath(fn);

			if (m_pParent->m_bUseShortFilename)
			{
				//build archive path\name
				char cYear;
				int iYear = TC.GetYear();
				if ((iYear < 1990) || (iYear > 2025))
					cYear = '#';
				else if (iYear < 2000)
					cYear = (char)('0' + iYear - 1990);
				else 
					cYear = (char)('A' + iYear - 2000);

				ArchiveFileName.Format("%s\\archive\\%s%c%c%c%c%02d.%s",
				((CEOSSInstrument*)m_pParent)->m_szSaveLoc,
				((CEOSSInstrument*)m_pParent)->m_pID,
				cYear,
	//			((TC.GetYear()-1990)<10)?
	//				((TC.GetYear()-1990<0)?'#':'0'+(TC.GetYear()-1990)):
	//				'A'+(TC.GetYear()-2000),
				((TC.GetMonth()<10)?
					'0'+(TC.GetMonth()):
					'A'+(TC.GetMonth()-10)),
				((TC.GetDay()  <10)?
					'0'+(TC.GetDay()):
					'A'+(TC.GetDay()  -10)),
				'A',0,CEV_SUFFIX);
			}
			else
			{
				CString cTemp;
				cTemp = m_pParent->m_szSaveLoc;
				cTemp += "\\archive\\";
				BuildFileName(ArchiveFileName,
					m_pParent->m_csLongNameFormatString,
					cTemp,"EO",
					m_pParent->m_pID,TC.GetYear(),TC.GetMonth(),TC.GetDay(),0,0,0,"",CEV_SUFFIX);
			}

			//if it exists in the subdirectory "archive" then move it and use it
			if (_access(ArchiveFileName,0)==0)
				MoveFileEx(ArchiveFileName,fn,
					MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH );
		}

		if ((File = fopen(fn,"at+")) != NULL)
		{
			//if new file do stuff
			fseek(File,0,SEEK_END);
			fgetpos(File,&position);
			if (position==0)
			{
				m_bStartOfFile	= true;
			}

			//	send string
			fprintf(File,Message);
			//	close cev
			fclose(File);
		}
	}

	//if to pfm
	if (ToWhom & TO_PFM)
	{
		//	open filename+pfm
		CString fn(m_szCurrentFileName);
		fn += PFM_SUFFIX;

//		CString ArchiveFileNameExt = ArchiveFileName + PFM_SUFFIX;

		//if fn does not exist (it may have been moved or we have a new day)
		if (_access(fn,0) != 0)
		{
			//make sure path exists
			MakeMyPath(fn);

			//check if it is in the archive directory
			//build file name
			if (m_pParent->m_bUseShortFilename)
			{
				char cYear;
				int iYear = TC.GetYear();
				if ((iYear < 1990) || (iYear > 2025))
					cYear = '#';
				else if (iYear < 2000)
					cYear = (char)('0' + iYear - 1990);
				else 
					cYear = (char)('A' + iYear - 2000);

				ArchiveFileName.Format("%s\\archive\\%s%c%c%c%c%02d.%s",
				m_pParent->m_szSaveLoc,
				m_pParent->m_pID,
				cYear,
	//			((TC.GetYear()-1990)<10)?
	//				((TC.GetYear()-1990<0)?'#':'0'+(TC.GetYear()-1990)):
	//				'A'+(TC.GetYear()-2000),
				((TC.GetMonth()<10)?
					'0'+(TC.GetMonth()):
					'A'+(TC.GetMonth()-10)),
				((TC.GetDay()  <10)?
					'0'+(TC.GetDay()):
					'A'+(TC.GetDay()  -10)),
				'A',0,PFM_SUFFIX);
			}
			else
			{
				CString cTemp;
				cTemp = ((CEOSSInstrument*)m_pParent)->m_szSaveLoc;
				cTemp += "\\archive\\";
				BuildFileName(ArchiveFileName,
					m_pParent->m_csLongNameFormatString,
					cTemp,"EO",
					m_pParent->m_pID,TC.GetYear(),TC.GetMonth(),TC.GetDay(),0,0,0,"",PFM_SUFFIX);
			}

			//if it exists in the subdirectory "archive" then move it and use it
			if (_access(ArchiveFileName,0)==0)
				MoveFileEx(ArchiveFileName,fn,
					MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH );
		}

		if ((File = fopen(fn,"at+")) != NULL)
		{
			//if new file do stuff
			fseek(File,0,SEEK_END);
			fgetpos( File, &position );
			if (position==0)
			{
				m_bStartOfFile	= true;
			}
			//	send string
			fprintf(File,Message);
			//	close pfm
			fclose(File);
		}
	}

}
Esempio n. 22
0
void CDlgAutoRegister::RegisterID( TaskNode& task )
{
	CRegisterMethod UserRegister;
	UserRegister.SetUserClass(1);
	UserRegister.SetIdType(12); // 二代证
	UserRegister.SetPersonalId(task.idInfo.idNumber);
	UserRegister.SetCountry(_T("CN"));
	UserRegister.SetUserName(task.idInfo.name);
	UserRegister.SetSex(task.idInfo.sex);
	UserRegister.SetCostExpense(0);//不受自带卡影响,因为设为0
	UserRegister.SetGuarantyMoney(0);

	CString strCardID = GetCardIdFromCenter(task.idInfo.idNumber);
	UserRegister.SetCardId(strCardID);
	UserRegister.SetNoCard(1);
	//UserRegister.SetNoCard(0); //固定收押金
	UserRegister.SetNoPresent(1);
	UserRegister.SetPassword("");
	UserRegister.SetCreditAmount(task.nAmount);
	UserRegister.SetAuditId(task.idInfo.idNumber);

	//深圳特殊的几个字段
	UserRegister.SetTel(_T(""));
	UserRegister.SetIdDepart(_T(""));
	UserRegister.SetJob(_T(""));
	UserRegister.SetAddress(_T(""));

	UserRegister.SetTimeId(0);

	if(!strCardID.IsEmpty())
	{
		theApp.GetCurCashier()->DoRegister(UserRegister);
		if (UserRegister.GetStatusCode() == 0)
		{
			CString str;
			str.Append(CIBAHelpper::FormatTime(COleDateTime::GetCurrentTime()));
			str.Append(_T(": "));
			str.AppendFormat(_T("%s %s %d元"), task.idInfo.idNumber, task.idInfo.name, task.nAmount / 100);

			ConsumeNode node;
			ZeroMemory(&node, sizeof(ConsumeNode));
			_tcscpy(node.idNumber, task.idInfo.idNumber);
			node.nMemberId = UserRegister.GetMemberId();

			COleDateTime cur = COleDateTime::GetCurrentTime();
			COleDateTime checkIn = cur + COleDateTimeSpan(0, 0, 1, 0);
			int n = task.nAmount / 100;
			int nH = n / 2;
			int nM = (n % 2 == 0 ? 0 : 30);
			COleDateTime checkOut = cur + COleDateTimeSpan(0, nH, nM, 0);
			_tcscpy(node.checkInTime,CIBAHelpper::FormatTime(checkIn));
			_tcscpy(node.checkOutTime,CIBAHelpper::FormatTime(checkOut));
			node.OleCheckOutTime = checkOut;
			node.OleCheckInTime = checkIn;
			node.nAmount = task.nAmount;
			_tcsncpy(node.name, task.idInfo.name, 10);
			COleDateTimeSpan timeSpan = checkOut - checkIn;
			node.nTimeConsume = timeSpan.GetTotalSeconds();

			node.bInvalid = 0;
			m_cs.Lock();
			m_arrConsumeNode.push_back(node);
			m_cs.Unlock();

			CString *pStr = new CString;
			*pStr = str;
			PostMessage(M_INSERT_STRING, (WPARAM)pStr);
		}
		else
		{
			CString str;
			str.Append(CIBAHelpper::FormatTime(COleDateTime::GetCurrentTime()));
			str.Append(_T(": 失败! "));
			str.AppendFormat(_T("%s %s %d元 %s"), task.idInfo.idNumber, task.idInfo.name, task.nAmount / 100, UserRegister.GetStatusMessage());

			CString *pStr = new CString;
			*pStr = str;
			PostMessage(M_INSERT_STRING, (WPARAM)pStr);
		}
	}
	else
	{
		CString str;
		str.Append(CIBAHelpper::FormatTime(COleDateTime::GetCurrentTime()));
		str.Append(_T(": 失败! "));
		str.AppendFormat(_T("%s %s %d元 %s"), task.idInfo.idNumber, task.idInfo.name, task.nAmount / 100, _T("卡号已经存在"));

		CString *pStr = new CString;
		*pStr = str;
		PostMessage(M_INSERT_STRING, (WPARAM)pStr);
	}
	
}