Ejemplo n.º 1
0
/*********************************************************
函数名称:CheckSocketStatus
功能描述:检查每个Socket 将其中空的和超时的删除掉
创建时间:2016-08-19
参数说明:
返 回 值:
*********************************************************/
int CSocketServerDlg::CheckSocketStatus(void)
{
	POSITION pos = m_listSocketChat.GetHeadPosition();
	while(pos != NULL)
	{
		CChatSocket* p = m_listSocketChat.GetNext(pos);
		// 删除空Socket
		if(p == NULL)
		{
			if(pos == NULL)
			{// 空Socket位于链表末尾
				m_listSocketChat.RemoveTail();
				break;
			}
			else
			{
				POSITION posTemp = pos;
				m_listSocketChat.GetPrev(posTemp);
				m_listSocketChat.RemoveAt(posTemp);
			}
			continue;
		}
		
		// 删除超过时间没有通信的Socket
		int nMaxSec = 30; // 等待的最大时间
		CTimeSpan tmsp;
		tmsp = CTime::GetCurrentTime() - p->m_tmLastMsg;
		TRACE("%d\n", tmsp.GetTotalSeconds());
		
		if(tmsp.GetTotalSeconds() >= nMaxSec || tmsp.GetSeconds() < 0)
		{
			CString csOutMsg;
			CString csID;
			csID = p->m_userID;
			csOutMsg.Format(_T("用户%s连接超时"), csID);
			OutputInfo(csOutMsg);
			
			m_data.SetUserStatus(p->m_userID, IDS_STATUS_OFFLINE);
			
			p->Close(); // 关闭连接
			delete p; // 释放内存
			// 删除元素
			if(pos == NULL)
			{// 空Socket位于链表末尾				
				m_listSocketChat.RemoveTail();
				break;
			}
			else
			{
				POSITION posTemp = pos;
				m_listSocketChat.GetPrev(posTemp);
				m_listSocketChat.RemoveAt(posTemp);
			}
			continue;
		}
	}
	return 0;
}
Ejemplo n.º 2
0
double DBPool::GetJshValue(int nValue ,CString strRealName)
{
	CString strName;
	
	CString stream;

	strName.Format("%s--%s",strRealName,dsn);

	#if _DEBUG
	  stream.Format("%s\\Temp\\SQLMonitor.ini",szRootPath);
	#else
	  stream.Format("%s\\Monitormanager\\Temp\\SQLMonitor.ini",szRootPath);
	#endif
	 int lastvalue ;
	 lastvalue=GetPrivateProfileInt(strName,"lastvalue",-1,(LPCSTR)stream);
	 int lasttime;
	 lasttime =GetPrivateProfileInt(strName,"lasttime",-1,(LPCSTR)stream);
	 CTime tNow =CTime::GetCurrentTime();
	 CTime tBase =CTime(2004,1,1,0,0,0,-1);
	 CTimeSpan tC;
	 tC=tNow-tBase;
	 long nCurrentTime =tC.GetTotalSeconds();
	 CString wValue;
	 wValue.Format("%d",nCurrentTime);
	 WritePrivateProfileString(strName,"lasttime",wValue.GetBuffer(wValue.GetLength()),(LPCSTR)stream);
	 wValue.Format("%d",nValue);
	 WritePrivateProfileString(strName,"lastvalue",wValue.GetBuffer(wValue.GetLength()),(LPCSTR)stream);
	 if(lastvalue==-1) nValue=0;
	  nValue=nValue-lastvalue;
	  if(nValue<0)  nValue=0;
	  double dValue ;
	  dValue =(double )nValue/(nCurrentTime-lasttime);
	  return dValue;
}
Ejemplo n.º 3
0
void CMainFrame::OnTimer
(
	UINT		nIDEvent
) 
{
	CTimeSpan	timeLeft	= 0;
	LONG		minLeft		= 0;
	LONG		secLeft		= 0;
	CMainFrame	*hWnd		= NULL;
	char		*szSubj		= NULL;

	log_printf("CMainFrame::OnTimer: entered.\n");

//#if 0 ///////////////////////////////////////////////////////
	hWnd		= (CMainFrame *)theApp.m_pMainWnd;
	get_cert_time_left(szCertRealm, &timeLeft);	// returns 0 if no realm or cert
	minLeft		= timeLeft.GetTotalMinutes();


	// Set TrayIcon to reflect status of cert (if any)
	if (minLeft >= CERT_DYING)
		hWnd->m_trayIcon.ChangeSysTrayIcon(IDI_AUTH);
	else 
	{
		if (minLeft < CERT_DYING)
		{
			szSubj		= get_cert_subj(szCertRealm);

			// If null Subject, then no cert exists so change to Un-authenticated Icon
			if (!szSubj)
				hWnd->m_trayIcon.ChangeSysTrayIcon(IDI_UNAUTH);
			else
			{
				// Alternate TrayIcons 'tween DEAD & DYING
				secLeft = (int)timeLeft.GetTotalSeconds();
				if ((secLeft % 2))
					hWnd->m_trayIcon.ChangeSysTrayIcon(IDI_DEAD);
				else
					hWnd->m_trayIcon.ChangeSysTrayIcon(IDI_AUTH);
				free(szSubj);
			}
		}
		else
			hWnd->m_trayIcon.ChangeSysTrayIcon(IDI_DEAD);
		log_printf("CMainFrame::OnTimer: gszHardErrorMsg=%s.\n", gszHardErrorMsg);
		if (bkx509busy == FALSE) 
		{
			bkx509busy = TRUE;
			kx509_main(kx509_argc, kx509_argv);
			bkx509busy = FALSE;
		}
	}
//#endif // 0 //////////////////////////////////////////////////////////////////


	// Do above check every 5 seconds
	(void)SetTimer(ID_SAMPLE_RATE, 5*1000, NULL);

	CFrameWnd::OnTimer(nIDEvent);
}
Ejemplo n.º 4
0
Archivo: alarm.cpp Proyecto: bugou/test
static void setTimer(CTime &t)
{
	CTime cur = CTime::GetCurrentTime();
	if (t >= cur) {
		KillTimer(NULL, timerID);
		CTimeSpan span = t - cur;
		timerID = SetTimer(NULL, 0, span.GetTotalSeconds() * 1000, onTimer);
	}
}
void CALLBACK CAuctionServerDoc::TimerAfterBidProc(void* p)
{
    CTime lastTxTime = GetRecentTransactionTime(m_dwAuctionID);
    CTime now = CTime::GetCurrentTime();
    CTimeSpan ts = now - lastTxTime;
    TRACE(L"\nDiff of Tx = %I64d\n", ts.GetTotalSeconds() );

    CBroadcastState state;
    if (ts.GetTotalSeconds() > WAITINGTIME)
    {
        state.SetState(E_NONE);
    }
    else
    {
        state.SetState(E_AUCTION);
    }

    BroadcastBuffer(state);
}
Ejemplo n.º 6
0
//006bc300
unsigned long CPeriodItemEx::GetLeftDate(long lExpireDate)	//OK
{
	unsigned long dwReturnValue = 0;
	CTime tExpireTime(lExpireDate);
	CTime tCurrentTime(CTime::GetTickCount());
	CTimeSpan tSpanTime;
	tSpanTime = tExpireTime - tCurrentTime;
	dwReturnValue = tSpanTime.GetTotalSeconds();
	return dwReturnValue;
}
Ejemplo n.º 7
0
//此函数暂时不使用
CString CMainFrame::GetRunningTime()
{
	CTimeSpan tSpan;
	tSpan = CTime::GetCurrentTime() - m_StartTime;
	LONGLONG totalSeconds = tSpan.GetTotalSeconds();
	LONGLONG totalMinutes = tSpan.GetTotalMinutes();
	LONGLONG totalHours = tSpan.GetTotalHours();
	CString strRet="";
	strRet.Format("%d天%02d时%02d分%02d秒",totalHours / 24,totalHours % 24,totalMinutes % 60,totalSeconds % 60);
	return strRet;
}
Ejemplo n.º 8
0
/*===========================================================================
 *
 * Function - int l_FileListCompare (lParam1, lParam2, lParamSort);
 *
 *=========================================================================*/
int CALLBACK l_FileListCompare (LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) {
  srloaddlgfileinfo_t*  pData1    = (srloaddlgfileinfo_t  *) lParam1;
  srloaddlgfileinfo_t*  pData2    = (srloaddlgfileinfo_t  *) lParam2;
  srloadfilesortinfo_t* pSortData = (srloadfilesortinfo_t *) lParamSort;
  int		        Result    = 0;

  if (pData1 == NULL || pData2 == NULL || pSortData == NULL) return (0);

  switch (pSortData->SortType) {
    case SRFILELIST_FILENAME:
        Result = _tcsicmp(pData2->FindData.cFileName, pData1->FindData.cFileName);
	break;
    case SRFILELIST_DATE: {
        CTime Time1(pData1->FindData.ftLastWriteTime);
        CTime Time2(pData2->FindData.ftLastWriteTime);
        CTimeSpan TimeDiff = Time2 - Time1;
		Result = (int)(TimeDiff.GetTotalSeconds());
		break; }
    case SRFILELIST_SIZE:
        Result = pData2->FindData.nFileSizeHigh - pData1->FindData.nFileSizeHigh;
		if (Result == 0) Result = pData1->FindData.nFileSizeLow - pData2->FindData.nFileSizeLow;
		break;
    case SRFILELIST_DEFAULTSORT: {
        
		if (pData1->IsMaster != pData2->IsMaster) {
			Result = pData2->IsMaster - pData1->IsMaster;
		}
		else {
          CTime Time1(pData1->FindData.ftLastWriteTime);
          CTime Time2(pData2->FindData.ftLastWriteTime);
          CTimeSpan TimeDiff = Time2 - Time1;
		  Result = (int) (TimeDiff.GetTotalSeconds());
		}

	break; }
  }

  if (pSortData->Reverse) return (-Result);
  return (Result);
}
Ejemplo n.º 9
0
void CActivityView::PaintHost(CBrother *b,CDC *pDC,CRect& rc,CTime *bTime,CTimeSpan *tSpan)
{
	ASSERT(b);
	if(b->m_Log.IsEmpty())
		return;
CBigBrotherDoc* pDoc = (CBigBrotherDoc*)GetDocument();
	ASSERT(pDoc);
	ASSERT(pDoc->IsKindOf(RUNTIME_CLASS(CBigBrotherDoc)));
ULONG	rttMax = b->m_TimeOut;
CTime beginTime;
CTimeSpan ts;
	if(bTime && tSpan){
		beginTime= *bTime;
		ts = *tSpan;
	}else{
		beginTime = b->m_Log.GetHead()->m_Time;
	CTime endTime = b->m_Log.GetTail()->m_Time;
		ts = endTime-beginTime;
		if(ts<pDoc->m_MaxLogTime)
			ts = pDoc->m_MaxLogTime;
	}
POSITION	p = b->m_Log.GetHeadPosition();
	ASSERT(p);
CLogEntry *le = b->m_Log.GetNext(p);
	ASSERT(le);
int	x = rc.left+(le->m_Time-beginTime).GetTotalSeconds()*rc.Width()/ts.GetTotalSeconds();
	while(p){
		le = b->m_Log.GetNext(p);
		ASSERT(le);
	int newx=rc.left+(le->m_Time-beginTime).GetTotalSeconds()*rc.Width()/ts.GetTotalSeconds();
		if(!(le->flags&CLogEntry::flagsSeparator)){
		UINT	size = le->m_bReached?min(rttMax,le->m_RTT):rttMax;
		int	drawSize=(rttMax-size)*rc.Height()/rttMax;
		COLORREF color=le->m_bReached?((size<(rttMax/3))?m_Green:((size<(rttMax*2/3))?m_Yellow:m_Red)):m_Dim;
			pDC->FillSolidRect(x,rc.bottom-drawSize,newx-x,drawSize,color);
		}
		x=newx;
	}
}
void SaveBinaryNoParsingDlg::OnTimer(UINT_PTR nIDEvent)
{
  char drive[3] = {0};
  drive[0] = filePath[0];
  drive[1] = filePath[1];
  CTimeSpan ts = CTime::GetCurrentTime() - startTime;
  ShowDuration(ts, IDC_DURATION);
  ShowSize(buffer.totalWriteSize, IDC_TOTAL_SIZE);

  ULARGE_INTEGER p1;
  if(GetDiskFreeSpaceEx(drive, &p1, NULL, NULL))
  {
    ShowSize(p1.QuadPart, IDC_TOTAL_FREE);
    if(ts.GetTotalSeconds() > 5 && buffer.totalWriteSize > 0)
    {
      int estSec = (int)(p1.QuadPart / (buffer.totalWriteSize / ts.GetTotalSeconds()));
      //IDC_EST_TIME
      CTimeSpan estTs(0, 0, 0, estSec);
      ShowDuration(estTs, IDC_EST_TIME);
    }
  }

  if(buffer.alreadyAck)
  {
    GetDlgItem(IDC_PROMPT)->SetWindowText("HostLog starts.");
  }
  else
  {
    if(--noAckAlerm == 0)
    {
      KillTimer(DisplayInfoTimerId);
      ::AfxMessageBox("HostLog restart timeout!");
      SetTimer(DisplayInfoTimerId, 1000, NULL);
    }
  }
  CDialog::OnTimer(nIDEvent);
}
Ejemplo n.º 11
0
/*===========================================================================
 *
 * Function - int l_SortLoadInfosByDate (lParam1, lParam2, lParamSort);
 *
 *=========================================================================*/
int __stdcall l_SortLoadInfosByDate (long lParam1, long lParam2, long lParamSort) 
{
  srloaddlgfileinfo_t* pFileInfo1 = (srloaddlgfileinfo_t *) lParam1;
  srloaddlgfileinfo_t* pFileInfo2 = (srloaddlgfileinfo_t *) lParam2;

		/* Special case for Skyrim.esm to ensure it is loaded first */
  if (stricmp(pFileInfo1->FindData.cFileName, "Skyrim.esm") == 0) return -1;
  if (stricmp(pFileInfo2->FindData.cFileName, "Skyrim.esm") == 0) return 1;

  if (pFileInfo1 == NULL || pFileInfo2 == NULL) return (0);

  CTime Time1(pFileInfo1->FindData.ftLastWriteTime);
  CTime Time2(pFileInfo2->FindData.ftLastWriteTime);
  CTimeSpan TimeDiff = Time1 - Time2;

  return(int) TimeDiff.GetTotalSeconds();
}
Ejemplo n.º 12
0
//sends a message, or part of one
int CPassiveSock::Send(const void * const lpBuf, const int Len)
{
    WSAOVERLAPPED os;
    WSABUF buffers[2];
    WSAEVENT hEvents[2] = {NULL,NULL};
    DWORD
    dwWait,
    bytes_sent=0,
    msg_flags = 0;

    // Setup up the events to wait on
    hEvents[1] = write_event;
    hEvents[0] = m_hStopEvent;
    // Setup the buffers array
    buffers[0].buf = (char *)lpBuf;
    buffers[0].len = Len;
    msg_flags = 0;
    dwWait = 0;
    int rc;

    LastError = 0;

    // Create the overlapped I/O event and structures
    memset(&os, 0, sizeof(OVERLAPPED));
    os.hEvent = write_event;
    WSAResetEvent(read_event);
    rc = WSASend(ActualSocket, buffers, 1, &bytes_sent, 0, &os, NULL);
    LastError=WSAGetLastError();
    if ((rc == SOCKET_ERROR) && (LastError == WSA_IO_PENDING))  // Write in progress
    {
        CTimeSpan TimeLeft = SendEndTime - CTime::GetCurrentTime();
        dwWait = WaitForMultipleObjects(2, hEvents, false, (DWORD)TimeLeft.GetTotalSeconds()*1000);
        if (dwWait == WAIT_OBJECT_0+1) // I/O completed
        {
            if (WSAGetOverlappedResult(ActualSocket, &os, &bytes_sent, true, &msg_flags))
                return bytes_sent;
        }
    }
    else if (!rc) // if rc is zero, the read was completed immediately
    {
        if (WSAGetOverlappedResult(ActualSocket, &os, &bytes_sent, true, &msg_flags))
            return bytes_sent;
    }
    return SOCKET_ERROR;
}
Ejemplo n.º 13
0
void CXfilterDlg::OnLoad() 
{
	IpFilterDriver.init(IP_FILTER_DRIVER_NAME, FILE_ATTRIBUTE_NORMAL);	
	CString s;
	CTime time = CTime::GetCurrentTime();
	CTimeSpan ts;
	CTime t(0);
	ts = time - t;
	s.Format("CurrentTime: %u, %s DayCount:%u, TotalSec:%u, Week: %u\n"
		, CTime::GetCurrentTime().GetTime()
		, time.Format("%Y-%m-%d %H:%M:%S")
		, ts.GetDays()
		, ts.GetTotalSeconds()
		, time.GetDayOfWeek());
//	OutputDebugString(s);

	if (IpFilterDriver.getError() != NO_ERROR) 
		AfxMessageBox(_T("Can't load IpFilter Driver"));
}
Ejemplo n.º 14
0
void CLeftView::stopFlightExperiment(void)
{
	char command[2];
	__int16 *c = (__int16 *)command;
	c[0] = TFT_STOPTASK;

	CNetCln* cln = ((CGTApp*)AfxGetApp())->getCln();
	cln->SendSvr(command, sizeof(command));	

	// Update...
	endTime = CTime::GetCurrentTime();
		
	CTimeSpan tof = endTime - startTime;
	ed.tof = tof.GetTotalSeconds();
		
	// Force to serialize
	serialize(TRUE);

	((CMainFrame*)AfxGetMainWnd())->enableMenuItems(TRUE);

}
Ejemplo n.º 15
0
int CPacket::ReceiveFrame(CSerialPort &port)
{
	char c=0;
	strData.Empty();
	do
	{
		int n=port.Read(&c,1);
		if (n<0)
			return -1;
		else if(n==0)
			return 0;
	}while(c != STX);

	strData+=c;
	CTime start = CTime::GetCurrentTime();
	CTime now;
	CTimeSpan pause;
	do
	{
		int n = port.Read(&c,1);
		if (n<0)
			return -1;
		else if (n)
		{
			start = CTime::GetCurrentTime();
			strData+=c;
		}
		now = CTime::GetCurrentTime();
		pause = now - start;
		if (pause.GetTotalSeconds() > 5)
		{
			strData.Empty();
			return 0;
		}
	}while(c!=ETX);

	return strData.GetLength();
}
Ejemplo n.º 16
0
void CAddTimer::UpdateDuration()
{
	CTimeSpan aday(1,0,0,0);
	CTimeSpan tempduration;
	CTime end, start;
	UpdateData(TRUE);

	//m_endtime.GetTime(end);
	//m_starttime.GetTime(start);
	end = m_endtimex;
	start = m_starttimex;

	if (end < start) end += aday;

	tempduration = end - start;

	//Only enable ok button if duration is greater than 0
	if((tempduration.GetTotalSeconds() > 0) && (m_channellist.GetCurSel() != LB_ERR)){
		m_ok.EnableWindow(TRUE);
	}else{
		m_ok.EnableWindow(FALSE);
	}

	CString temp;
	if(tempduration.GetHours()>0) temp += tempduration.Format("%Hhr");
	if(tempduration.GetMinutes()>0)  temp += tempduration.Format("%Mmin");
	//temp += duration.Format("%Ssec");
	m_duration = temp;
	
	
	//Get programme name from guide
	CProgGuideDlg pgdlg(NULL,NULL);
	m_progname = pgdlg.getProg(m_channellist.GetCurSel(),m_starttimex);

	UpdateData(FALSE);

}
// 工作
unsigned int OnWork(m_oEnvironmentStruct* pEnv)
{
	ASSERT(pEnv != NULL);
	if (pEnv->m_bFieldOn == true)
	{
		return 0;
	}
	CTime timeFieldOn = CTime::GetCurrentTime();
	CTime timeFieldOff;
	CTimeSpan timeWait;
	int nDays, nHours, nMins, nSecs;
	// 从配置文件中读出上一次FieldOff时间
	LoadServerParameterSetupData(pEnv->m_pInstrumentCommInfo->m_pServerSetupData);
	EnterCriticalSection(&pEnv->m_pInstrumentCommInfo->m_pServerSetupData->m_oSecCommInfo);
	timeFieldOff = pEnv->m_pInstrumentCommInfo->m_pServerSetupData->m_oXMLParameterSetupData.m_oTimeFieldOff;
	LeaveCriticalSection(&pEnv->m_pInstrumentCommInfo->m_pServerSetupData->m_oSecCommInfo);
	nDays = pEnv->m_pConstVar->m_uiFieldOnWaitTimeLimit / (24 * 3600);
	nHours = pEnv->m_pConstVar->m_uiFieldOnWaitTimeLimit / 3600;
	nMins = pEnv->m_pConstVar->m_uiFieldOnWaitTimeLimit / 60;
	nSecs = pEnv->m_pConstVar->m_uiFieldOnWaitTimeLimit % 60;
	timeFieldOff += CTimeSpan(nDays, nHours, nMins, nSecs);
	if (timeFieldOn < timeFieldOff)
	{
		timeWait = timeFieldOff - timeFieldOn;
		return (unsigned int)timeWait.GetTotalSeconds();
	}
	pEnv->m_bFieldOn = true;
	// 重置测线队列结构体
	OnResetLineList(pEnv->m_pLineList);
	// 重置数据存储缓冲区结构体
	OnResetADCDataBufArray(pEnv->m_pADCDataBufArray);
	// 重置施工任务数组结构体
	OnResetOptTaskArray(pEnv->m_pOptTaskArray);
	// 日志输出线程开始工作
	EnterCriticalSection(&pEnv->m_pLogOutPutThread->m_oSecLogOutPutThread);
	pEnv->m_pLogOutPutThread->m_pThread->m_bWork = true;
	LeaveCriticalSection(&pEnv->m_pLogOutPutThread->m_oSecLogOutPutThread);
	// 心跳线程开始工作
	EnterCriticalSection(&pEnv->m_pHeartBeatThread->m_oSecHeartBeatThread);
	pEnv->m_pHeartBeatThread->m_pThread->m_bWork = true;
	LeaveCriticalSection(&pEnv->m_pHeartBeatThread->m_oSecHeartBeatThread);
	EnterCriticalSection(&pEnv->m_pHeadFrame->m_oSecHeadFrame);
	// 清空首包帧接收缓冲区
	OnClearSocketRcvBuf(pEnv->m_pHeadFrame->m_oHeadFrameSocket, pEnv->m_pConstVar->m_iRcvFrameSize);
	LeaveCriticalSection(&pEnv->m_pHeadFrame->m_oSecHeadFrame);
	// 首包接收线程开始工作
	EnterCriticalSection(&pEnv->m_pHeadFrameThread->m_oSecHeadFrameThread);
	pEnv->m_pHeadFrameThread->m_pThread->m_bWork = true;
	pEnv->m_pHeadFrameThread->m_uiHeadFrameCount = 0;
	LeaveCriticalSection(&pEnv->m_pHeadFrameThread->m_oSecHeadFrameThread);
	EnterCriticalSection(&pEnv->m_pIPSetFrame->m_oSecIPSetFrame);
	// 清空IP地址设置应答帧接收缓冲区
	OnClearSocketRcvBuf(pEnv->m_pIPSetFrame->m_oIPSetFrameSocket, pEnv->m_pConstVar->m_iRcvFrameSize);
	LeaveCriticalSection(&pEnv->m_pIPSetFrame->m_oSecIPSetFrame);
	// IP地址设置线程开始工作	
	EnterCriticalSection(&pEnv->m_pIPSetFrameThread->m_oSecIPSetFrameThread);
	pEnv->m_pIPSetFrameThread->m_pThread->m_bWork = true;
	LeaveCriticalSection(&pEnv->m_pIPSetFrameThread->m_oSecIPSetFrameThread);
	EnterCriticalSection(&pEnv->m_pTailFrame->m_oSecTailFrame);
	// 清空尾包帧接收缓冲区
	OnClearSocketRcvBuf(pEnv->m_pTailFrame->m_oTailFrameSocket, pEnv->m_pConstVar->m_iRcvFrameSize);
	LeaveCriticalSection(&pEnv->m_pTailFrame->m_oSecTailFrame);
	// 尾包接收线程开始工作
	EnterCriticalSection(&pEnv->m_pTailFrameThread->m_oSecTailFrameThread);
	pEnv->m_pTailFrameThread->m_pThread->m_bWork = true;
	pEnv->m_pTailFrameThread->m_uiTailFrameCount = 0;
	LeaveCriticalSection(&pEnv->m_pTailFrameThread->m_oSecTailFrameThread);
	// 路由监视线程开始工作
	EnterCriticalSection(&pEnv->m_pMonitorThread->m_oSecMonitorThread);
	pEnv->m_pMonitorThread->m_pThread->m_bWork = true;
	LeaveCriticalSection(&pEnv->m_pMonitorThread->m_oSecMonitorThread);
	EnterCriticalSection(&pEnv->m_pErrorCodeFrame->m_oSecErrorCodeFrame);
	// 清空误码查询接收缓冲区
	OnClearSocketRcvBuf(pEnv->m_pErrorCodeFrame->m_oErrorCodeFrameSocket, pEnv->m_pConstVar->m_iRcvFrameSize);
	LeaveCriticalSection(&pEnv->m_pErrorCodeFrame->m_oSecErrorCodeFrame);
	EnterCriticalSection(&pEnv->m_pADCSetFrame->m_oSecADCSetFrame);
	// 清空ADC参数设置应答帧接收缓冲区
	OnClearSocketRcvBuf(pEnv->m_pADCSetFrame->m_oADCSetFrameSocket, pEnv->m_pConstVar->m_iRcvFrameSize);
	LeaveCriticalSection(&pEnv->m_pADCSetFrame->m_oSecADCSetFrame);
	EnterCriticalSection(&pEnv->m_pADCDataFrame->m_oSecADCDataFrame);
	// 清空ADC数据接收缓冲区
	OnClearSocketRcvBuf(pEnv->m_pADCDataFrame->m_oADCDataFrameSocket, pEnv->m_pConstVar->m_iRcvFrameSize);
	LeaveCriticalSection(&pEnv->m_pADCDataFrame->m_oSecADCDataFrame);
	// ADC数据接收线程开始工作
	EnterCriticalSection(&pEnv->m_pADCDataRecThread->m_oSecADCDataRecThread);
	pEnv->m_pADCDataRecThread->m_pThread->m_bWork = true;
	LeaveCriticalSection(&pEnv->m_pADCDataRecThread->m_oSecADCDataRecThread);
	// ADC数据存储线程开始工作
	EnterCriticalSection(&pEnv->m_pADCDataSaveThread->m_oSecADCDataSaveThread);
	pEnv->m_pADCDataSaveThread->m_pThread->m_bWork = true;
	LeaveCriticalSection(&pEnv->m_pADCDataSaveThread->m_oSecADCDataSaveThread);
	AddMsgToLogOutPutList(pEnv->m_pLogOutPutOpt, "OnWork", "开始工作");
	pEnv->m_bFieldOff = false;
	return 0;
}
Ejemplo n.º 18
0
BOOL TRAFFIC_MONITOR(char *server, int port, char *community, int ifindex, 
					 int timeout, int retrydelay, CString strMonitorID, 
					 char *custpath, char *szReturn)
{
	int s;
	struct sockaddr_in serv;

	int		i = 0, ret = 0;
	int		count = 1;
	struct	snval *ptmp = NULL;
	struct	snval *ptmpnext = NULL;

	long	ifOperStatus = 0;
	Gauge	ifSpeed = 0;
	Counter ifInOctets = 0, ifOutOctets = 0;
	Counter ifInErrors = 0, ifOutErrors = 0;

	if((ret = MakeSocket(server, port, s, serv)) < 0)
	{
		if(ret == -1)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Traffic_1%>"));
		else if(ret == -2)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Traffic_2%>"));
		else
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Traffic_3%>"));

		return FALSE;
	}

	struct oid *poid = NULL, *ptmpoid = NULL;
	oid ifInOctets_oid = {{0x2b, 6, 1, 2, 1, 2, 2, 1, 10}, 9};
	oid ifOutOctets_oid = {{0x2b, 6, 1, 2, 1, 2, 2, 1, 16}, 9};
	ifInOctets_oid.id[ifInOctets_oid.len++] = ifindex;
	poid = ptmpoid = &ifInOctets_oid;
	ifOutOctets_oid.id[ifOutOctets_oid.len++] = ifindex;
	ptmpoid->next = &ifOutOctets_oid;
	ptmpoid = ptmpoid->next;

	struct snval *psnval = NULL;
	if((ret = SN_VALUES(s, serv, community, 1, poid, &psnval)) < 0)
	{
		if(ret == -1)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_4%>"));//<%IDS_Dynamo_4%>
		else if(ret == -2)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_5%>"));//<%IDS_Dynamo_5%>
		else if(ret == -3)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_6%>"));//<%IDS_Dynamo_6%>
		else if(ret == -4)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_7%>"));//<%IDS_Dynamo_7%>
		else if(ret == -5)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_8%>"));//<%IDS_Dynamo_8%>
		else if(ret == -6)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_9%>"));//<%IDS_Dynamo_9%>
		else if(ret == -7)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_10%>"));//<%IDS_Dynamo_10%>
		else if(ret == -8)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_11%>"));//<%IDS_Dynamo_11%>
		else
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_Dynamo_12%>"));//<%IDS_Dynamo_12%>

		goto w;
	}

	ptmp = psnval;
	ptmpnext = NULL;
	while(ptmp)
	{
		switch(count)
		{
		case 1:
			switch(ptmp->sv_type)
			{
			case ASN1_INT:
			case ASN1_COUNTER:
			case ASN1_GAUGE:
			case ASN1_TIMETICKS:
			case ASN1_COUNTER64:
			case ASN1_UINTEGER32:
				ifInOctets = ptmp->sv_val.sv_int;
				break;
			default:
				ifInOctets = 0;
				break;
			}
			break;
		case 2:
			switch(ptmp->sv_type)
			{
			case ASN1_INT:
			case ASN1_COUNTER:
			case ASN1_GAUGE:
			case ASN1_TIMETICKS:
			case ASN1_COUNTER64:
			case ASN1_UINTEGER32:
				ifOutOctets = ptmp->sv_val.sv_int;
				break;
			default:
				ifOutOctets = 0;
				break;
			}
			break;
		}
		count ++;
		ptmp = ptmp->next;
	}

	// computer the traffic 
	{
	char ciniFile[256] = {0}, 
		 cinifile[256] = {0};
	char cifIndex[256] = {0};
	sprintf(cinifile, "snmp_%s_%s.ini", server, strMonitorID);
	sprintf(ciniFile, "%s\\%s", custpath, cinifile);
	sprintf(cifIndex, "ifIndex_%ld", ifindex);

	long	ifTime = 0;
	Counter inOctets = 0, outOctets = 0;

	CTime curTime = CTime::GetCurrentTime();

	ifTime = DFN_GetPrivateProfileInt(cifIndex, "ifTime", -99, ciniFile);
	inOctets = DFN_GetPrivateProfileInt(cifIndex, "ifInOctets", -99, ciniFile);
	outOctets = DFN_GetPrivateProfileInt(cifIndex, "ifOutOctets", -99, ciniFile);

	if(ifTime == -99 || inOctets == -99 || outOctets == -99)
	{
		CString strSection = _T("");
		strSection.Format("ifIndex_%ld", ifindex);

		curTime = CTime::GetCurrentTime();
		CString strMsg = _T("");
		strMsg.Format("%ld", curTime.GetTime());
		::DFN_WritePrivateProfileString((LPCTSTR)strSection, "ifTime", (LPCTSTR)strMsg, ciniFile);

		strMsg.Format("%ld", ifInOctets);
		::DFN_WritePrivateProfileString((LPCTSTR)strSection, "ifInOctets", (LPCTSTR)strMsg, ciniFile);
		strMsg.Format("%ld", ifOutOctets);
		::DFN_WritePrivateProfileString((LPCTSTR)strSection, "ifOutOctets", (LPCTSTR)strMsg, ciniFile);
		WriteLogFile(strMonitorID, "读配置文件失败");
	}
	else
	{
		float ifInOctetsRate = 0.0, ifOutOctetsRate = 0.0;
		Counter	InOctets = 0, OutOctets = 0;

		CTime bTime(ifTime);
		curTime = CTime::GetCurrentTime();
		CTimeSpan spanTime = curTime - bTime;
		long lInterval = spanTime.GetTotalSeconds();
		
		if(lInterval == 0) lInterval = 1;
		if(lInterval <= 12 * 60 * 60 && lInterval >= 0)
		{
			InOctets = (unsigned int)(ifInOctets - inOctets < 0 ? (COUNTER_MAX - inOctets + ifInOctets) : (ifInOctets - inOctets));
			//ifInOctetsRate = (float)InOctets / lInterval;
			//k
			ifInOctetsRate = (float)InOctets / lInterval/1024;

			OutOctets = (unsigned int)(ifOutOctets - outOctets < 0 ? (COUNTER_MAX - outOctets + ifOutOctets) : (ifOutOctets - outOctets));
			// wang peng /1024 =k
            //Edit By Kevin.Yang PM: 14:55 2004.10.21
            //Reason: 根据张鹏所提供的资料目前Cisio的MIF库中单位为KB,因此在
            //得到的数据后不再需要除以1024
			ifOutOctetsRate = (float)OutOctets / lInterval /1024;
			//ifOutOctetsRate = (float)OutOctets / lInterval;

			sprintf(szReturn, 
					"ifIndex=%ld$ifInOctetsRate=%.2f$ifOutOctetsRate=%.2f$",
					ifindex, 
					ifInOctetsRate * 8, 
					ifOutOctetsRate * 8);
		}
		else
		{
			CString strLog;
			strLog.Format("时间总秒数%d", lInterval);
//			WriteLogFile(strMonitorID, strLog);		
		}
//		WriteLogFile(strMonitorID, szReturn);
		//if(strlen(szReturn) == 0)
		//{
		//	printf("%d年%d月%d日 %d时%d分%d秒 \n%d年%d月%d日 %d时%d分%d秒 \n",
		//		curTime.GetYear(), curTime.GetMonth(), curTime.GetDay(), 
		//		curTime.GetHour(), curTime.GetMinute(), curTime.GetSecond(),
		//		bTime.GetYear(), bTime.GetMonth(), bTime.GetDay(),
		//		bTime.GetHour(), bTime.GetMinute(), bTime.GetSecond());
		//}
		char buff[256] = {0};
		memset(buff, 0, 256);
		ltoa(curTime.GetTime(), buff, 10);
		DFN_WritePrivateProfileString(cifIndex, "ifTime", buff, ciniFile);
		memset(buff, 0, 256);
		ltoa(ifInOctets, buff, 10);
		DFN_WritePrivateProfileString(cifIndex, "ifInOctets", buff, ciniFile);
		memset(buff, 0, 256);
		ltoa(ifOutOctets, buff, 10);
		DFN_WritePrivateProfileString(cifIndex, "ifOutOctets", buff, ciniFile);
	}
	}

w:	ptmp = psnval;
	if(ptmp) ptmpnext = ptmp->next;
	while(ptmp)
	{
		free(ptmp);
		ptmp = ptmpnext;
		if(ptmp) ptmpnext = ptmp->next;
	}

	return !ret;
}
Ejemplo n.º 19
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
#ifdef __EXPIRATION__
	// Program Expiration routines
	CTime expirationTime(2010,	// year
		2,					// month
		30,					// date
		23,					// hour 24
		59,					// minute
		59);				// second
	CTime currentTime = CTime::GetCurrentTime();

    CTimeSpan leftTime = expirationTime - currentTime;   

	// 사용 기간이 남았을 경우
	if(leftTime.GetTotalSeconds() > 0)
    {
		 CString msg;
		 msg = L"";
		 msg += L"This is a trial version of BTools2\n";
		 msg += expirationTime.Format(L"Expiration date :\n %Y-%m-%d  %H:%M:%S\n\n");
		 msg += leftTime.Format(L"%D day(s) and\n %H:%M:%S left" );
     
		 // 사용 기간이 3일 미만 남았을 경우
		 if(leftTime.GetDays() < 7)
		 {
			 msg = leftTime.Format(L"This software will expire after %D day(s)");// %H Hour(s) %M Minute(s)");
			 //AtlMessageBox(NULL, msg.GetBuffer(), L"Expiration Warning");
		 }
		 //AfxMessageBox(msg);
    }
    else // 사용 기간이 만료된 경우
    {
		CString msg("This is a trial version of BTools2\n"
				"If you want to use this software more\n"
				"Please contact to me.\[email protected]\n"
				"Thank you for your interest\n");

		msg += expirationTime.Format(L"Expiration date :\n %Y-%m-%d  %H:%M\n\n");
		msg += leftTime.Format(L"%D day(s) and\n %H:%M:%S passed" );
        //msg.Format(L"This software is submitted for the Windows Mobile Contest");
		//AtlMessageBox(NULL, msg.GetBuffer(), L"Warning");
		return FALSE;
	 }

#endif

#ifdef __TSTORE_ARM__0
	// ARM
	T_RETURN ret;
	TAPPID *APPID = TSTORE_APPLICATION_ID;

	bool aSuccess=true;

	T_RETURN res; 
	ARM_PLUGIN_Initialize(&res,APPID);
	if (res.code == ARM_SUCCESS) 
	{
		ARM_PLUGIN_CheckLicense(&res); 
		if (res.code == ARM_SUCCESS) 
		{ 
			ARM_PLUGIN_RequestLicense(&res); 
			if (res.code !=ARM_SUCCESS) 
			{ //실패시 구현 
				aSuccess=false;
				TCHAR wszMsg[1024];
				if(ret.pMsg)
				{
					ansi_to_unicode(ret.pMsg, strlen(ret.pMsg), wszMsg, 1024);
					::AtlMessageBox(NULL, wszMsg, L"[ARM]Request License");
				}
			}
		
		} 
		else 
		{//실패시 메시 구현 
			aSuccess=false;

			TCHAR wszMsg[1024];

			switch(res.code)
			{
			case CLICENSE_DENY:
			case CLICENSE_NOT_EXIST:
			case CLICENSE_EXPIRED:
			case CLICENSE_INVALID:
				{
					if(ret.pMsg)
					{
						ansi_to_unicode(ret.pMsg, strlen(ret.pMsg), wszMsg, 1024);
						::AtlMessageBox(NULL, wszMsg, L"[ARM]Check License");
					}
				}

			default:
				;
			}
		} 
	} 
	else 
	{ 
		aSuccess=false; 
	} 
	ARM_PLUGIN_Uninitialize(&res); 


	//if (! aSuccess) return 0;//PostQuitMessage(0); 

#endif

	//CAboutDlg aboutDlg;	aboutDlg.DoModal();
    //
	HRESULT hRes = CBTools2Frame::ActivatePreviousInstance(hInstance, lpstrCmdLine);

	if(FAILED(hRes) || S_FALSE == hRes)
	{
		return hRes;
	}

	hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
	ATLASSERT(SUCCEEDED(hRes));

	AtlInitCommonControls(ICC_DATE_CLASSES);
	SHInitExtraControls();

	hRes = _Module.Init(NULL, hInstance);
	ATLASSERT(SUCCEEDED(hRes));

	int nRet = CBTools2Frame::AppRun(lpstrCmdLine, nCmdShow);

	_Module.Term();
	::CoUninitialize();

	return nRet;
}
Ejemplo n.º 20
0
// do the action required to open a single atomic tag (iAction)
void CMUSHclientDoc::MXP_OpenAtomicTag (const CString strTag,
                                        int iAction, 
                                        CStyle * pStyle,
                                        CString & strAction,    // new action
                                        CString & strHint,      // new hint
                                        CString & strVariable,   // new variable
                                        CArgumentList & ArgumentList)
  {
CString strArgument;
CString strArgumentName;
bool bIgnoreUnusedArgs = false; // cut down on some spam by setting this
COLORREF colour1,
         colour2;

unsigned short iFlags      = pStyle->iFlags;      
COLORREF       iForeColour = pStyle->iForeColour; 
COLORREF       iBackColour = pStyle->iBackColour; 

  // call script if required
  if (m_dispidOnMXP_OpenTag != DISPID_UNKNOWN || m_bPluginProcessesOpenTag)
    {
    // dummy-up an argument list
    CString strArgument;
    CArgument * pArgument;
    POSITION pos;

    // put the arguments into the array

    for (pos = ArgumentList.GetHeadPosition (); pos; )
      {
      pArgument = ArgumentList.GetNext (pos);
      
      // empty ones we will put there by position
      if (pArgument->strName.IsEmpty ())
        strArgument += CFormat ("'%s'",
                      (LPCTSTR) pArgument->strValue);
      else
        strArgument += CFormat ("%s='%s'",
                      (LPCTSTR) pArgument->strName,
                      (LPCTSTR) pArgument->strValue);

      if (pos)
        strArgument += " ";

      }      // end of looping through each argument

    bool bNotWanted = MXP_StartTagScript (strTag, strArgument, ArgumentList);

    // re-get current style in case the script did a world.note
    pStyle = m_pCurrentLine->styleList.GetTail ();

    // put things backt to how they were
    pStyle->iFlags      = iFlags;      
    pStyle->iForeColour = iForeColour; 
    pStyle->iBackColour = iBackColour; 

    if (bNotWanted)
      return;   // they didn't want to go ahead with this tag

    }


// find current foreground and background RGB values
  GetStyleRGB (pStyle, colour1, colour2);

// special processing for Pueblo
// a tag like this: <A XCH_CMD="examine #1"> 
// will convert to a SEND tag

  if (iAction == MXP_ACTION_HYPERLINK &&
      PUEBLO_ACTIVE)
    {
    strArgument = GetArgument (ArgumentList, "xch_cmd", 0, true);
    if (!strArgument.IsEmpty ())
      {
      m_bPuebloActive = true;  // for correct newline processing
      iAction = MXP_ACTION_SEND;
      }
    }    

  // now take the action 
  switch (iAction)
    {

    // temporarily make headlines the same as bold
    case MXP_ACTION_H1: 
    case MXP_ACTION_H2: 
    case MXP_ACTION_H3: 
    case MXP_ACTION_H4: 
    case MXP_ACTION_H5: 
    case MXP_ACTION_H6: 

    case MXP_ACTION_BOLD: pStyle->iFlags |= HILITE; break;
    case MXP_ACTION_UNDERLINE: pStyle->iFlags |= UNDERLINE; break;
    case MXP_ACTION_ITALIC: pStyle->iFlags |= BLINK; break;

    case MXP_ACTION_COLOR:
         {

         pStyle->iForeColour = colour1;
         pStyle->iBackColour = colour2;
         // convert to RGB colour to start with in case only FORE or BACK supplied
         pStyle->iFlags &= ~COLOURTYPE;  // clear bits, eg. custom
         pStyle->iFlags |= COLOUR_RGB;

         // foreground colour
         strArgument = GetArgument (ArgumentList, "fore", 1, true);  // get foreground colour
         if (!m_bIgnoreMXPcolourChanges)
           if (SetColour (strArgument, pStyle->iForeColour)) 
             MXP_error (DBG_ERROR, errMXP_UnknownColour,
                        TFormat ("Unknown colour: \"%s\"" ,
                                 (LPCTSTR) strArgument));

         // background colour
         strArgument = GetArgument (ArgumentList, "back", 2, true);  // get background colour
         if (!m_bIgnoreMXPcolourChanges)
           if (SetColour (strArgument, pStyle->iBackColour)) 
             MXP_error (DBG_ERROR, errMXP_UnknownColour,
                        TFormat ("Unknown colour: \"%s\"" ,
                                 (LPCTSTR) strArgument));
         }
         break;   // end of COLOR

    case MXP_ACTION_HIGH:
         {
         CColor clr;

         pStyle->iForeColour = colour1;
         pStyle->iBackColour = colour2;
         // convert to RGB colour to start with 
         pStyle->iFlags &= ~COLOURTYPE;  // clear bits, eg. custom
         pStyle->iFlags |= COLOUR_RGB;

         clr.SetColor (colour1);
         float lum = clr.GetLuminance ();
         lum += 0.15f;
         if (lum > 1.0f)
           lum = 1.0f;
         clr.SetLuminance (lum);
         pStyle->iForeColour = clr; 
         
         }
         break;   // end of COLOR

    case MXP_ACTION_SEND: 
          // send to mud hyperlink

          pStyle->iFlags &= ~ACTIONTYPE;   // cancel old actions
          if (GetKeyword (ArgumentList, "prompt"))
            pStyle->iFlags |= ACTION_PROMPT;   // prompt action
          else
            pStyle->iFlags |= ACTION_SEND;   // send-to action

          if (m_bUnderlineHyperlinks)
            pStyle->iFlags |= UNDERLINE;   // underline it

          if (m_bUseCustomLinkColour)
            {
            // find current background RGB value
            pStyle->iForeColour = m_iHyperlinkColour;    // use hyperlink colour
            pStyle->iBackColour = colour2;
            pStyle->iFlags &= ~COLOURTYPE;  // clear bits, eg. custom
            pStyle->iFlags |= COLOUR_RGB;
            }

          strArgument = GetArgument (ArgumentList,"href", 1, false);  // get link
          if (strArgument.IsEmpty ())
            strArgument = GetArgument (ArgumentList,"xch_cmd", 1, false);  // get link
            
          strAction = strArgument;   // hyperlink
         
          strArgument = GetArgument (ArgumentList, "hint", 2, false);  // get hints
          if (strArgument.IsEmpty ())
            strArgument = GetArgument (ArgumentList,"xch_hint", 2, false);  // get hint
          
          strHint = strArgument;     // hints

          break;  // end of MXP_ACTION_SEND

    case MXP_ACTION_HYPERLINK: 
          // hyperlink

          strArgument = GetArgument (ArgumentList,"href", 1, false);  // get link
          strAction = strArgument;   // hyperlink

          pStyle->iFlags &= ~ACTIONTYPE;   // cancel old actions
          pStyle->iFlags |= ACTION_HYPERLINK | UNDERLINE;   // send-to action

          if (m_bUseCustomLinkColour)
            {
            pStyle->iForeColour = m_iHyperlinkColour;    // use hyperlink colour
            pStyle->iBackColour = colour2;
            pStyle->iFlags &= ~COLOURTYPE;  // clear bits, eg. custom
            pStyle->iFlags |= COLOUR_RGB;
            }

          break;  // end of MXP_ACTION_HYPERLINK

    case MXP_ACTION_FONT:
          {
          pStyle->iForeColour = colour1;
          pStyle->iBackColour = colour2;
          // convert to RGB colour to start with in case only FORE or BACK supplied
          pStyle->iFlags &= ~COLOURTYPE;  // clear bits, eg. custom
          pStyle->iFlags |= COLOUR_RGB;

          // eg. <FONT COLOR=Red,Blink>
          CStringList list;

          strArgument = GetArgument (ArgumentList,"color", 1, true);  // get color etc.
          if (strArgument.IsEmpty () && PUEBLO_ACTIVE)
            strArgument = GetArgument (ArgumentList,"fgcolor", 1, true);  // get color
          StringToList (strArgument, ",", list);   // break into components

          for (POSITION pos = list.GetHeadPosition (); pos; )
            {
            CString strItem = list.GetNext (pos); // get action item

            if (strItem == "blink")
               pStyle->iFlags |= BLINK;
            else
            if (strItem == "italic")
               pStyle->iFlags |= BLINK;
            else
            if (strItem == "underline")
               pStyle->iFlags |= UNDERLINE;
            else
            if (strItem == "bold")
               pStyle->iFlags |= HILITE;
            else
            if (strItem == "inverse")
               pStyle->iFlags |= INVERSE;
            else
              {  // must be colour name, yes?

              // foreground colour
              if (!m_bIgnoreMXPcolourChanges)
                if (SetColour (strItem, pStyle->iForeColour)) 
                  MXP_error (DBG_ERROR, errMXP_UnknownColour,
                              TFormat ("Unknown colour: \"%s\"" ,
                                      (LPCTSTR) strItem));
              } // end of colour

            } // end of handling each item in the list
          strArgument = GetArgument (ArgumentList,"back", 2, true);  // get back color
          if (strArgument.IsEmpty () && PUEBLO_ACTIVE)
            strArgument = GetArgument (ArgumentList,"bgcolor", 2, true);  // get back color
          // background colour

          if (!m_bIgnoreMXPcolourChanges)
            if (SetColour (strArgument, pStyle->iBackColour)) 
              MXP_error (DBG_ERROR, errMXP_UnknownColour,
                        TFormat ("Unknown colour: \"%s\"" ,
                                  (LPCTSTR) strArgument));

          // get font size argument to avoid warnings about unused arguments
          strArgument = GetArgument (ArgumentList,"size", 0, true);  // get font size
          }
          break; // end of FONT

    case MXP_ACTION_VERSION:
            {

            CString strVersion = CFormat ("\x1B[1z<VERSION MXP=\"%s\" CLIENT=MUSHclient "
                      "VERSION=\"%s\" REGISTERED=YES>%s",
                     MXP_VERSION,
                     MUSHCLIENT_VERSION,
                     ENDLINE
                     );

            SendPacket (strVersion, strVersion.GetLength ());  // send version info back
            MXP_error (DBG_INFO, infoMXP_VersionSent,
                      TFormat ("Sent version response: %s" ,
                                (LPCTSTR) strVersion.Mid (4)));

            }
          break;  // end of VERSION

    case MXP_ACTION_AFK:
          if (m_bSendMXP_AFK_Response)    // if player wants us to
            {
            strArgument = GetArgument (ArgumentList,"challenge", 1, false);  // get challenge

            // find time since last player input
            CTimeSpan ts = CTime::GetCurrentTime() - m_tLastPlayerInput;
            CString strAFK = CFormat ("\x1B[1z<AFK %ld %s>%s",
                      ts.GetTotalSeconds  (),
                      (LPCTSTR) strArgument,
                      ENDLINE
                     );

            SendPacket (strAFK, strAFK.GetLength ());  // send AFK info back
            MXP_error (DBG_INFO, infoMXP_AFKSent,
                      TFormat ("Sent AFK response: %s" ,
                                (LPCTSTR) strAFK.Mid (4)));
            } // end of AFK
          break;

    case MXP_ACTION_SUPPORT:
            {
            CString strSupports;
            CAtomicElement * pElement;
            CStringList list;
            CString strName;       

            if (ArgumentList.IsEmpty ())
              {
              for (POSITION pos = App.m_ElementMap.GetStartPosition(); pos; ) 
                {                                                
                App.m_ElementMap.GetNextAssoc (pos, strName, pElement);

                if ((pElement->iFlags & TAG_NOT_IMP) == 0)
                  {
                  strSupports += "+";
                  strSupports += pElement->strName;
                  strSupports += " ";

                  // now list the sub-items it supports
                  StringToList (pElement->strArgs, ",", list);   // break into components
                  for (POSITION argpos = list.GetHeadPosition (); argpos; )
                    {
                    CString strItem = list.GetNext (argpos); // get argument item
                    strSupports += "+";
                    strSupports += pElement->strName;
                    strSupports += ".";
                    strSupports += strItem;
                    strSupports += " ";
                    } // end of doing each sub-item
                  } // end of being implemented
                }  // end of looping through all atomic elements
              } // end of wanting complete list
            else
              {
              for (POSITION pos = ArgumentList.GetHeadPosition (); pos; )
                {
                CArgument * pArgument = ArgumentList.GetNext (pos); 
                CStringList questionlist;
                StringToList (pArgument->strValue, ".", questionlist);   // break into components

                // should be one or two words, eg. send.prompt or color
                if (questionlist.GetCount () > 2)
                  {
                  MXP_error (DBG_ERROR, errMXP_InvalidSupportArgument,
                            TFormat ("Invalid <support> argument: %s" ,
                                      (LPCTSTR) pArgument->strValue));
                  return;
                  }
                
                CString strTag =  questionlist.RemoveHead ();
                strTag.MakeLower ();

                // check valid name requested
                if (!IsValidName (strTag))
                  {
                  MXP_error (DBG_ERROR, errMXP_InvalidSupportArgument,
                            TFormat ("Invalid <support> argument: %s" ,
                                      (LPCTSTR) strTag));
                  return;
                  }

                // look up main element name

                if (!App.m_ElementMap.Lookup (strTag, pElement) ||
                   (pElement->iFlags & TAG_NOT_IMP) != 0)
                  {     // not supported
                  strSupports += "-";
                  strSupports += strTag;
                  strSupports += " ";
                  continue;   // all done for this argument
                  }

                // only one word - they aren't looking for a suboption
                if (questionlist.IsEmpty ())
                  {     // supported
                  strSupports += "+";
                  strSupports += strTag;
                  strSupports += " ";
                  continue;   // all done for this argument
                  }
                  
                CString strSubtag =  questionlist.RemoveHead ();
                strSubtag.MakeLower ();

                if (strSubtag == "*")
                  {   // they want list of options for this tag
                  // now list the sub-items it supports
                  StringToList (pElement->strArgs, ",", list);   // break into components
                  for (POSITION argpos = list.GetHeadPosition (); argpos; )
                    {
                    CString strItem = list.GetNext (argpos); // get argument item
                    strSupports += "+";
                    strSupports += pElement->strName;
                    strSupports += ".";
                    strSupports += strItem;
                    strSupports += " ";
                    } // end of doing each sub-item
                  } // end of wildcard
                else
                  {  // not wildcard - must be name
                  // check valid name requested
                  if (!IsValidName (strSubtag))
                    {
                    MXP_error (DBG_ERROR, errMXP_InvalidSupportArgument,
                              TFormat ("Invalid <support> argument: %s" ,
                                        (LPCTSTR) strSubtag));
                    return;
                    }

                  // so, see if that word is in our arguments list
                  StringToList (pElement->strArgs, ",", list);   // break into components
                  if (list.Find (strSubtag))
                    {
                    strSupports += "+";
                    strSupports += pArgument->strValue;
                    strSupports += " ";
                    }
                  else
                    {
                    strSupports += "-";
                    strSupports += pArgument->strValue;
                    strSupports += " ";
                    }
                  }    // end of not looking for wildcard
                } // end of doing each argument

              } // find individual items

            CString strMessage = CFormat ("\x1B[1z<SUPPORTS %s>%s",
                                          (LPCTSTR) strSupports,
                                          ENDLINE);

            SendPacket (strMessage, strMessage.GetLength ());  // send version info back
            MXP_error (DBG_INFO, infoMXP_SupportsSent,
                      TFormat ("Sent supports response: %s" ,
                                (LPCTSTR) strMessage.Mid (4)));

            }
          bIgnoreUnusedArgs = true;

          break;  // end of MXP_ACTION_SUPPORT

    case MXP_ACTION_OPTION:
            {
            CString strOptions;
            CStringList list;
            CString strName;       

            if (ArgumentList.IsEmpty ())
              {

              for (long i = 0; OptionsTable [i].pName; i++)
                {
                char * pName = OptionsTable [i].pName;
                strOptions += CFormat ("%s=%ld ",
                               pName, 
                               (LPCTSTR) GetOptionItem (i));
                }

              } // end of wanting complete list
            else
              {
              for (POSITION pos = ArgumentList.GetHeadPosition (); pos; )
                {
                CArgument * pArgument = ArgumentList.GetNext (pos); 

                strOptions += CFormat ("%s=%ld",
                               (LPCTSTR) pArgument->strValue, 
                               (LPCTSTR) GetOption (pArgument->strValue));

                } // end of doing each argument

              } // find individual items

            CString strMessage = CFormat ("\x1B[1z<OPTIONS %s>%s",
                                          (LPCTSTR) strOptions,
                                          ENDLINE);

            SendPacket (strMessage, strMessage.GetLength ());  // send version info back
            MXP_error (DBG_INFO, infoMXP_OptionsSent,
                      TFormat ("Sent options response: %s" ,
                                (LPCTSTR) strMessage.Mid (4)));

            }
          bIgnoreUnusedArgs = true;

          break;  // end of MXP_ACTION_OPTION

    case MXP_ACTION_RECOMMEND_OPTION:
          if (m_bMudCanChangeOptions)
            {
            CString strOptions;
            CStringList list;
            CString strName;       

            for (POSITION pos = ArgumentList.GetHeadPosition (); pos; )
              {
              CArgument * pArgument = ArgumentList.GetNext (pos); 

              int iItem;
              int iResult = FindBaseOption (pArgument->strName, OptionsTable, iItem);

              if (iResult != eOK)
                MXP_error (DBG_ERROR, errMXP_InvalidOptionArgument,
                          TFormat ("Option named '%s' not known.",
                          (LPCTSTR) pArgument->strName));      
              else if (!(OptionsTable [iItem].iFlags & OPT_SERVER_CAN_WRITE))
                MXP_error (DBG_ERROR, errMXP_CannotChangeOption,
                          TFormat ("Option named '%s' cannot be changed.",
                          (LPCTSTR) pArgument->strName));      
              else
                {
                iResult = SetOptionItem (iItem, atol (pArgument->strValue), true, false);
                if (iResult == eOK)
                  MXP_error (DBG_INFO, infoMXP_OptionChanged,
                            TFormat ("Option named '%s' changed to '%s'.",
                            (LPCTSTR) pArgument->strName,
                            (LPCTSTR) pArgument->strValue)); 
                else
                  MXP_error (DBG_ERROR, errMXP_OptionOutOfRange,
                            TFormat ("Option named '%s' could not be changed to '%s' (out of range).",
                            (LPCTSTR) pArgument->strName,
                            (LPCTSTR) pArgument->strValue));      
                }

              } // end of doing each argument

            }
          bIgnoreUnusedArgs = true;

          break;  // end of MXP_ACTION_RECOMMEND_OPTION


    case MXP_ACTION_USER:
            if (!m_name.IsEmpty () && 
                m_connect_now == eConnectMXP)
              {
              CString strPacket = m_name + ENDLINE;
              SendPacket (strPacket, strPacket.GetLength ());  // send name to MUD
              MXP_error (DBG_INFO, infoMXP_CharacterNameSent,
                          TFormat ("Sent character name: %s" ,
                                  (LPCTSTR) m_name));      
              }
            else if (m_connect_now != eConnectMXP)
              MXP_error (DBG_WARNING, wrnMXP_CharacterNameRequestedButNotDefined,
                        Translate ("Character name requested but auto-connect not set to MXP."));      
            else
              MXP_error (DBG_WARNING, wrnMXP_CharacterNameRequestedButNotDefined,
                        Translate ("Character name requested but none defined."));      
            break;  // end of USER

    case MXP_ACTION_PASSWORD:
            if (m_nTotalLinesSent > 10)     // security check
              MXP_error (DBG_WARNING, wrnMXP_PasswordNotSent,
                        "Too many lines sent to MUD - password not sent.");      
            else
            if (!m_password.IsEmpty () && 
                m_connect_now == eConnectMXP)
              {
              CString strPacket = m_password + ENDLINE;
              SendPacket (strPacket, strPacket.GetLength ());  // send password to MUD
              MXP_error (DBG_INFO, infoMXP_PasswordSent,
                        "Sent password to world.");      
              }
            else if (m_connect_now != eConnectMXP)
              MXP_error (DBG_WARNING, wrnMXP_PasswordRequestedButNotDefined,
                        "Password requested but auto-connect not set to MXP.");      
            else
              MXP_error (DBG_WARNING, wrnMXP_PasswordRequestedButNotDefined,
                        "Password requested but none defined.");      
            break;  // end of PASSWORD

         // new para
    case MXP_ACTION_P:
          // experimental
          m_cLastChar = 0;
          m_bInParagraph = true;      
          break;  // end of MXP_ACTION_P
    
          // new line
    case MXP_ACTION_BR:
          bIgnoreUnusedArgs = true; // don't worry about args for now :)

          StartNewLine (true, 0);
          SetNewLineColour (0);
          break;  // end of MXP_ACTION_BR

          // reset
    case MXP_ACTION_RESET:
          MXP_Off ();
          break;  // end of MXP_ACTION_RESET

          // MXP options  (MXP OFF, MXP DEFAULT_OPEN, MXP DEFAULT_SECURE etc.
    case MXP_ACTION_MXP:
          
          if (GetKeyword (ArgumentList, "off"))
            MXP_Off (true);

          /*
          if (GetKeyword (ArgumentList, "default_open"))
            {
            MXP_error (DBG_INFO, "MXP default mode now OPEN.");
            m_iMXP_defaultMode = eMXP_open;
            }  // end of DEFAULT_OPEN

          if (GetKeyword (ArgumentList, "default_secure"))
            {
            MXP_error (DBG_INFO, "MXP default mode now SECURE.");
            m_iMXP_defaultMode = eMXP_secure;
            }  // end of DEFAULT_SECURE

          if (GetKeyword (ArgumentList, "default_locked"))
            {
            MXP_error (DBG_INFO, "MXP default mode now LOCKED.");
            m_iMXP_defaultMode = eMXP_locked;
            }  // end of DEFAULT_LOCKED


          if (GetKeyword (ArgumentList, "use_newlines"))
            {
            MXP_error (DBG_INFO, "Now interpreting newlines as normal.");
            m_bInParagraph = false;      
            }   // end of USE_NEWLINES

          if (GetKeyword (ArgumentList, "ignore_newlines"))
            {
            MXP_error (DBG_INFO, "Now ignoring newlines.");
            m_bInParagraph = true;      
            }   // end of IGNORE_NEWLINES

          */

          break;  // end of MXP_ACTION_MXP

    case MXP_ACTION_SCRIPT:
          MXP_error (DBG_INFO, infoMXP_ScriptCollectionStarted,
                      "Script collection mode entered (discarding script).");
          m_bMXP_script = true;
          break;  // end of MXP_ACTION_SCRIPT

    case MXP_ACTION_HR: 

          {
          // wrap up previous line if necessary
          if (m_pCurrentLine->len > 0)
             StartNewLine (true, 0);

          /*
          CString strLine;
          char * p = strLine.GetBuffer (m_nWrapColumn);
          memset (p, 175, m_nWrapColumn);
          strLine.ReleaseBuffer (m_nWrapColumn);
          AddToLine (strLine, 0);
          */
          // mark line as HR line
          m_pCurrentLine->flags = HORIZ_RULE;
          
          StartNewLine (true, 0); // now finish this line
          }
          break;  // end of MXP_ACTION_HR

    case MXP_ACTION_PRE: 
          m_bPreMode = true;
          break;  // end of MXP_ACTION_PRE

     case MXP_ACTION_UL:   
          m_iListMode = eUnorderedList;
          m_iListCount = 0;
          break;  // end of MXP_ACTION_UL
     case MXP_ACTION_OL:   
          m_iListMode = eOrderedList;
          m_iListCount = 0;
          break;  // end of MXP_ACTION_OL
     case MXP_ACTION_LI:   
         {
          // wrap up previous line if necessary
          if (m_pCurrentLine->len > 0)
             StartNewLine (true, 0);
          CString strListItem = " * ";
          if (m_iListMode == eOrderedList)
            strListItem.Format (" %i. ", ++m_iListCount);
          AddToLine (strListItem, 0);
          }
          break;  // end of MXP_ACTION_LI

    // pueblo tags we put here so we don't get warnings

      case MXP_ACTION_BODY : bIgnoreUnusedArgs = true; break; // just ignore it
      case MXP_ACTION_HEAD : bIgnoreUnusedArgs = true; break; // just ignore it
      case MXP_ACTION_HTML : bIgnoreUnusedArgs = true; break; // just ignore it
      case MXP_ACTION_TITLE: bIgnoreUnusedArgs = true; break; // just ignore it
      case MXP_ACTION_SAMP : bIgnoreUnusedArgs = true; break; // just ignore it
      case MXP_ACTION_CENTER : bIgnoreUnusedArgs = true; break; // just ignore it
      case MXP_ACTION_XCH_PANE : bIgnoreUnusedArgs = true; break; // just ignore it

      case MXP_ACTION_IMG  : 
      case MXP_ACTION_IMAGE:

        {
          GetKeyword (ArgumentList, "ismap"); // make sure we realise it is a keyword

          // detect newline treatment
          strArgument = GetArgument (ArgumentList,"xch_mode", 0, false);  // get mode
          if (!strArgument.IsEmpty ())
            {
            m_bPuebloActive = true;  // for correct newline processing
            if (strArgument.CompareNoCase ("purehtml") == 0)
               m_bSuppressNewline = true;
            else
            if (strArgument.CompareNoCase ("html") == 0)
               m_bSuppressNewline = false;
            } // end of some sort of Pueblo

          strArgument = GetArgument (ArgumentList,"url", 0, false);  // get link
          if (strArgument.IsEmpty () && PUEBLO_ACTIVE)   
            strArgument = GetArgument (ArgumentList,"src", 0, false);  // get link

          CString strFilename = GetArgument (ArgumentList,"fname", 0, false); // and file name

          if (!strArgument.IsEmpty ())
            {

            CString strOldAction = strAction;
            int iFlags = pStyle->iFlags;
            COLORREF iForeColour = pStyle->iForeColour;
            COLORREF iBackColour = pStyle->iBackColour;

            // ensure on new line
            if (m_pCurrentLine->len > 0)
               StartNewLine (true, 0);

            // starting a new line may have deleted pStyle

            pStyle = m_pCurrentLine->styleList.GetTail ();

            if (m_bUseCustomLinkColour)
              {
              pStyle->iForeColour = m_iHyperlinkColour;    // use hyperlink colour
              pStyle->iBackColour = colour2;
              pStyle->iFlags &= ~COLOURTYPE;  // clear bits, eg. custom
              pStyle->iFlags |= COLOUR_RGB;
              }

            strArgument += strFilename;   // append filename to URL
            strAction = strArgument;   // hyperlink
            pStyle->iFlags &= ~ACTIONTYPE;   // cancel old actions
            pStyle->iFlags |= ACTION_HYPERLINK;   // send-to action

            if (m_bUnderlineHyperlinks)
              pStyle->iFlags |= UNDERLINE;   // send-to action

            AddToLine ("[", 0);          
            AddToLine (strArgument, 0);
            AddToLine ("]", 0);

            // have to add the action now, before we start a new line
            pStyle->pAction = GetAction (strAction, strHint, strVariable);
            strAction.Empty ();

            StartNewLine (true, 0);   // new line after image tag
            // go back to old style (ie. lose the underlining)
            AddStyle (iFlags, 
                     iForeColour, 
                     iBackColour, 
                     0, 
                     strOldAction);

            }
        }
        break; // end of MXP_ACTION_IMG

    case MXP_ACTION_XCH_PAGE:
         bIgnoreUnusedArgs = true;
         m_bPuebloActive = true;  // for correct newline processing
         MXP_Off ();    // same as <reset>?
      break;  // end of MXP_ACTION_XCH_PAGE

    case MXP_ACTION_VAR: 
          // set variable

          strVariable = GetArgument (ArgumentList,"", 1, false);  // get name

          // case insensitive
          strVariable.MakeLower ();

          if (!IsValidName (strVariable))
            {
            MXP_error (DBG_ERROR, errMXP_InvalidDefinition,
                      TFormat ("Invalid MXP entity name: <!%s>", 
                      (LPCTSTR) strVariable)); 
            strVariable.Empty ();
            return;
            }

            { // protect local variable
            CString strEntityContents;

            if (App.m_EntityMap.Lookup (strVariable, strEntityContents))
              {
              MXP_error (DBG_ERROR, errMXP_CannotRedefineEntity,
                        TFormat ("Cannot redefine entity: &%s;", 
                        (LPCTSTR) strVariable)); 
              strVariable.Empty ();
              return;
              }
              }

          break;  // end of MXP_ACTION_VAR


    default:
          {
          // warn them it is not implemented
          MXP_error (DBG_WARNING, wrnMXP_TagNotImplemented,
                     TFormat ("MXP tag <%s> is not implemented" ,
                             (LPCTSTR) strTag));
          }   // end of default

    } // end of switch on iAction

  if (!bIgnoreUnusedArgs)
    CheckArgumentsUsed (strTag, ArgumentList);

  } // end of CMUSHclientDoc::MXP_OpenAtomicTag
 CTimeSpan ts1(10); // 10 seconds
 CTimeSpan ts2(100); // 100 seconds
 ts2 -= ts1;
 ATLASSERT(ts2.GetTotalSeconds() == 90);   
Ejemplo n.º 22
0
UINT GlobeFuns::TimeToInt( const CTime &t )
{
	CTimeSpan ts = t-CTime(0);
	return (UINT)ts.GetTotalSeconds();
}
Ejemplo n.º 23
0
BOOL RunService (LPCTSTR lpszServiceName, DWORD& dwError)
{
	SC_HANDLE  schSCManager;
	SC_HANDLE  schService;
	SERVICE_STATUS svrstatus;
	memset (&svrstatus, sizeof(svrstatus), 0);

	//
	// Connect to service control manager on the local machine and 
	// open the ServicesActive database
	schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if (schSCManager == NULL )
	{
		CString strMsg;
		dwError = GetLastError();
		
		switch (dwError)
		{
		case ERROR_ACCESS_DENIED:
		case ERROR_DATABASE_DOES_NOT_EXIST:
		case ERROR_INVALID_PARAMETER:
			//strMsg = _T("Failed to connect to the Service Control Manager");
			AfxMessageBox (VDBA_MfcResourceString(IDS_E_CONNECT_SERVICE));
			break;
		}
		return FALSE;
	}
	// 
	// Check if the Service 'lpszServiceName' is already installed
	// REGEDT32.EXE can check this on
	// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
	schService = OpenService (schSCManager, lpszServiceName, SERVICE_ALL_ACCESS);
	if (schService == NULL)
		return FALSE;

	if (!StartService (schService, 0, NULL))
	{
		dwError = GetLastError();
		return FALSE;
	}

	CTime tStarted = CTime::GetCurrentTime();
	CTime t = CTime::GetCurrentTime();
	CTimeSpan tdiff  = t - tStarted;
	int   nTotalSecods = 0;
	// 
	// Check if the Service 'lpszServiceName' is Running
	if (!QueryServiceStatus (schService, &svrstatus))
	{
		//CString strMsg = _T("Cannot query the service status information");
		AfxMessageBox (VDBA_MfcResourceString(IDS_E_SERVICE_STATUS));
		dwError = GetLastError();
		return FALSE;
	}
	//
	// Maximum time 20 seconds waiting for the service finishs starting.
	while (svrstatus.dwCurrentState == SERVICE_START_PENDING && nTotalSecods < 20)
	{
		Sleep (200);
		QueryServiceStatus (schService, &svrstatus);
		if (svrstatus.dwCurrentState == SERVICE_RUNNING)
			return TRUE;
		t = CTime::GetCurrentTime();
		tdiff  = t - tStarted;
		nTotalSecods = (int)tdiff.GetTotalSeconds();
	}
	QueryServiceStatus (schService, &svrstatus);
	if (svrstatus.dwCurrentState =! SERVICE_RUNNING)
	{
		dwError = GetLastError();
		return FALSE;
	}
	else
		return TRUE;
}
Ejemplo n.º 24
0
/////////////////////////////////////////////////////////////////////////////
// Member-Funktion CTransferSocket
void CTransferSocket::OnReceive(int nErrorCode)
{
	if (GetState() != connected && GetState() != attached && GetState() != closed)
		return;
	if (m_nTransferState == STATE_WAITING)
	{
		m_nNotifyWaiting |= FD_READ;
		return;
	}

	if (m_bSentClose)
		return;
	if (m_bListening)
		return;

	if (m_nMode&CSMODE_LIST)
	{
		if (m_nTransferState == STATE_STARTING)
			OnConnect(0);

		char *buffer = static_cast<char *>(nb_calloc(1, BUFSIZE));
		int numread = CAsyncSocketEx::Receive(buffer, BUFSIZE);
		if (numread != SOCKET_ERROR && numread)
		{
			m_LastActiveTime = CTime::GetCurrentTime();
			UpdateRecvLed();

#ifndef MPEXT_NO_ZLIB
			if (m_useZlib)
			{
				m_zlibStream.next_in = (Bytef *)buffer;
				m_zlibStream.avail_in = numread;
				char *out = static_cast<char *>(nb_calloc(1, BUFSIZE));
				m_zlibStream.next_out = (Bytef *)out;
				m_zlibStream.avail_out = BUFSIZE;
				int res = inflate(&m_zlibStream, 0);
				while (res == Z_OK)
				{
					m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
					out = static_cast<char *>(nb_calloc(1, BUFSIZE));
					m_zlibStream.next_out = (Bytef *)out;
					m_zlibStream.avail_out = BUFSIZE;
					res = inflate(&m_zlibStream, 0);
				}
				nb_free(buffer);
				if (res == Z_STREAM_END)
					m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
				else if (res != Z_OK && res != Z_BUF_ERROR)
				{
					nb_free(out);
					CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
					return;
				}
				else
					nb_free(out);
			}
			else
#endif
				m_pListResult->AddData(buffer, numread);
			m_transferdata.transfersize += numread;
			CTimeSpan timespan = CTime::GetCurrentTime() - m_StartTime;
			int elapsed = (int)timespan.GetTotalSeconds();
			//TODO
			//There are servers which report the total number of
			//bytes in the list response message, but yet it is not supported by FZ.
			/*double leftmodifier=(transfersize-transferstart-transferleft);
			leftmodifier*=100;
			leftmodifier/=(transfersize-transferstart);
			if (leftmodifier==0)
				leftmodifier=1;
			double leftmodifier2=100-leftmodifier;
			int left=(int)((elapsed/leftmodifier)*leftmodifier2);
			int percent=MulDiv(100,transfersize-transferleft,transfersize);*/
			int transferrate=static_cast<int>( (elapsed && m_transferdata.transfersize)?m_transferdata.transfersize/elapsed:0 );
			t_ffam_transferstatus *status = new t_ffam_transferstatus;
			status->bFileTransfer = FALSE;
#ifdef MPEXT
			status->transfersize = -1;
#endif
			status->bytes = m_transferdata.transfersize;
			status->percent = -1;
			status->timeelapsed = elapsed;
			status->timeleft = -1;
			status->transferrate = transferrate;
			PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
		}
		else
			nb_free(buffer);
		if (!numread)
		{
			CloseAndEnsureSendClose(0);
		}
		if (numread == SOCKET_ERROR)
		{
			int nError = GetLastError();
			if (nError == WSAENOTCONN)
			{
				//Not yet connected
				return;
			}
#ifndef MPEXT_NO_SSL
			else if (m_pSslLayer && nError == WSAESHUTDOWN)
			{
				// Do nothing, wait for shutdown complete notification.
				return;
			}
#endif
			else if (nError != WSAEWOULDBLOCK)
			{
				LogError(nError);
				CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
			}
		}
	}
	else if (m_nMode & CSMODE_DOWNLOAD)
	{
		if (m_nTransferState == STATE_STARTING)
			OnConnect(0);

		bool beenWaiting = false;
		_int64 ableToRead;
		if (GetState() != closed)
			ableToRead = m_pOwner->GetAbleToTransferSize(CControlSocket::download, beenWaiting);
		else
			ableToRead = BUFSIZE;

		if (!beenWaiting)
			ASSERT(ableToRead);
		else if (!ableToRead)
		{
			TriggerEvent(FD_READ);
			return;
		}

		if (!m_pBuffer)
			m_pBuffer = static_cast<char *>(nb_calloc(1, BUFSIZE));

		int numread = CAsyncSocketEx::Receive(m_pBuffer, static_cast<int>(ableToRead));
		if (numread!=SOCKET_ERROR)
		{
			Transfered( numread, CTime::GetCurrentTime());
			m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::download, numread);
		}

		if (!numread)
		{
			CloseAndEnsureSendClose(0);
			return;
		}

		if (numread == SOCKET_ERROR)
		{
			int nError = GetLastError();
			if (nError == WSAENOTCONN)
			{
				//Not yet connected
				return;
			}
#ifndef MPEXT_NO_SSL
			else if (m_pSslLayer && nError == WSAESHUTDOWN)
			{
				// Do nothing, wait for shutdown complete notification.
				return;
			}
#endif
			else if (nError != WSAEWOULDBLOCK)
			{
				LogError(nError);
				CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
			}

			UpdateStatusBar(false);
			return;
		}

		int written = 0;
		m_LastActiveTime = CTime::GetCurrentTime();
		UpdateRecvLed();
		TRY
		{
#ifndef MPEXT_NO_ZLIB
			if (m_useZlib)
			{
				if (!m_pBuffer2)
					m_pBuffer2 = static_cast<char *>(nb_calloc(1, BUFSIZE));

				m_zlibStream.next_in = (Bytef *)m_pBuffer;
				m_zlibStream.avail_in = numread;
				m_zlibStream.next_out = (Bytef *)m_pBuffer2;
				m_zlibStream.avail_out = BUFSIZE;
				int res = inflate(&m_zlibStream, 0);
				while (res == Z_OK)
				{
					m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
					written += BUFSIZE - m_zlibStream.avail_out;
					m_zlibStream.next_out = (Bytef *)m_pBuffer2;
					m_zlibStream.avail_out = BUFSIZE;
					res = inflate(&m_zlibStream, 0);
				}
				if (res == Z_STREAM_END)
				{
					m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
					written += BUFSIZE - m_zlibStream.avail_out;
				}
				else if (res != Z_OK && res != Z_BUF_ERROR)
				{
					m_pOwner->ShowStatus(L"Compression error", FZ_LOG_ERROR);
					CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
					return;
				}
			}
			else
#endif
			{
				m_pFile->Write(m_pBuffer, numread);
				written = numread;
			}
		}
		CATCH(CFileException,e)
		{
			LPTSTR msg = static_cast<TCHAR *>(nb_calloc(BUFSIZE, sizeof(TCHAR)));
			if (e->GetErrorMessage(msg, BUFSIZE))
				m_pOwner->ShowStatus(msg, FZ_LOG_ERROR);
			nb_free(msg);
			CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
			return;
		}
		END_CATCH;
		m_transferdata.transferleft -= written;

		UpdateStatusBar(false);
	}
Ejemplo n.º 25
0
BOOL CTRONETHERSTATUS_MONITOR(char *server, int port, char *community, CString strIndex, 
			int rdelay, int timeout, int ngid, int nmid, char *cpath, char *szReturn)
{
	int		s;
	struct	sockaddr_in serv;

	int		i = 0, j = 0, ret = 0;
	int		count = 1;
	struct	snval *ptmp = NULL;
	struct	snval *ptmpnext = NULL;

	u_int	_64Octets = 0, _65to127Octets = 0;
	u_int	_Curr64Octets = 0, _Curr65to127Octets = 0;

	if((ret = MakeSocket(server, port, s, serv)) < 0)
	{
		if(ret == -1)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_1%>"));//<%IDS_CheckPoint_1%>
		else if(ret == -2)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_2%>"));//<%IDS_CheckPoint_2%>
		else
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_3%>"));//<%IDS_CheckPoint_3%>

		return FALSE;
	}

	long index_id[32];
	int	 index_id_c = 0;
	while(1)
	{
		i = strIndex.Find('.', 0);
		if(i > 0)
			index_id[index_id_c++] = atoi(strIndex);
		else if(i < 0 && strIndex.GetLength() > 0)
		{
			index_id[index_id_c++] = atoi(strIndex);
			break;
		}
		else
			break;

		strIndex.Delete(0, i + 1);
	}

	for(i = 0;i < index_id_c;i ++)
	{
		etherStatsPkts64Octets.id[etherStatsPkts64Octets.len++] = index_id[i];
		etherStatsPkts65to127Octets.id[etherStatsPkts65to127Octets.len ++] = index_id[i];
	}

	struct oid *poid = NULL, *ptmpoid = NULL;
	poid = ptmpoid = &etherStatsPkts64Octets;
	ptmpoid->next = &etherStatsPkts65to127Octets;
	ptmpoid = ptmpoid->next;

	struct snval *psnval = NULL;
	if((ret = SN_VALUES(s, serv, community, 1, poid, &psnval)) < 0)
	{
		if(ret == -1)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_4%>"));//<%IDS_CheckPoint_4%>
		else if(ret == -2)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_5%>"));//<%IDS_CheckPoint_5%>
		else if(ret == -3)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_6%>"));//<%IDS_CheckPoint_6%>
		else if(ret == -4)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_7%>"));//<%IDS_CheckPoint_7%>
		else if(ret == -5)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_8%>"));//<%IDS_CheckPoint_8%>
		else if(ret == -6)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_9%>"));//<%IDS_CheckPoint_9%>
		else if(ret == -7)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_10%>"));//<%IDS_CheckPoint_10%>
		else if(ret == -8)
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_11%>"));//<%IDS_CheckPoint_11%>
		else
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("<%IDS_CheckPoint_12%>"));//<%IDS_CheckPoint_12%>

		goto w;
	}

	_Curr64Octets = psnval->sv_val.sv_int;
	_Curr65to127Octets = psnval->next->sv_val.sv_int;

	{
	char ciniFile[256] = {0}, 
		 cinifile[256] = {0};
	char cifIndex[256] = {0};
	sprintf(cinifile, "ctron_%s_%d_%d.ini", server, ngid, nmid);
	sprintf(ciniFile, "%s\\%s", cpath, cinifile);
	sprintf(cifIndex, "ifIndex_%s", strIndex);

	long	ifTime = 0;
	CTime	curTime = CTime::GetCurrentTime();

	ifTime = DFN_GetPrivateProfileInt(cifIndex, "ifTime", 0, ciniFile);
	_64Octets = DFN_GetPrivateProfileInt(cifIndex, "_64Octets", 0, ciniFile);
	_65to127Octets = DFN_GetPrivateProfileInt(cifIndex, "_65to127Octets", 0, ciniFile);

	if(ifTime == 0 && _64Octets == 0 && _65to127Octets == 0)
	{
		CString strSection = _T("");
		strSection.Format("ifIndex_%s", strIndex);

		CString strMsg = _T("");
		strMsg.Format("%ld", curTime.GetTime());
		::DFN_WritePrivateProfileString((LPCTSTR)strSection, "ifTime", (LPCTSTR)strMsg, ciniFile);

		strMsg.Format("%ld", _Curr64Octets);
		::DFN_WritePrivateProfileString((LPCTSTR)strSection, "_64Octets", (LPCTSTR)strMsg, ciniFile);

		strMsg.Format("%ld", _Curr65to127Octets);
		::DFN_WritePrivateProfileString((LPCTSTR)strSection, "_65to127Octets", (LPCTSTR)strMsg, ciniFile);
	}
	else
	{
		float	_Rate64Octets = 0.0, _Rate65to127Octets = 0.0;
		Counter	_Delta64Octets = 0, _Delta65to127Octets = 0;

		CTime bTime(ifTime);
		CTimeSpan spanTime = curTime - bTime;
		long lInterval = spanTime.GetTotalSeconds();
		
		if(lInterval == 0) lInterval = 1;
		if(lInterval <= 12 * 60 * 60 && lInterval > 0)
		{
			_Delta64Octets = (unsigned int)(_Curr64Octets - _64Octets < 0 ? (COUNTER_MAX - _64Octets + _Curr64Octets) : (_Curr64Octets - _64Octets));
			_Rate64Octets = (float)_Delta64Octets / lInterval;

			_Delta65to127Octets = (unsigned int)(_Curr65to127Octets - _65to127Octets < 0 ? (COUNTER_MAX - _65to127Octets + _Curr65to127Octets) : (_Curr65to127Octets - _65to127Octets));
			_Rate65to127Octets = (float)_Delta65to127Octets / lInterval;

			sprintf(szReturn, "_Rate64Octets=%.2f$_Rate65to127Octets=%.2f$",
					_Rate64Octets, _Rate65to127Octets);
		}

		char buff[256] = {0};
		memset(buff, 0, 256);
		ltoa(curTime.GetTime(), buff, 10);
		DFN_WritePrivateProfileString(cifIndex, "ifTime", buff, ciniFile);
		memset(buff, 0, 256);
		ltoa(_Curr64Octets, buff, 10);
		DFN_WritePrivateProfileString(cifIndex, "_64Octets", buff, ciniFile);
		memset(buff, 0, 256);
		ltoa(_Curr65to127Octets, buff, 10);
		DFN_WritePrivateProfileString(cifIndex, "_65to127Octets", buff, ciniFile);
	}
	}

w:	ptmp = psnval;
	if(ptmp) ptmpnext = ptmp->next;
	while(ptmp)
	{
		free(ptmp);
		ptmp = ptmpnext;
		if(ptmp) ptmpnext = ptmp->next;
	}

	return !ret;
}
Ejemplo n.º 26
0
void CFdDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add storing code here
		ElapsedTime = CTime::GetCurrentTime() - StartTime;
		ae->ElapsedTime += ElapsedTime.GetTotalSeconds();
		ae->NumberOfPaints += NumberOfPaints;
		StartTime = CTime::GetCurrentTime();
		NumberOfPaints = 0L;
		ar.Write((void far *)ae, sizeof(ACKENG));
		TRACE("...Game Saved...\n");
		if (fds) fds->TextMsg("Game Saved");
		DocAction = -1;
	}
	else
	{
		// TODO: add loading code here
HGLOBAL		haet;
ACKENG		*aet;
		haet = GlobalAlloc(GMEM_MOVEABLE|GMEM_SHARE, sizeof(ACKENG));
		if (haet == NULL)
		{
			TRACE("GlobalAlloc in CFdDoc of temporary ACKENG struct failed\n");
			return;
		}
		aet = (ACKENG far *)GlobalLock(haet);
		if (ar.GetFile()->GetLength() == sizeof(ACKENG))
		{
			ar.Read((void far *)aet, sizeof(ACKENG));
			if (aet->Version == AE_VERSION && lstrcmp(aet->Descriptor,AE_DESCRIPTOR) == 0)
			{
				memmove((void far *)ae, (void far *)aet, sizeof(ACKENG));
				//	Initialize weapons ammo pointers
				ae->WeaponsCarried[0].Ammo = &ae->Fists;
				ae->WeaponsCarried[1].Ammo = &ae->Bullets;
				ae->WeaponsCarried[2].Ammo = &ae->Shells;
				ae->WeaponsCarried[3].Ammo = &ae->Bullets;
				ae->WeaponsCarried[4].Ammo = &ae->Rockets;
				if (!ae->ObjList[PLAYER_OBJECT].Dead)
						ViewUpDown = 32 << (8 - ViewLowRes);
				TRACE("...Game Loaded...\n");
				if (fds)
				{
					fds->TextHealth();
					fds->TextAmmo();
					fds->TextMsg("Game Loaded");
					fds->DrawKeys();
				}
				StartTime = CTime::GetCurrentTime();
				NumberOfPaints = 0L;
				OurView->GetParentFrame()->SetWindowText("WinAdv");
				if (fdm) fdm->InvalidateRect(NULL,FALSE);
				DocAction = 1;
			}
			else
			{
				AfxMessageBox("Saved file format does not match\n");
				TRACE("Saved file format does not match\n");
			}
		}
		else
		{
			AfxMessageBox("Saved file size is not compatible\n");
			TRACE("Saved file size is not compatible\n");
		}
		GlobalUnlock(haet);
		GlobalFree(haet);
	}
}
Ejemplo n.º 27
0
inline
void Star::generate()
{
   //player info
  ShipTechs selfTechs;
  selfTechs.Weapon = data_->GetResearchLevel(RESEARCH_WEAPON);
  selfTechs.Shield = data_->GetResearchLevel(RESEARCH_SHEILED);
  selfTechs.Armour = data_->GetResearchLevel(RESEARCH_ARMOUR);
  uchar computer_rank = data_->GetLoginedAccountComputerRank();
  double account_rank = data_->GetLoginedAccountRank();
  ////enemy star information
  //random create fleets and defenses
  fleet_and_defense_.clear();
  float seed = 1000.0;
  switch(computer_rank)
  {
  case COMPUTER_T_MID:
    seed = 3000.0;
    break;
  case COMPUTER_T_LOW:
    seed = 6000.0;
    break;
  }
  CTime curT = CTime::GetCurrentTime();
  CTimeSpan span = curT - data_->REGISTER_TIME();
  long register_seconds = span.GetTotalSeconds();
  assert(register_seconds >= 0);
  if(register_seconds < 0) register_seconds = 0;
  //on line time ratio
  //high: 24 hours one day
  double online_ratio = 1.0;
  //mid: 12 hours one day
  if(computer_rank == COMPUTER_T_MID)
  {
    online_ratio = 0.6;
  }
  //low: 5 hours one day
  else if(computer_rank == COMPUTER_T_LOW)
  {
    online_ratio = 0.3;
  }
  double base_rank = pow(register_seconds * online_ratio / 3600.0 , 2.2) * pow(_speed_adjust_ , 1.4); 

  //computer AI setting
  UINT base = 0;
  //by time
  if(data_->COMPUTER_AI_MODE() == COM_AI_T_BY_TIME)
  {
    base = base_rank   / 5678.0;
  }
  //by player
  else
  {
    base = account_rank / seed;
  }

  //random
  int temp = RandomNumber(100);
  //3%: no fleets and defense: 0-2
  if(temp < COMPUTER_T_HIGH + 2 - computer_rank)
  {
    base = 1;
  }
  //5% percent, fewest fleet and defense, 3~8
  else if(temp >= 3 && temp < 8)
  {
    base = UINT(base / 6.0);
  }
  //5% percent, fewer fleet and defense, 8~13
  else if(temp >= 8 && temp < 13)
  {
    base = UINT(base / 4.0);
  }
  //5% percent, few fleet and defense, 13~18
  else if(temp >= 13 && temp < 18)
  {
    base = UINT(base / 2.0);
  }
  //5% percent, many fleet and defense, 85~90
  else if(temp >= 85 && temp < 90)
  {
    base = UINT(base * 2.0);
  }
  //5% percent, more fleet and defense, 90~95
  else if(temp >= 90 && temp < 95)
  {
    base = UINT(base * 4.0);
  }
  //5% percent, most many fleet and defense, 95~99
  else if(temp >= 95 && temp < 100)
  {
    base = UINT(base * 6.0);    
  }
  //%67 normal
  else
  {
  }

  base = (base == 0 ? 1 : base);
  SItem item;
  item.OwnerID = 0;
  //S.C    
  item.Type    = T_KT;
  item.Num     = RandomNumber(base * 3);
  fleet_and_defense_.push_back(item);
  //L.C
  item.Type    = T_GT;
  item.Num     = RandomNumber(base);
  fleet_and_defense_.push_back(item);
  //L.F
  item.Type    = T_LJ;
  item.Num     = RandomNumber(base * 50);
  fleet_and_defense_.push_back(item);
  //H.F
  item.Type    = T_SJ;
  item.Num     = RandomNumber(base * 10);
  fleet_and_defense_.push_back(item);
  //C.L
  item.Type    = T_KREUZER;
  item.Num     = RandomNumber(base * 4);
  fleet_and_defense_.push_back(item);
  //BB
  item.Type    = T_SS;
  item.Num     = RandomNumber(base * 4);
  fleet_and_defense_.push_back(item);
  //Colony
  item.Type    = T_KOLO;
  item.Num     = RandomNumber(10);
  fleet_and_defense_.push_back(item);
  //Recycle
  item.Type    = T_REC;
  item.Num     = RandomNumber(base);
  fleet_and_defense_.push_back(item);
  //spy
  item.Type    = T_SPIO;
  item.Num     = RandomNumber(base / 10.0 + 1);
  fleet_and_defense_.push_back(item);
  //bomber
  item.Type    = T_BOMBER;
  item.Num     = RandomNumber(base);
  fleet_and_defense_.push_back(item);
  //solar ship
  item.Type    = T_SAT;
  item.Num     = RandomNumber(base / 5.0 + 1);
  fleet_and_defense_.push_back(item);
  //destroyer
  item.Type    = T_ZER;
  item.Num     = RandomNumber(base);
  fleet_and_defense_.push_back(item);
  //ds
  item.Type    = T_TS;
  item.Num     = RandomNumber(base / 200.0 + 1);
  fleet_and_defense_.push_back(item);

  //Missile Launcher
  item.Type    = T_RAK;
  item.Num     = RandomNumber(base * 15);
  fleet_and_defense_.push_back(item);

  //Small Laser
  item.Type    = T_LL;
  item.Num     = RandomNumber(base * 15);
  fleet_and_defense_.push_back(item);

  //heavy Laser
  item.Type    = T_SL;
  item.Num     = RandomNumber(base / 5.0 + 1);
  fleet_and_defense_.push_back(item);

  //Gauss
  item.Type    = T_GAUSS;
  item.Num     = RandomNumber(base / 10.0 + 1);
  fleet_and_defense_.push_back(item);

  //ION
  item.Type    = T_IONEN;
  item.Num     = RandomNumber(base / 10.0 + 1);
  fleet_and_defense_.push_back(item);

  //PC
  item.Type    = T_PLASMA;
  item.Num     = RandomNumber(base / 20.0 + 1);
  fleet_and_defense_.push_back(item);

  //Small Shield Dome
  item.Type    = T_KS;
  item.Num     = RandomNumber(2);
  fleet_and_defense_.push_back(item);

  //LARGE Shield Dome
  item.Type    = T_GS;
  item.Num     = RandomNumber(2);
  fleet_and_defense_.push_back(item);

  assert(fleet_and_defense_.size() == T_END);
  //special 3% or less than 30 score no fleets and defense, i
  if(register_seconds == 0 || RandomNumber(100) < 3 || account_rank < 500.0)
  {
    for(int i = T_KT ; i < T_END ; ++i)
    {
      fleet_and_defense_[i].Num = 0;
    }
  }
  //calc fleet number
  fleet_number_ = 0L;
  for(int i = T_KT ; i < T_RAK ; ++i)
  {
    fleet_number_ += fleet_and_defense_[i].Num;
  }

  //calc score
  Res worth = kernel_.GetFleetWorth(&fleet_and_defense_);
  UINT t = RandomNumber(30) + 60;//60% ~ 90%
  rank_  = (worth.met + worth.deut + worth.kris) / 1000.0 * (100.0 / t);

  //resource
  metal_    = pow(_speed_adjust_ , 0.3) * pow(2 , COMPUTER_T_HIGH - computer_rank) * ( pow(rank_ , 0.6) + 100) * RandomNumber(MAX_RESOURCE_BASE);
  crystal_  = pow(_speed_adjust_ , 0.3) * pow(2 , COMPUTER_T_HIGH - computer_rank) * ( pow(rank_ , 0.6) + 100) * RandomNumber(UINT(MAX_RESOURCE_BASE / 1.5));
  diplogen_ = pow(_speed_adjust_ , 0.3) * pow(2 , COMPUTER_T_HIGH - computer_rank) * ( pow(rank_ , 0.6) + 100) * RandomNumber(UINT(MAX_RESOURCE_BASE / 2.5));

  ////tech and elapsed percent
  spy_level_     = RandomNumber(data_->GetResearchLevel(RESEARCH_SPY) + pow(4 , computer_rank));
  elpase_        = RandomNumber(250 * (1 + computer_rank)) / 1000.0;

  //special 4%: resource much, elpase_ * 2
  if(RandomNumber(100) < COMPUTER_T_HIGH + 3 - computer_rank)
  {
    metal_    *= (50 * pow(2 , computer_rank));
    crystal_  *= (50 * pow(2 , computer_rank));
    diplogen_ *= (50 * pow(2 , computer_rank));
    elpase_   *= pow(2 , computer_rank);    
  }
  elpase_    = elpase_ > 1 ? 1.0 : elpase_;

  //max resource
  ulong max_res = 200000000 * pow(2 , computer_rank) * pow(_speed_adjust_ , 0.3);
  metal_    = metal_    > max_res ? max_res : metal_;
  crystal_  = crystal_  > max_res ? max_res : crystal_;
  diplogen_ = diplogen_ > max_res ? max_res : diplogen_;

  //techs
  ship_techs_.Armour = RandomNumber(selfTechs.Weapon + pow(3 , computer_rank));
  ship_techs_.Shield = RandomNumber(selfTechs.Weapon + pow(3 , computer_rank));
  ship_techs_.Weapon = RandomNumber(selfTechs.Weapon + pow(3 , computer_rank));
}
Ejemplo n.º 28
0
void CMUSHclientDoc::CheckTimers ()
  {

  // make sure status line is showing the right thing (after 5 seconds)
  if (m_pActiveCommandView || m_pActiveOutputView)
    {
    CTimeSpan ts = CTime::GetCurrentTime() - m_tStatusDisplayed;
    if (ts.GetTotalSeconds () > 5)
      ShowStatusLine ();
    }   // end of this being the active world

  // flush log file to disk every 2 minutes
  if (m_logfile)
    {
    CTimeSpan ts = CTime::GetCurrentTime() - m_LastFlushTime;

    // flush every 2 minutes
    if (ts.GetTotalSeconds () > 120.0)
      {
      m_LastFlushTime = CTime::GetCurrentTime();
//      fflush (m_logfile);
      
      fclose (m_logfile);
      m_logfile = fopen (m_logfile_name, "a+");

      }

    }   // end of log file open
  
// if reconnection wanted, attempt it now ...

// if they want automatic reconnection, do it

  if (App.m_bReconnectOnLinkFailure && 
      !m_bDisconnectOK &&
      m_iConnectPhase == eConnectNotConnected)
    {
    Frame.SetStatusMessage (Translate ("Reconnecting ..."));
    ConnectSocket();      // reconnect
    }

  if (m_bEnableTimers)
    {

    // timer has kicked in unexpectedly - ignore it
    if (m_CurrentPlugin)
      return;

    CheckTimerList (GetTimerMap ());
    // do plugins
   for (PluginListIterator pit = m_PluginList.begin (); 
         pit != m_PluginList.end (); 
         ++pit)
      {
      m_CurrentPlugin = *pit;
      if (m_CurrentPlugin->m_bEnabled)
        CheckTimerList (GetTimerMap ());
      } // end of doing each plugin
    m_CurrentPlugin = NULL;
    }
  } // end of CMUSHclientDoc::CheckTimers
Ejemplo n.º 29
0
// Receives up to Len bytes of data and returnds the amount received - or SOCKET_ERROR if it times out
int CPassiveSock::Recv(void * const lpBuf, const int Len)
{
    WSABUF buffer;
    WSAEVENT hEvents[2] = {NULL,NULL};
    DWORD
    bytes_read = 0,
    dwWait = 0,
    msg_flags = 0;
    int rc;

    // Setup up the events to wait on
    hEvents[1] = read_event;
    hEvents[0] = m_hStopEvent;

    if (RecvInitiated)
    {
        // Special case, the previous read timed out, so we are trying again, maybe it completed in the meantime
        rc = SOCKET_ERROR;
        LastError = WSA_IO_PENDING;
    }
    else
    {
        // Normal case, the last read completed normally, now we're reading again

        // Setup the buffers array
        buffer.buf = static_cast<char*>(lpBuf);
        buffer.len = Len;

        // Create the overlapped I/O event and structures
        memset(&os, 0, sizeof(OVERLAPPED));
        os.hEvent = hEvents[1];
        WSAResetEvent(os.hEvent);
        RecvInitiated = true;
        rc = WSARecv(ActualSocket, &buffer, 1, &bytes_read, &msg_flags, &os, NULL); // Start an asynchronous read
        LastError=WSAGetLastError();
    }
    if ((rc == SOCKET_ERROR) && (LastError == WSA_IO_PENDING))  // Read in progress, normal case
    {
        CTimeSpan TimeLeft = RecvEndTime - CTime::GetCurrentTime();
        if (TimeLeft.GetTotalSeconds() <= 0)
            dwWait = WAIT_TIMEOUT;
        else
            dwWait = WaitForMultipleObjects(2, hEvents, false, (DWORD)TimeLeft.GetTotalSeconds()*1000);
        if (dwWait == WAIT_OBJECT_0+1)
        {
            RecvInitiated = false;
            if (WSAGetOverlappedResult(ActualSocket, &os, &bytes_read, true, &msg_flags) && (bytes_read > 0))
                return bytes_read; // Normal case, we read some bytes, it's all good
            else
            {   // A bad thing happened
                int e = WSAGetLastError();
                if (e == 0) // The socket was closed
                    return 0;
            }
        }
    }
    else if (!rc) // if rc is zero, the read was completed immediately
    {
        RecvInitiated = false;
        if (WSAGetOverlappedResult(ActualSocket, &os, &bytes_read, true, &msg_flags) && (bytes_read > 0))
            return bytes_read; // Normal case, we read some bytes, it's all good
    }
    return SOCKET_ERROR;
}
Ejemplo n.º 30
0
/*
			等待5秒
*/
int CHTMLViewCapView::RunModalLoop(DWORD dwFlags)
{
			ASSERT(::IsWindow(m_hWnd)); // window must be created
			ASSERT(!(m_nFlags & WF_MODALLOOP)); // window must not already be in modal state

			// for tracking the idle time state
			BOOL bIdle = TRUE;
			LONG lIdleCount = 0;
			BOOL bShowIdle = (dwFlags & MLF_SHOWONIDLE) && !(GetStyle() & WS_VISIBLE);
			HWND hWndParent = ::GetParent(m_hWnd);
			m_nFlags |= (WF_MODALLOOP|WF_CONTINUEMODAL);
			MSG *pMsg = AfxGetCurrentMessage();

			// acquire and dispatch messages until the modal state is done
			for (;;)
			{
				ASSERT(ContinueModal());

				// phase1: check to see if we can do idle work
				while (bIdle &&
					!::PeekMessage(pMsg, NULL, NULL, NULL, PM_NOREMOVE))
				{
					ASSERT(ContinueModal());

					// show the dialog when the message queue goes idle
					if (bShowIdle)
					{
						ShowWindow(SW_SHOWNORMAL);
						UpdateWindow();
						bShowIdle = FALSE;
					}

					// call OnIdle while in bIdle state
					if (!(dwFlags & MLF_NOIDLEMSG) && hWndParent != NULL && lIdleCount == 0)
					{
						// send WM_ENTERIDLE to the parent
						::SendMessage(hWndParent, WM_ENTERIDLE, MSGF_DIALOGBOX, (LPARAM)m_hWnd);
					}
					if ((dwFlags & MLF_NOKICKIDLE) ||
						!SendMessage(WM_KICKIDLE, MSGF_DIALOGBOX, lIdleCount++))
					{
						// stop idle processing next time
						bIdle = FALSE;
					}
				}

				// Get current time
				//CTime tBeginLoop;
				CTime tEndLoop;
				CTimeSpan span;
				BOOL bQuit = FALSE;

				// phase2: pump messages while available
				do
				{
					ASSERT(ContinueModal());
					TRACE("pump messages!\n");

					//
					//tBeginLoop = CTime::GetCurrentTime();

					// pump message, but quit on WM_QUIT
					if (!AfxPumpMessage())
					{
						AfxPostQuitMessage(0);
						return -1;
					}

					// show the window when certain special messages rec'd
					if (bShowIdle &&
						(pMsg->message == 0x118 || pMsg->message == WM_SYSKEYDOWN))
					{
						ShowWindow(SW_SHOWNORMAL);
						UpdateWindow();
						bShowIdle = FALSE;
					}

					if (!ContinueModal() || bQuit)
						goto ExitModal;

					// reset "no idle" state after pumping "normal" message
					if (AfxIsIdleMessage(pMsg))
					{
						bIdle = TRUE;
						lIdleCount = 0;
					}

					tEndLoop = CTime::GetCurrentTime();
					span =  tEndLoop - m_tBeforeEnterLoop;
					TRACE("Span : %d .\n", span.GetTotalSeconds());
					if (span.GetTotalSeconds() >= m_wating_time_max)
					{
						bQuit = TRUE;
					}

				} while (::PeekMessage(pMsg, NULL, NULL, NULL, PM_NOREMOVE));
			}

		ExitModal:
			m_nFlags &= ~(WF_MODALLOOP|WF_CONTINUEMODAL);
			return m_nModalResult;
}