Exemplo n.º 1
0
DWORD CSerialPDDPowerUpCallback::ThreadRun()
{
    while (!IsTerminated() && m_hEvent!=NULL && m_pSerialObj!=NULL) {
        if (WaitForSingleObject(m_hEvent,INFINITE)==WAIT_OBJECT_0) {
            if (!IsTerminated()) {
                m_pSerialObj->NotifyPDDInterrupt(INTR_NONE);
            }
        }
        else 
            ASSERT(FALSE);
        
    }
    return 0;
}
Exemplo n.º 2
0
trap_retval ReqRunThread_poll( void )
{
    struct TDebug           *obj;
    struct TDebugThread     *thread;
    run_thread_poll_ret     *ret;

    ret = GetOutPtr( 0 );
    ret->conditions = 0;

    obj = GetCurrentDebug();

    if (obj) {
        thread = GetCurrentThread( obj );
        if( thread ) {
            SetCurrentThread( obj, thread->ThreadID );
            SetCurrentDebug( obj );
        }

        if( IsTerminated( obj ) )
            ret->conditions |= COND_TERMINATE;

        if( HasThreadChange( obj ) ) {
            ret->conditions |= COND_THREAD;
            ClearThreadChange( obj );
        }

        if( HasModuleChange( obj ) ) {
            ret->conditions |= COND_LIBRARIES;
        }
    }
    return( sizeof( *ret ) );
}
Exemplo n.º 3
0
DWORD CThread::FilesInFolder(CString scFolder)
{
	HANDLE hFind = NULL;
	WIN32_FIND_DATA dFind;

	DWORD res = 0;

	// Ищем все файлы\папки в переданной папке
	CString sFolder = scFolder + TEXT("\\*");
	if ((hFind = FindFirstFile(sFolder.C(), &dFind)) != INVALID_HANDLE_VALUE)
	{
		do
		{
			// Если прервали выполнение - выход из цикла
			if (IsTerminated()) break;

			// Пропускаем специальные папки '.' и '..'
			if (lstrcmp(dFind.cFileName, TEXT(".")) == 0 ||
				lstrcmp(dFind.cFileName, TEXT("..")) == 0)
				continue;

			if ((dFind.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
				res++;

		} while (FindNextFile(hFind, &dFind) != 0);

		FindClose(hFind);
	}

	return res;
}
Exemplo n.º 4
0
	void CLogSocket::DoExecute()
	{
		unsigned long ulLastCheckTick = 0;
		unsigned long ulTick = 0;
		LoadConfig();
		while (!IsTerminated())
		{
			try
			{
				m_ClientSocket.Execute();
				ulTick = GetTickCount();
				if (ulTick - ulLastCheckTick >= 10 * 1000)
				{
					ulLastCheckTick = ulTick;
					if (m_ClientSocket.IsConnected())
					{
						if (m_iPingCount > 3)
							m_ClientSocket.Close();
						else
							SendHeartBeat();
					}
					else
						m_ClientSocket.Open();
				}
			}
			catch (...)
			{
				SendDebugString("CLogSocket::DoExecute Exception");
			}
			WaitForSingleObject(m_Event, 10);
		}
		m_ClientSocket.Close();
	}
Exemplo n.º 5
0
//////////////////////////////////////////////////////////////////////////
// KSGTaskCollDeviceState
void KSGTaskCollDeviceState::Run()
{
	while(!IsTerminated())
	{
		try
		{
			_visitor.dev_start_ = 0;
			KsgGetGateway()->GetDeviceManager()->Traseval(
				boost::bind(&KSGTaskCollDeviceState::NewHeartBeatTask,this,_1));
			// 发送剩下的设备状态
			_visitor.send_state();
			Notify();
			// 采集一次流水
			//KsgGetGateway()->GetConfig()->_serialIntval * 50;
			ACE_DEBUG((LM_DEBUG,"采集一次心跳。。。"));
			KSG_SLEEP(KsgGetGateway()->GetConfig()->_heartbeat*10);
		}
		catch(std::exception& ex)
		{
			// 
			KSG_DUMP_EXCEPTION(ex);
			ACE_DEBUG((LM_DEBUG,"采集设备状态任务异常[%s]",ex.what()));
			KSG_SLEEP(KsgGetGateway()->GetConfig()->_heartbeat);
		}
	}
	ACE_DEBUG((LM_NOTICE,"任务线程退出"));
}
Exemplo n.º 6
0
void CHttpUploadFileProc::NotifyReceiver(WPARAM wParam, LPARAM lParam)
{
    if (IsTerminated())
        return;

    ::PostMessage(m_threadParam.hNotifyWnd, m_threadParam.uNotifyMsg, wParam, lParam);
}
Exemplo n.º 7
0
void KSGTaskDownloadBlackCard::Run()
{
	while(!IsTerminated())
	{
		_collect_count = 0;
		try
		{
			ACE_DEBUG((LM_DEBUG,"blklist-开始下载黑名单..."));
			KsgGetGateway()->GetDeviceManager()->Traseval(
				boost::bind(&KSGTaskDownloadBlackCard::NewDLBlkCardTask,this,_1));
			Notify();
			ACE_DEBUG((LM_DEBUG,"blklist-下载黑名单完成...sleep[%d]",KsgGetGateway()->GetConfig()->_heartbeat));
			// 采集一次流水
			//KsgGetGateway()->GetConfig()->_serialIntval * 50;
			KSG_SLEEP(KsgGetGateway()->GetConfig()->_heartbeat);
		}
		catch(std::exception& ex)
		{
			// 
			KSG_DUMP_EXCEPTION(ex);
			ACE_DEBUG((LM_TRACE,"下载黑名单任务异常[%s]",ex.what()));
			KSG_SLEEP(KsgGetGateway()->GetConfig()->_heartbeat);
		}
	}
	ACE_DEBUG((LM_NOTICE,"下载任务线程退出"));
}
Exemplo n.º 8
0
	void KSGLoopDeviceListenScheduler::Run()
	{
		int ret;
		_s_LoopReactor.owner(ACE_OS::thr_self());
		LoopSvrAcceptor acceptor;
		if(_s_interface.LoadDLLFunc())
		{
			ACE_DEBUG((LM_ERROR,"加载本地设备接口失败"));
			return;
		}
		
		int port = 9001;
#ifndef _DEBUG
		// TODO: 正式环境从后台中读取参数
		ACE_DEBUG((LM_NOTICE,"请设置侦听端口"));

#endif
		if(acceptor.open(ACE_INET_Addr(port),&_s_LoopReactor))
		{
			ACE_DEBUG((LM_ERROR,"Loop设备侦听失败,端口[%d]",port));
		}
		else if((ret = _s_interface.Initialize()))
		{
			ACE_DEBUG((LM_ERROR,"初始化Loop接口失败,返回错误[%d]",ret));
		}
		else
		{
			ACE_DEBUG((LM_INFO,"Loop设备开始侦听,线程号[%d]",ACE_OS::thr_self()));
			try
			{
				while(true)
				{
					ACE_Time_Value tv(5);
					_s_LoopReactor.handle_events(tv);
					Notify();
					if(IsTerminated())
					{
						while(!_s_LoopReactor.reactor_event_loop_done())
							_s_LoopReactor.end_reactor_event_loop();
						break;
					}
				}
				ACE_DEBUG((LM_NOTICE,"停止本地侦听服务"));
				if(_s_interface.Uninitialize())
				{
					ACE_DEBUG((LM_ERROR,"调用Loop设备接口释放资源失败!"));
				}
				ACE_DEBUG((LM_INFO,"Loop设备服务线程结束"));
			}
			catch(...)
			{
				// 捕获所有异常
				ACE_DEBUG((LM_NOTICE,"Loop设备服务线程执行异常"));
			}
		}
	}
Exemplo n.º 9
0
	virtual void Body()
	{
		in.Register("/foo/the/rampaging/frog");
		YARPTime::DelayInSeconds(2);
		while (!IsTerminated())
		{
			printf("Waiting for input\n");
			in.Read();
			printf("Read %d\n", (int)in.Content());
		}
	}
Exemplo n.º 10
0
	virtual void Body()
	{
		YARPInputPortOf<NetInt32> in;

		char buf[256];
		ACE_OS::sprintf(buf,"/etest/foo%d", id);
		in.Register(buf);
		YARPTime::DelayInSeconds(2);
		while (!IsTerminated())
		{
			ACE_OS::printf("Waiting for input\n");
			in.Read();
			ACE_OS::printf("Read %d\n", (int)in.Content());
		}
	}
Exemplo n.º 11
0
void Arbiter::Run()
{
	struct cmemBuffer *pBuffer = NULL;
	struct image_buffer_description *image = NULL;
	char snapMode = INVALID_MODE;
	_pCamera->StartCapture();	//开始采集数据

	while (!IsTerminated()) {
		
		if (!_pCamera->GetCaptureBuffer(&pBuffer)) {
			usleep(15000);
			//printf("can't get Buffer from driver\n");
			continue;
		}
		printf("get Buffer from driver\n");

		if (capture_buffer_alloc(&image)) {
			_pCamera->PutCaptureBuffer(pBuffer);
			printf("Fun:%s, Line:%d, get image buffer from list failed\n", __func__, __LINE__);
			usleep(15000);
			continue;
		}

		//snapMode = *((char *)pBuffer->vir_addr + position);
		snapMode = MANUAL_SNAP;
		switch (snapMode) {
		case VIDEO_MODE:	//视频模式处理
			_image_processor->VideoProcess(pBuffer, image);
			break;
		case MANUAL_SNAP:	//手动抓拍处理
			printf("manual snap\n");
			_image_processor->CaptureProcess(pBuffer, image);
			break;
		case HARD_TRIGGER:
			_image_processor->CaptureProcess(pBuffer, image);
		default:
			break;
		}
		//capture_buffer_free(image);
		transport_buffer_put(image);
		image = NULL;

		_pCamera->PutCaptureBuffer(pBuffer);
	}	

	_pCamera->CameraCleanup();	//释放相机资源
	return;
}
Exemplo n.º 12
0
void CSeqDlg::Body (void)
{
	/* */
	int count = 0;

	while (!IsTerminated())
	{
		if (m_s[count] < 0 || m_s[count] >= N_POSTURES || count >= SEQUENCE_LEN)
			count = 0;

		if (px != NULL)
		{
			if (px->_headrunning && px->_armrunning)
			{
				bool finished = false;
				head.setVelocities (px->_headstorev[m_s[count]]);
				arm.setVelocities (px->_armstorev[m_s[count]]);
				head.setPositions (px->_headstore[m_s[count]]);
				arm.setPositions (px->_armstore[m_s[count]]);

				YARPTime::DelayInSeconds (0.3);

				// wait.
				int timeout = 0;
				while (!finished)
				{
					finished = head.checkMotionDone();
					finished &= arm.checkMotionDone();

					YARPTime::DelayInSeconds (0.1);
					timeout ++;
					if (timeout >= 50)
						finished = true;
				}

				if (m_delay[count] != 0)
					YARPTime::DelayInSeconds (double(m_delay[count])/1000.0);
			}
			else
				YARPTime::DelayInSeconds (1.0);
		}
		else
			YARPTime::DelayInSeconds (1.0);

		count ++;
	}
}
Exemplo n.º 13
0
///
/// this together with Relinquish is part of the Read process.
///
///
///
Sendable *Port::Acquire(int wait)
{
	int go = 0;
	Sendable *result = NULL;
	if (wait)
	{
		out_mutex.Wait();
		while (!has_input)
		{
			out_mutex.Post();
			something_to_read.Wait();
			out_mutex.Wait();
		}
		out_mutex.Post();
		go = 1;
	}
	else
	{
		// HIT unfinished
		go = something_to_read.PollingWait();
	}

	if (go && !IsTerminated())
	{
		out_mutex.Wait();
		ACE_ASSERT (!accessing);
		if (p_receiver_latest.Ptr()!=NULL)
		{
			YARP_DBG(THIS_DBG) ((LM_DEBUG, "&&& READ from latest space\n"));
			p_receiver_latest.Switch(p_receiver_access);
			has_input = 0;
		}
		result = p_receiver_access.Ptr();

		if (asleep)
		{
			wakeup.Post();
		}
		accessing = 1;
		out_mutex.Post();
	}

	return result;
}
Exemplo n.º 14
0
void TcpClient::Run()
{

	int cnt = 0;

	while (!IsTerminated()) {

		if (_connect_flag) {
	
			if (!_connected_status) {
				ConnectClient();
			}

		} else {

			if (_connected_status) {
				
				if (local_sock) {
					Socket::Close(local_sock);
					local_sock = -1;
				}

				_connected_status = false;
			}
		}
		UploadClient();

		usleep(10000);

		if (_connected_status) {
			cnt++;
			if (cnt > 500) {
				cnt = 0;
				SendHeartBeat();
			}
		}
        }
	
	ClearBuffer();
	local_sock = -1;
	_connected_status = false;
	_connect_flag = false;
}
Exemplo n.º 15
0
void KSGTaskCollectSerial::Run()
{
	KSGThreadUtil::Sleep(10000);
	while(!IsTerminated())
	{
		try
		{
			KsgGetGateway()->GetDeviceManager()->Traseval(
				boost::bind(&KSGTaskCollectSerial::NewCollSerialTask,this,_1));
			Notify();
			// 采集一次流水
			KSGThreadUtil::Sleep(KsgGetGateway()->GetConfig()->_serialIntval);
		}
		catch(std::exception& ex)
		{
			// 
			ACE_DEBUG((LM_DEBUG,"采集流水任务异常[%s]",ex.what()));
		}
	}
}
Exemplo n.º 16
0
void KSGTaskCollHeartBeat::Run()
{
	while(!IsTerminated())
	{
		try
		{
			KsgGetGateway()->GetDeviceManager()->Traseval(
				boost::bind(&KSGTaskCollHeartBeat::NewHeartBeatTask,this,_1));
			Notify();
			// 每 3 分钟采集一次心跳
			KSGThreadUtil::Sleep(1000 * 60 * 3);
			//KSGThreadUtil::Sleep(5000);
		}
		catch(std::exception& ex)
		{
			// 
			ACE_DEBUG((LM_DEBUG,"采集心跳任务异常[%s]",ex.what()));
		}
	}
}
Exemplo n.º 17
0
	virtual void Body()
    {
		out.Register("/foo/the/rampaging/fly");
		YARPTime::DelayInSeconds(2);
		printf("Step1\n");
		out.Connect("/foo/the/rampaging/frog");
		printf("Step1.5\n");
		YARPTime::DelayInSeconds(2);
		int ct = 1;
		while (!IsTerminated())
		{
			printf("Step2\n");
			out.Content() = ct;
			printf("Step3\n");
			ct++;
			printf("Writing %d\n", (int)out.Content());
			//	  out.Write(true);
			out.Write();
			//	  YARPTime::DelayInSeconds(0.02);
		}
    }
Exemplo n.º 18
0
 virtual void Body()
 {
     out.Register("/fly");
     YARPTime::DelayInSeconds(2);
     printf("Step1\n");
     //out.Connect("/frog");
     printf("*** please connect /fly to /frog\n");
     printf("Step1.5\n");
     YARPTime::DelayInSeconds(2);
     int ct = 1;
     while (!IsTerminated())
     {
         printf("*** porter /fly /frog\n");
         printf("Step2\n");
         out.Content() = ct;
         printf("Step3\n");
         ct++;
         printf("Writing %d\n", (int)out.Content());
         out.Write();
         YARPTime::DelayInSeconds(4);
     }
 }
Exemplo n.º 19
0
void KSGTaskDoorBatchDlCard::Run()
{
	while(!IsTerminated())
	{
		try
		{
			KsgGetGateway()->GetDeviceManager()->Traseval(
				boost::bind(&KSGTaskDoorBatchDlCard::NewDLCardTask,this,_1));
			Notify();
			// 采集一次流水
			//KsgGetGateway()->GetConfig()->_serialIntval * 50;
			KSG_SLEEP(KsgGetGateway()->GetConfig()->_heartbeat );
		}
		catch(std::exception& ex)
		{
			// 
			KSG_DUMP_EXCEPTION(ex);
			ACE_DEBUG((LM_DEBUG,"下载门禁单任务异常[%s]",ex.what()));
			KSG_SLEEP(KsgGetGateway()->GetConfig()->_heartbeat);
		}
	}
	ACE_DEBUG((LM_NOTICE,"下载任务线程退出"));
}
Exemplo n.º 20
0
void CThread::DoPrescan(CString scFolder)
{
	m_bLevel++;

	HANDLE hFind = NULL;
	WIN32_FIND_DATA dFind;

	// Ищем все файлы\папки в переданной папке
	CString sFolder = scFolder + TEXT("\\*");
	if ((hFind = FindFirstFile(sFolder.C(), &dFind)) != INVALID_HANDLE_VALUE)
	{
		do
		{
			// Если прервали выполнение - выход из цикла
			if (IsTerminated()) break;

			// Пропускаем специальные папки '.' и '..'
			if (lstrcmp(dFind.cFileName, TEXT(".")) == 0 ||
				lstrcmp(dFind.cFileName, TEXT("..")) == 0)
				continue;

			if ((dFind.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
			{
				m_dwPrescanFolders++;

				// Продолжим предсканирование если не превысилы вложенность папок
				if (m_bLevel < PRESCAN_LEVELS - 1)
					DoPrescan(scFolder + TEXT("\\") + dFind.cFileName);
			}

		} while (FindNextFile(hFind, &dFind) != 0);

		FindClose(hFind);
	}

	m_bLevel--;
}
Exemplo n.º 21
0
/**
 * 任务队列的策略需要进行修改
 */
void KSGTaskReceiverScheduler::Run()
{
	while(!IsTerminated())
	{
		try
		{
			DRTPPoolType::SmartObject obj;
			try
			{
				obj = KsgGetDrtpPool()->Alloc();
			}
			catch (NoneResourceException& )
			{
				// 没有资源	
				KSGThreadUtil::Sleep(KsgGetGateway()->GetConfig()->_taskRecvIntval);
				continue;
			}
			ACE_DEBUG((LM_DEBUG,"开始接收指令..."));
			if(obj->Connect())
			{
				// 连接失败
				KSGThreadUtil::Sleep(KsgGetGateway()->GetConfig()->_taskRecvIntval);
				continue;
			}
			obj->SetRequestHeader(KsgGetGateway()->GetConfig()->_taskRecvFuncNo);
			obj->AddField(F_LCERT_CODE,KsgGetGateway()->GetConfig()->_gwId);
			obj->AddField(F_SCUST_LIMIT2,KsgGetGateway()->GetConfig()->_dynaKey.c_str());
			if(obj->SendRequest(1000))
			{
				// 发送指令失败
				ACE_DEBUG((LM_ERROR,"接收指令超时"));
				KSGThreadUtil::Sleep(KsgGetGateway()->GetConfig()->_taskRecvIntval);
				ACE_DEBUG((LM_DEBUG,"接收指令超时等待结束!"));
				continue;
			}
			Notify();
			if(obj->HasMoreRecord())
			{
				ST_PACK * data = obj->GetNextRecord();
				// 下载指令
				unsigned long taskid = data->lvol1;
				int funcid = data->lvol2;
				int devid = data->lvol3;
				TaskPriority priority = static_cast<TaskPriority>(data->lvol4);
				ACE_DEBUG((LM_DEBUG,"下载指令,ID[%d]func[%d]",taskid,funcid));
				if(devid == 0 || devid == 1)
				{
					devid = KSGDeviceNode::LoopDeviceId;
				}
				// 查找设备
				KSGateway::DeviceNodeType* dev = KsgGetGateway()->GetDeviceManager()->FindDevice(devid);
				if(dev == NULL)
				{
					ACE_DEBUG((LM_ERROR,"指令无对应的设备[%d]",devid));
					continue;
				}
				else
				{
					// 设备当前状态为错误
					if(dev->GetState() == KSGateway::DeviceNodeType::dsError)
					{
						// TODO : 应答执行指令超时
						ACE_DEBUG((LM_NOTICE,"设备状态错误, 任务被取消,dev[%d]taskid[%d]",devid,taskid));
						// 直接收取下一条指令
						continue;
					}
				}
				// TODO: 对于系统级的指令需要再进行分析细化
				// 生成指令
				// 设置指令的优先级
				TaskManager::PtrType task = KsgGetGateway()->GetTaskManager()->NewTask(taskid
					,funcid,data->vsvarstr0,dev,priority);
				// 处理 preemptive 指令
				//ACE_DEBUG((LM_DEBUG,"下载指令完成"));
			}
			else
			{
				// 如果没有指令可以接收,等待5000ms
				ACE_DEBUG((LM_DEBUG,"没有指令接收进入等待状态"));
				KSGThreadUtil::Sleep(5000);
				continue;
			}
			// 通知所有的 observer
		}
		catch(TaskAlreadyExistsException& )
		{
			// 指令已存在,可能还没有执行完成
			ACE_DEBUG((LM_NOTICE,"指令已经在队列中等待执行了!"));
		}
		catch(TaskQueueExceedException&)
		{
			// 指令队列已经满了
			ACE_DEBUG((LM_NOTICE,"指令队列已满!"));
		}
		catch(NullPointerException& )
		{
			ACE_DEBUG((LM_ERROR,"设备未正确配置"));
		}
		catch(std::exception& ex)
		{
			ACE_DEBUG((LM_ERROR,"接收指令线程处理异常!"));
		}
		KSGThreadUtil::Sleep(KsgGetGateway()->GetConfig()->_taskRecvIntval);
		ACE_DEBUG((LM_DEBUG,"等待指令结束"));
	}
}
Exemplo n.º 22
0
BOOL CHttpUploadFileProc::UseHttpSendReqEx(HINTERNET hRequest, CFile &file)
{
    //	生成form-data协议信息	<begin>
    CStringA	straHeader;
    CStringA	straContentHead;
    CStringA	straContentTail;

    straHeader = GetHttpAppendHeader();
    straContentHead = GetContentHead(file.GetFileName());
    straContentTail = GetContentTail();
    //	生成form-data协议信息	<end>

    ULONGLONG	ullFileLength = file.GetLength();
    DWORD	dwContentLength = straContentHead.GetLength() + (DWORD) ullFileLength + straContentTail.GetLength();

    INTERNET_BUFFERS BufferIn = {0};
    BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
    BufferIn.Next = NULL;
    //BufferIn.lpcszHeader = NULL;
    //BufferIn.dwHeadersLength = 0;
    BufferIn.lpcszHeader = straHeader.LockBuffer();
    straHeader.UnlockBuffer();
    BufferIn.dwHeadersLength = (DWORD)straHeader.GetLength();
    BufferIn.dwHeadersTotal = 0;
    BufferIn.lpvBuffer = NULL;
    BufferIn.dwBufferLength = 0;
    BufferIn.dwBufferTotal = dwContentLength;
    BufferIn.dwOffsetLow = 0;
    BufferIn.dwOffsetHigh = 0;

    if (IsTerminated())	return FALSE;
    NotifyReceiver(P_HUF_SENDING_FILE, 0);
    if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0))
        return FALSE;

    UINT	uProgressBegin = 10;
    UINT	uProgressEnd = 90;
    UINT	uProgressCur = 0;
    UINT	uReadCountSum = 0;


    const UINT uBufSize = 1024;
    BYTE pBuffer[uBufSize];
    UINT uReadCount;
    DWORD dwBytesWritten;
    BOOL bRet;
    float	fSendPercent;
    UINT	uProgressScale;


    //	Write Head
    bRet = InternetWriteFile( hRequest, straContentHead.LockBuffer(), straContentHead.GetLength(), &dwBytesWritten);
    straContentHead.UnlockBuffer();
    if(!bRet)
    {
        NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
        return FALSE;
    }

    if (IsTerminated())	return FALSE;
    //	Write file contents
    uReadCountSum = 0;
    bRet = TRUE;
    file.SeekToBegin();
    do {
        if (IsTerminated())	return FALSE;
        uReadCount = file.Read(pBuffer, uBufSize);
        if (0 == uReadCount)
            break;

        if(! InternetWriteFile( hRequest, pBuffer, uReadCount, &dwBytesWritten))
        {
            NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
            return FALSE;
        }

        uReadCountSum += uReadCount;
        fSendPercent = (float)uReadCountSum / BufferIn.dwBufferTotal;
        uProgressScale = (UINT) ((uProgressEnd - uProgressBegin) * fSendPercent);
        uProgressCur = uProgressBegin + uProgressScale;
        NotifyReceiver(P_HUF_PROGRESS, uProgressCur);

    } while (uReadCount == uBufSize);

    if (IsTerminated())	return FALSE;
    //	Write Tail
    bRet = InternetWriteFile( hRequest, straContentTail.LockBuffer(), straContentTail.GetLength(), &dwBytesWritten);
    straContentTail.UnlockBuffer();
    if(!bRet)
    {
        NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
        return FALSE;
    }
    NotifyReceiver(P_HUF_PROGRESS, uProgressEnd);


    if (IsTerminated())	return FALSE;
    NotifyReceiver(P_HUF_WAIT_RESPONSE, 0);
    if (!HttpEndRequest(hRequest, NULL, 0, 0))
    {
        NotifyReceiver(E_HUF_WAIT_RESPONSE_FAILD, 0);
        bRet = FALSE;
    }

    return bRet;
}
Exemplo n.º 23
0
BOOL CHttpUploadFileProc::HttpUploadFile()
{
    if (NULL == m_threadParam.szFileName
            || _T('\0') == m_threadParam.szFileName[0])
        return FALSE;

    BOOL		bRet;
    LPCTSTR		lpszAgent = _T("eMule Verycd");
    LPCTSTR		lpszServerName = _T("crash.emule.org.cn");
    LPCTSTR		lpszObjectName = _T("/report");
    CFile		file;
    HINTERNET hSession = NULL;
    HINTERNET hConnect = NULL;
    HINTERNET hRequest = NULL;


    NotifyReceiver(P_HUF_OPEN_FILE, 0);

    if (!file.Open(m_threadParam.szFileName, CFile::modeRead | CFile::shareDenyWrite))
    {
        NotifyReceiver(E_HUF_OPEN_FILE_FAILED, 0);
        return FALSE;
    }

    NotifyReceiver(P_HUF_PROGRESS, 5);



    bRet = TRUE;
    do {

        if (IsTerminated())	goto Label_Quit;
        NotifyReceiver(P_HUF_INTERNET_OPEN, 0);
        hSession = InternetOpen(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG,
                                NULL, NULL, 0);
        if(NULL == hSession)
        {
            NotifyReceiver(E_HUF_INTERNET_OPEN_FAILED, 0);
            bRet = FALSE;
            break;
        }

        if (IsTerminated())	goto Label_Quit;
        NotifyReceiver(P_HUF_INTERNET_CONNET, 0);
        hConnect = InternetConnect(hSession, lpszServerName, INTERNET_DEFAULT_HTTP_PORT,
                                   NULL, NULL, INTERNET_SERVICE_HTTP,NULL, NULL);
        if (NULL == hConnect)
        {
            NotifyReceiver(E_HUF_INTERNET_CONNECT_FAILED, 0);
            bRet = FALSE;
            break;
        }

        if (IsTerminated())	goto Label_Quit;
        NotifyReceiver(P_HUF_HTTP_OPEN_REQUEST, 0);
        hRequest = HttpOpenRequest(hConnect, "POST", lpszObjectName,
                                   NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);
        if (NULL == hRequest)
        {
            NotifyReceiver(E_HUF_HTTP_OPEN_REQUEST_FAILED, 0);
            bRet = FALSE;
            break;
        }

        NotifyReceiver(P_HUF_PROGRESS, 10);

        if (IsTerminated())	goto Label_Quit;
        if (!UseHttpSendReqEx(hRequest, file))
        {
            NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
            bRet = FALSE;
        }
    } while(0);

    if (IsTerminated())	goto Label_Quit;
    if (bRet)
    {
        NotifyReceiver(P_HUF_PROGRESS, 100);
        NotifyReceiver(S_HUF_FINISHED, 0);
    }

Label_Quit:
    ;

    if (NULL != hRequest)
    {
        InternetCloseHandle(hRequest);
        hRequest = NULL;
    }
    if (NULL != hConnect)
    {
        InternetCloseHandle(hConnect);
        hConnect = NULL;
    }
    if (NULL != hSession)
    {
        InternetCloseHandle(hSession);
        hSession = NULL;
    }

    file.Close();


    return bRet;
}
Exemplo n.º 24
0
DWORD WINAPI CThread::ThreadProc(LPVOID lpParameter)
{
	UpdateInfo(true);

	// Скопируем имена папок в новые переменные что бы не затереть исходные значения
	m_sSrcFolder = m_TaskInfo.sSrcFolder;
	m_sDestFolder = m_TaskInfo.sDestFolder;

	DelSlash(m_sSrcFolder);

	// Отформатируем имя папки назначения (раскроем макросы)
	CString sFormatedGenName = FormatDateTime(m_TaskInfo.sDestGenName.C());

	// Сформируем окончательное имя папки назначения
	m_sDestFolder += sFormatedGenName;
	DelSlash(m_sDestFolder);

	// Начало лога - запишем информацию о выполняемой задаче
	AddLog(TEXT("[i] Начало выполнения задачи, параметры:\r\n"));
	AddLog(TEXT("========================================\r\n"));
	AddLog(TEXT("[i] Задача: %s\r\n"), m_TaskInfo.sName.C());
	AddLog(TEXT("[i] Исходная папка: %s\r\n"), m_TaskInfo.sSrcFolder.C());
	AddLog(TEXT("[i] Папка назначения: %s\r\n"), (m_TaskInfo.sDestFolder + m_TaskInfo.sDestGenName).C());
	AddLog(TEXT("[i] Папка назначения: %s\r\n"), m_sDestFolder.C());
	AddLog(TEXT("[i] Включать файлы: %s\r\n"), m_TaskInfo.sIncludeMask.C());
	AddLog(TEXT("[i] Исключать файлы: %s\r\n"), m_TaskInfo.sExcludeMask.C());
    AddLog(TEXT("========================================\r\n"));

	// Если выполнение задачи не прервали - продолжаем
	if (!IsTerminated())
	{
		// Проверяем что бы папка назначения не была подпапкой исходной папки
		if (IsSubFolder(m_TaskInfo.sSrcFolder, m_sDestFolder))
		{
			AddLog(TEXT("[!] Папка назначения является подпапкой исходной папки\r\n"));
			AddLog(TEXT("[x] Невозможно продолжить выполнение задачи\r\n"));
		}
		// Проверка что папка назначения существует (или успешно создана)
		else if (!CheckDestFolder())
		{
			AddLog(TEXT("[!] Не могу создать папку назначения (%s)\r\n"), m_TaskInfo.sDestFolder.C());
			AddLog(TEXT("[x] Невозможно продолжить выполнение задачи\r\n"));
		}
		else
		{
			if (m_TaskInfo.bDoArchive)
			{
				// Получим временное (и уникальное) имя файла во временной папке
				TCHAR cTempPath[MAX_PATH];
				// получим временную папку
				GetTempPath(MAX_PATH, cTempPath);
				// получим уникальное имя для времнного файла, так же система создаст этот файл
				GetTempFileName(cTempPath, TEXT("smb"), 0, (LPTSTR) m_sFileList.Buf());

				if (!PathFileExists(m_sFileList.C()))
				{
					AddLog(TEXT("[!] Не могу создать файл-список (%s)\r\n"), m_sFileList.C());
					AddLog(TEXT("[!] Задача будет выполнена без архивирования\r\n"));
				}
			}

			// Сделаем предв. сканирование исходной папки
			m_bLevel = 0;
			m_dwPrescanFolders = 1;

			// Если работа с подпапками - предсканируем их
			if (m_TaskInfo.bSubFolders)
			{
				DoPrescan(m_sSrcFolder);

				// Узнаем сколько процентов занимает каждая "предсканированная" папка
				m_fPercentInc = (float) 100 / m_dwPrescanFolders;
			}
			// иначе просто подсчитаем кол-во файлов в исходной папке
			else
			{
				DWORD dwFiles = FilesInFolder(m_sSrcFolder);
				m_fPercentInc = (float) 100 / dwFiles;
			}

			UpdateInfo(true);

			MakeList(m_TaskInfo.sIncludeMask, m_aIncludeList);
			MakeList(m_TaskInfo.sExcludeMask, m_aExcludeList);

			// Создадим объект, в который будем записывать файл-лист для архиватора
			m_pFileList = new CMemTextFile();

			// Запускаем копирование файлов
			m_bLevel = 0;
			m_fPercents = 0;
			DoSubFolders(m_sSrcFolder, m_sDestFolder);

			// Сохраним файл-лист из памяти на диск
			m_pFileList->SaveFile(m_sFileList.C());
			delete m_pFileList;

			// Это последний вызов updateinfo, пускай получатели сообщения знают об этом
			m_TaskProgress.bLastInfo = true;
			UpdateInfo(true);

			// если задача не прервана - выполняем архивацию, если надо
			if (!IsTerminated() && m_TaskInfo.bDoArchive)
			{
				if (!PathFileExists(m_sArchiverEXE.C()))
				{
					AddLog(TEXT("[!] Не найден файл архиватора\r\n"));
					AddLog(TEXT("[x] Отмена запуска архиватора\r\n"));
				}											 
				else if (PathFileExists(m_sFileList.C()))
				{
					CString sArch = FormatC(TEXT("\"%s\" %s"), m_sArchiverEXE.C(), ParseArchiverCmdLine().C());
					AddLog(TEXT("[i] Вызов архиватора: %s\r\n"), sArch.C());

					PROCESS_INFORMATION pi = {0};

					STARTUPINFO si = {0};
					si.cb = sizeof(si);

					TCHAR cmd[MAX_PATH];
					lstrcpy(cmd, sArch.C());

					// Создаём процесс - запускаем архиватор
					if (CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
					{
						// И ждём пока он не завершит работу
						WaitForSingleObject(pi.hProcess, INFINITE);

						DWORD dwExitCode;
						GetExitCodeProcess(pi.hProcess, &dwExitCode);

						CloseHandle(pi.hProcess);
						CloseHandle(pi.hThread);
    
						AddLog(TEXT("[i] Архиватор завершил работу с кодом %d\r\n"), dwExitCode);

						// Если указано - удалим скопированный файлы (их имена занесены в список)
						if (m_TaskInfo.bArchDelFiles)
						{
							for (int i = 0; i < m_lFileList.Size(); i++)
                                DelFiles(m_lFileList[i]);
						}
					}
					else
						AddLog(TEXT("[!] Ошибка при вызове архиватора\r\n"));
				}

				// Удалим файл-список для архиватора
				DeleteFile(m_sFileList.C());
			}

			AddLog(TEXT("========================================\r\n"));
			if (IsTerminated())
				AddLog(TEXT("[i] Выполнение задачи прервано\r\n"));
			else
				AddLog(TEXT("[i] Выполнение задачи завершено\r\n"));
		}
	}

	// пошлём сообщения всем подписавшимся слушателям что работа завершена
	for (int i = 0; i < m_ProgressListenrs.Size(); i++)
		PostMessage(m_ProgressListenrs[i], RegisterWindowMessage(ThreadDoneMessage), 0, 0);

	return 0;
}
Exemplo n.º 25
0
void CThread::DoSubFolders(CString sFolder, CString sBackupFolder)
{
	m_bLevel++;	// очередной раз вошли рекурсивно в себя

	HANDLE hFind = NULL;
	WIN32_FIND_DATA dFind;

	CString strFolder = sFolder + TEXT("\\*");

	bool bError = false;
	DWORD dwFiles = 0;		// кол-во файлов в текущей папке
	DWORD dwFolders = 0;	// кол-во папок в текущей папке

	// Папки куда копировать файлы несуществует, попробуем создать
	if (!PathFileExists(sBackupFolder.C()))
	{
		// создать папку не вышло, ошибка
		if (CreateDirectory(sBackupFolder.C(), NULL) == FALSE)
		{
			AddLog(TEXT("[!] Не могу создать папку \'%s\'! Пропуск папки %s\r\n"), sBackupFolder.C(), sFolder.C());
			bError = true;
		}
	}

	// Не работаем дальше на текущем уровне вложенности если произошла ошибка - нельзя создать папку назначения
	if ((!bError) && (hFind = FindFirstFile(strFolder.C(), &dFind)) != INVALID_HANDLE_VALUE)
	{
		do
		{
			if (IsTerminated()) break;

			// Skip '.' and '..' folders
			if (lstrcmp(dFind.cFileName, TEXT(".")) == 0 ||
				lstrcmp(dFind.cFileName, TEXT("..")) == 0)
				continue;

			// Работаем с папкой
			if ((dFind.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
			{
				if (!m_TaskInfo.bSubFolders) continue;

				// Добавим папку в файл-список
				if (m_bLevel == 1)
				{
					m_pFileList->SetLine(CString(sBackupFolder + TEXT("\\") + dFind.cFileName).C());	
					m_lFileList.Add(sBackupFolder + TEXT("\\") + dFind.cFileName);
				}

				// Формируем имя след. папки для обработки (вложенной)
				CString strNewFolder = sFolder + TEXT("\\") + dFind.cFileName;
				CString sNewBackupFolder = sBackupFolder + TEXT("\\") + dFind.cFileName;

				// Обработали ещё одну папку на текущем уровне вложенности
				dwFolders++;

				// Вызываемся рекурсивно - обрабатываем вложенную папку
				DoSubFolders(strNewFolder, sNewBackupFolder);
			}
			// Работаем с файлом
			else
			{
				// Увеличим кол-во обработанных файлов
				m_TaskProgress.dwProceedFiles++;

				// Сперва проверим удовлетворяет ли имя файла с "маской исключения"
				if (MaskListMath(CString(dFind.cFileName), m_aExcludeList))
					// если да - увеличим число пропущенных файлов
					m_TaskProgress.dwExcludedFiles++;
				// иначе, если имя файла удовлетворяет "маске включения" - работаем с ним
				else if (MaskListMath(CString(dFind.cFileName), m_aIncludeList))
				{
					// Формируем полные имена файлов - откуда и куда копировать
					CString sFileCopyFrom = sFolder + TEXT("\\") + dFind.cFileName;
					CString sFileCopyTo = sBackupFolder + TEXT("\\") + dFind.cFileName;

					// Если файл уже есть в папке назначения - удалим его (как будто он старый)
					if (PathFileExists(sFileCopyTo.C()))
						DeleteFile(sFileCopyTo.C());

					// Скопируем файл из исходной папки в папку назначения
					if (!CopyFile(sFileCopyFrom.C(), sFileCopyTo.C(), TRUE))
					{
						// ошибка при копировании
						m_TaskProgress.dwErrors++;
						AddLog(TEXT("[!] Ошибка при копировании файла \'%s\'!\r\n"), sFileCopyFrom.C());
					}
					else
					{
						HANDLE hFile = CreateFile(sFileCopyFrom.C(), GENERIC_READ, 0, NULL, OPEN_EXISTING, NULL, NULL);
						if (hFile != INVALID_HANDLE_VALUE)
						{
							m_TaskProgress.i64FinishedBytes += GetFileSize(hFile, NULL);
							CloseHandle(hFile);
						}

						// Добавим файл в файл-список, если он скопировался успешно
						if (m_bLevel == 1)
						{
							m_pFileList->SetLine(CString(sBackupFolder + TEXT("\\") + dFind.cFileName).C());
							m_lFileList.Add(sBackupFolder + TEXT("\\") + dFind.cFileName);
						}
					}

					// Обработали ещё один файл - увеличим счётчики
					m_TaskProgress.dwIncludedFiles++;
                    dwFiles++;
				}
				// иначе, если имя файла не удовлетворяет ни одной из масок - записываем его как необработанный
				else
					m_TaskProgress.dwExcludedFiles++;

				// Обработали файл - увеличим процент выполнения
				if (!m_TaskInfo.bSubFolders)
					m_fPercents += m_fPercentInc;

				UpdateInfo();
			}

		} while (FindNextFile(hFind, &dFind) != 0);

		FindClose(hFind);
	}

	// Если нет ошибки и уровень вложенности менее заданного числа - добавим в лог эту папку
	if (!bError && m_bLevel <= 2)
		AddLog(TEXT("[i] Папка \'%s\' обработана; файлов: %d, папок: %d\r\n"), sFolder.C(), dwFiles, dwFolders);

	// Посчитаем процент выполнения задачи
	if (m_TaskInfo.bSubFolders && m_bLevel <= PRESCAN_LEVELS)
		m_fPercents += m_fPercentInc;

	// Обработали очередную папку
	m_TaskProgress.dwProceedFolders++;
	UpdateInfo();

	// поднимаемся на уровень выше
	m_bLevel--;
}
Exemplo n.º 26
0
///
///
///
/// hopefully an improvement. a thread that handles the fact that we can't wake up
/// Port::Body both on a socket and a mutex/semaphore.
///
/// this thread takes care of sending stuff to the list of output threads. 
/// it is simply activated by the Share method instead of the MSG_ID_GO command.
///
///
void _strange_select::Body ()
{
	ACE_DEBUG ((LM_DEBUG, "***** _strange_select::Body : starting\n"));

#if defined(__QNX6__) || defined(__LINUX__)
	signal (SIGCHLD, SIG_IGN);
	signal (SIGPIPE, SIG_IGN);
#endif

	OutputTarget *target, *next;

	while (!IsTerminated())
	{
		_ready_to_go.Wait ();
		
		/// hopefully in wait on the sema, it returns from here.
		if (IsTerminated()) continue;

		/// access to targets must be protected, in case, the port
		/// thread decides to delete a link ;)
		/// this should only (on average) just cause a delay in receiving
		///	a command, while operations in the port thread should take less.
		///
		_owner->list_mutex.Wait ();

		int scanned = 0;
		if (!scanned)
		{
			double now = YARPTime::GetTimeAsSeconds ();
			target = _owner->targets.GetRoot ();
			while (target != NULL)
			{
				next = target->GetMeshNext ();

				target->WaitMutex ();
				
				int active = target->active;
				int deactivated = target->deactivated;
				int ticking = target->ticking;
				double started = target->check_tick;
				
				target->PostMutex ();
				
				int timeout = 0;
				
				if (ticking && now - started > 5)
				{
					active = 0;
					timeout = 1;
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "timeout expired %f\n", now-started));
				}

				if (!active)
				{
					ACE_DEBUG ((LM_INFO, "*** disconnecting %s and %s %s%s\n",
						_owner->name.c_str(), target->GetLabel().c_str(),
						deactivated ? "" : "(target stopped responding)",
						timeout?" (timeout)":""));

					delete target;
				}
				
				target = next;
			}
			scanned = 1;
		}

		// Send message to all listeners
		if (!scanned)
		{
			target = _owner->targets.GetRoot ();
			while (target != NULL)
			{
				next = target->GetMeshNext ();
				
				target->WaitMutex ();
				int active = target->active;
				int deactivated = target->deactivated;
				target->PostMutex ();

				if (!active)
				{
					ACE_DEBUG ((LM_INFO, "*** disconnecting %s and %s %s\n", 
						_owner->name.c_str(), target->GetLabel().c_str(),
						deactivated ? "" : "(target stopped responding)"));

					delete target;
				}
				target = next;
			}
		}

		YARP_DBG(THIS_DBG) ((LM_DEBUG, "Sending a message from %s\n", _owner->name.c_str()));
		target = _owner->targets.GetRoot ();

		_owner->out_mutex.Wait ();

		while (target!=NULL)
		{
			YARP_DBG(THIS_DBG) ((LM_DEBUG, "Sending a message from %s to target %s\n", _owner->name.c_str(), target->GetLabel().c_str()));
			if (_owner->p_sendable.Ptr() != NULL)
			{
				if (_owner->require_complete_send)
				{
					target->space_available.Wait ();
					target->space_available.Post ();
				}

				target->Share (_owner->p_sendable.Ptr());
				target->add_header = _owner->add_header;
			}
			else
			{
				ACE_DEBUG ((LM_DEBUG, "Delayed message skipped\n"));
			}
			
			target = target->GetMeshNext ();
		}

		/// releases the list only here
		/// 
		_owner->p_sendable.Reset ();
		
		_owner->out_mutex.Post ();
		_owner->pending = 0;
		_owner->okay_to_send.Post ();

		_owner->list_mutex.Post ();

	}	/// while !IsTerminated()

	/// 
	ACE_DEBUG ((LM_DEBUG, "***** _strange_select::Body : closing 0x%x\n", GetIdentifier()));
	_owner = NULL;
}
Exemplo n.º 27
0
DWORD CPdd6410Uart::ThreadRun()
{
    DWORD dwData;
    DWORD interrupts;
    
    while ( m_hISTEvent!=NULL && !IsTerminated() )
    {
        if ( WaitForSingleObject( m_hISTEvent, m_dwISTTimeout) == WAIT_OBJECT_0)
        {
            m_HardwareLock.Lock();    
        
            while ( !IsTerminated() )
            {
                dwData = ( GetInterruptStatus() & (S6410UART_INT_RXD | S6410UART_INT_TXD | S6410UART_INT_ERR | S6410UART_INT_MODEM) );
                if (dwData)
                {
                    DEBUGMSG(ZONE_THREAD, (TEXT(" CPdd6410Uart::ThreadRun Active INT=%x\r\n"), dwData));

                    // Clear the interrupt value to notify to MDD
                    interrupts=NULL;
                    DEBUGCHK(interrupts==NULL);

                    if ((dwData & S6410UART_INT_RXD)!=0)
                    {
                        interrupts |= INTR_RX;
                    }
                    if ((dwData & S6410UART_INT_TXD)!=0)
                    {
                        interrupts |= INTR_TX;
                    }
                    if ((dwData & S6410UART_INT_ERR)!=0)
                    {
                        interrupts |= INTR_LINE | INTR_RX;
                    }
                    if ((dwData & S6410UART_INT_MODEM)!=0)
                    {
                        interrupts |=INTR_MODEM;
                    }
                    
                    NotifyPDDInterrupt( (INTERRUPT_TYPE)interrupts );
                    
                    ClearInterrupt(dwData);
                }
                else
                {
                    break;
                }
            }

            m_HardwareLock.Unlock();   

            InterruptDone(m_dwSysIntr);
        }
        else
        {
            DEBUGMSG(ZONE_THREAD,(TEXT(" CPdd6410Uart::ThreadRun timeout INT=%x,MASK=%d\r\n"),m_pReg6410Uart->Read_UINTP()/*m_pReg6410Uart->Read_UINTSP()*/, m_pReg6410Uart->Read_UINTM()) );
            ASSERT(FALSE);
        }
    }

    return 1;
}
Exemplo n.º 28
0
void Port::Body()
{
	int tag = 0;
	char *buf = NULL;
	Fragments cmd;
	OutputTarget *target = NULL, *next = NULL;
	BlockReceiver receiver;
	NewFragmentHeader hdr;
	int ok;
	int assume_data;
	int call_on_read = 0;

	YARPUniqueNameID* pid = NULL;
	name_set = 1;

	/// LATER: must actually jump to the end of the thread for proper cleanup instead of returning.
	/// this is the registration section.
	switch (protocol_type)
	{
	case YARP_QNET:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_QNET, YARPNativeEndpointManager::CreateQnetChannel()); 
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (qnet)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	case YARP_TCP:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_TCP, YARP_UDP_REGPORTS); 
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (tcp)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	case YARP_UDP:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_UDP, YARP_UDP_REGPORTS); 
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (udp)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	case YARP_MCAST:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_MCAST, YARP_UDP_REGPORTS);
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (mcast)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	default:
		{
			ACE_DEBUG ((LM_DEBUG, "troubles in acquiring ports (?)\n"));
			name_set = 0;
			if (asleep)
			{
				asleep = 0;
				okay_to_send.Post();
			}
			return;
		}
		break;
	}

	YARPEndpointManager::CreateInputEndpoint (*pid);
	
	/// ok, ready to create the sending thread (_strange_select).
	/// all this to avoid sending a message through the port socket.
	tsender.Begin ();

	/// registration completed. now goes the receiver/command thread.
	if (asleep)
	{
		asleep = 0;
		okay_to_send.Post();
	}

	while (!IsTerminated())
    {
		receiver.Begin(pid->getNameID());

		receiver.Get();
		out_mutex.Wait();
		assume_data = !expect_header;
		out_mutex.Post();

		/// WARNING: cmd buffer is not zeroed anywhere, in case buffer is string
		///		it might be better to do it somewhere around here.

		if (!assume_data)
		{
			ok = receiver.Get((char*)(&hdr),sizeof(hdr));
			if (ok || hdr.checker=='/')
			{
				if (hdr.checker == '~')
				{
					tag = hdr.tag;
					cmd.Require(hdr.length);
					if (tag != MSG_ID_DATA)
					{
						ok = receiver.Get(cmd.GetBuffer(),hdr.length);
						YARP_DBG(THIS_DBG) ((LM_DEBUG, "Got some form of command ( %d, %d )\n", ((int)tag), ok));
					}
				}
				else
				{
					if (hdr.checker != '/')
					{
						ACE_DEBUG ((LM_ERROR, "Error - command received in unknown protocol ( %s )\n", name.c_str()));
						ok = 0;
					}
					else
					{
						YARP_DBG(THIS_DBG) ((LM_DEBUG, "%s received unsupported old format request: %s\n", name.c_str()));
					}
				}
			}

			if (!ok)
			{
				tag = MSG_ID_ERROR;
			}

			if (tag == MSG_ID_NULL)
			{
				buf = cmd.GetBuffer();
				tag = buf[0];
			}
			else
			{
				buf = cmd.GetBuffer();
			}
		}
		else
		{
			YARP_DBG(THIS_DBG) ((LM_DEBUG, "Auto assume data\n"));
			tag = MSG_ID_DATA;
		}

		if (tag != MSG_ID_DATA)
		{
			receiver.End();
		}

		list_mutex.Wait ();
		int scanned = 0;
		if (!scanned)
		{
			double now = YARPTime::GetTimeAsSeconds();
			target = targets.GetRoot();
			while (target != NULL)
			{
				next = target->GetMeshNext();
				target->WaitMutex();
				int active = target->active;
				int deactivated = target->deactivated;
				int ticking = target->ticking;
				double started = target->check_tick;
				target->PostMutex();
				int timeout = 0;
				
				if (ticking && now-started > 5)
				{
					active = 0;
					timeout = 1;
				}

				if (!active)
				{
					ACE_DEBUG ((LM_INFO, "*** disconnecting %s and %s %s%s\n",
						name.c_str(), target->GetLabel().c_str(),
						deactivated ? "" : "(target stopped responding)",
						timeout?" (timeout)":""));
					/// remove the port no, from the list of used ports.

					delete target;
				}
				target = next;
			}
			scanned = 1;
		}
		list_mutex.Post ();

		if (pid->isValid())
		{
			switch(tag)
			{
			case MSG_ID_ATTACH:
				{
					list_mutex.Wait ();
					
					/// mcast is handled differently.
					if (protocol_type != YARP_MCAST)
					{
						target = targets.GetByLabel (buf);
						if (target == NULL)
						{
							ACE_DEBUG ((LM_INFO, "*** connecting %s to %s\n", name.c_str(), buf));

							target = targets.NewLink(buf);
							ACE_ASSERT(target != NULL);
							
							target->network_name = network_name;
							target->target_pid = NULL;
							target->protocol_type = protocol_type;
							target->allow_shmem = allow_shmem;
							target->SetRequireAck (GetRequireAck());
							target->SetOwnName (name);

							target->Begin();
						}
						else
						{
							ACE_DEBUG ((LM_DEBUG, "Ignoring %s, already connected\n", buf));
						}
					}
					else
					{
						/// it requires an extra call to the name server.
						YARPUniqueNameID *rem_pid = YARPNameService::LocateName (buf);

						YARPString ifname;
					
						bool same_net = YARPNameService::VerifySame (((YARPUniqueNameSock *)rem_pid)->getAddressRef().get_host_addr(), network_name.c_str(), ifname);

#ifndef DEBUG_DISABLE_SHMEM
						char myhostname[YARP_STRING_LEN];
						getHostname (myhostname, YARP_STRING_LEN);
						ACE_INET_Addr local ((u_short)0, myhostname);
						
						char iplocal[17];
						ACE_OS::memset (iplocal, 0, 17);
						ACE_OS::strcpy (iplocal, local.get_host_addr());

						bool same_machine = YARPNameService::VerifyLocal (((YARPUniqueNameSock *)rem_pid)->getAddressRef().get_host_addr(), iplocal, network_name.c_str());

						if (same_net || same_machine)
						{
#else
						if (same_net)
						{
#endif

							
#ifndef DEBUG_DISABLE_SHMEM
							if (same_machine && allow_shmem)
							{
								/// go into TCP-SHMEM.
								target = targets.GetByLabel (buf);
								if (target == NULL)
								{
									ACE_DEBUG ((LM_INFO, "*** connecting SHMEM between %s and %s\n", name.c_str(), buf));

									target = targets.NewLink(buf);
									ACE_ASSERT(target != NULL);
		
									target->network_name = network_name;
									target->target_pid = NULL;
									target->protocol_type = YARP_UDP;
									target->allow_shmem = allow_shmem;
									target->SetOwnName (name);

									target->Begin();
								}
								else
								{
									ACE_DEBUG ((LM_DEBUG, "Ignoring %s, already connected\n", buf));
								}
							}
							else
#endif
							{
								/// mcast out port thread.
								target = targets.GetByLabel ("mcast-thread");
								if (target == NULL)
								{
									ACE_DEBUG ((LM_INFO, "*** connecting MCAST %s to %s\n", name.c_str(), buf));
									target = targets.NewLink("mcast-thread");

									ACE_ASSERT(target != NULL);
									target->network_name = network_name;
									target->target_pid = NULL;
									target->protocol_type = protocol_type;
									target->allow_shmem = allow_shmem;
									target->SetOwnName (name);

									target->Begin();

									target->ConnectMcast (buf);
								}
								else
								{
									ACE_DEBUG ((LM_INFO, "*** connecting MCAST %s to %s\n", name.c_str(), buf));
									target->ConnectMcast (buf);
								}
							}

						}	/// end if (same_net)
					}	/// if !MCAST 

					list_mutex.Post ();
				}
				break;

			case MSG_ID_DETACH:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Received detach request for %s\n", buf+1));

					list_mutex.Wait ();

					if (protocol_type != YARP_MCAST)
					{
						target = targets.GetByLabel(buf+1);
						if (target != NULL)
						{
							ACE_DEBUG ((LM_DEBUG, "Removing connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							target->Deactivate();
						}
					}
					else
					{
#ifndef DEBUG_DISABLE_SHMEM
						target = targets.GetByLabel(buf+1);
						if (target != NULL)
						{
							ACE_DEBUG ((LM_DEBUG, "Removing (SHMEM) connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							target->Deactivate();
						}
						else
#endif
						{
							/// mcast
							target = targets.GetByLabel("mcast-thread");
							if (target != NULL)
							{
								ACE_DEBUG ((LM_DEBUG, "Removing connection between %s and (%s) via %s\n", name.c_str(), buf+1, target->GetLabel().c_str()));
								
								target->DeactivateMcast(buf+1);
							}
						}
					}

					/// scan the list of outputs to delete disconnected ones!

					///
					/// don't I need a wait for completion of the Deactivate procedure here?

					double now = YARPTime::GetTimeAsSeconds();
					target = targets.GetRoot();
					while (target != NULL)
					{
						next = target->GetMeshNext();
						target->WaitMutex();
						int active = target->active;
						int deactivated = target->deactivated;
						int ticking = target->ticking;
						double started = target->check_tick;
						target->PostMutex();
						int timeout = 0;
						
						if (ticking && now-started > 5)
						{
							active = 0;
							timeout = 1;
						}

						if (!active)
						{
							ACE_DEBUG ((LM_INFO, "disconnecting %s and %s %s%s\n",
								name.c_str(), target->GetLabel().c_str(),
								deactivated ? "" : "(target stopped responding)",
								timeout?" (timeout)":""));

							delete target;
						}
						target = next;
					}

					list_mutex.Post ();
				}
				break;

			case MSG_ID_DATA:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Gosh, someone sent me data! Me being %s in case you're curious\n", name.c_str()));

					out_mutex.Wait();
					receiving = 1;
					
					if (!ignore_data) 
					{
						while (p_receiver_incoming.Ptr() == NULL)
					    {
							YARP_DBG(THIS_DBG) ((LM_DEBUG, "&&& Waiting for incoming space\n"));
							// HIT - should have way to convey back skip
							// request to sender
							// (can't just ignore, don't know how many)
							// (components message has)

							asleep = 1;
							out_mutex.Post();
							wakeup.Wait();
							out_mutex.Wait();
					    }

						asleep = 0;
						p_receiver_incoming.Ptr()->AddRef();
						out_mutex.Post();

						p_receiver_incoming.Ptr()->Read(receiver);
						p_receiver_incoming.Ptr()->RemoveRef();
					}
					else
					{
						out_mutex.Post();
					}

					receiver.End();

					out_mutex.Wait();
					receiving = 0;
					
					if (!ignore_data) 
					{
						YARP_DBG(THIS_DBG) ((LM_DEBUG, "&&& Received. Switching with latest space\n"));
						p_receiver_latest.Switch(p_receiver_incoming);

						if (!has_input)
						{
							has_input = 1;
							something_to_read.Post();
						}
					}

					out_mutex.Post();

					if (!ignore_data) 
					{
						call_on_read = 1;
					}
				}
				break;

			case MSG_ID_GO:
				{
					ACE_DEBUG ((LM_ERROR, "this shouldn't happen, the new version doesn't accept MSG_ID_GO\n"));
				}
				break;

			case MSG_ID_DETACH_ALL:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Received detach_all request (%s)\n", name.c_str()));

					list_mutex.Wait ();

					if (protocol_type != YARP_MCAST)
					{
						target = targets.GetRoot();

						while (target != NULL)
						{
							next = target->GetMeshNext();
							ACE_DEBUG ((LM_INFO, "*** removing connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							target->Deactivate();
							target = next;
						}
					}
					else
					{
						OutputTarget *mtarget = targets.GetByLabel("mcast-thread");
#ifndef DEBUG_DISABLE_SHMEM
						/// takes care of the SHMEM connection
						target = targets.GetRoot();

						while (target != NULL)
						{
							next = target->GetMeshNext();
							ACE_DEBUG ((LM_INFO, "*** removing connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							if (target != mtarget && mtarget != NULL)
								target->Deactivate();
							target = next;
						}
#endif

						/// mcast
						if (mtarget != NULL)
						{
							ACE_DEBUG ((LM_INFO, "*** removing all MCAST connections\n"));
							mtarget->DeactivateMcastAll();
						}
					}

					list_mutex.Post ();

					/// signal the SelfEnd that the msg has been received.

					complete_msg_thread.Signal ();

					/// wait for closure of SelfEnd socket and relative thread.
					complete_terminate.Wait();

					/// only now asks for End.
					AskForEnd ();
				}
				break;

			case MSG_ID_DETACH_IN:
				{
					ACE_DEBUG ((LM_DEBUG, "*** received detach request for %s\n", buf+1));

					YARPUniqueNameID needclose;
					needclose = *pid;
					needclose.setName (buf+1);
					YARPEndpointManager::Close (needclose);
				}
				break;

			case MSG_ID_DUMP_CONNECTIONS:
				{
					ACE_DEBUG ((LM_INFO, "*** dumping connections for %s\n", name.c_str()));
					ACE_DEBUG ((LM_INFO, "*** output connections:\n"));

					list_mutex.Wait ();
					target = targets.GetRoot();
					int i = 0;
					while (target != NULL)
					{
						target->WaitMutex();
						ACE_DEBUG ((LM_INFO, "***   %d: %s %s:%d\n", 
							i, 
							target->GetLabel().c_str(),
							target->GetOwnAddress().get_host_addr(),
							target->GetOwnAddress().get_port_number()));
						target->PostMutex();
						next = target->GetMeshNext();
						target = next;
						i++;
					}

					list_mutex.Post ();

					ACE_DEBUG ((LM_INFO, "*** input connections:\n"));
					YARPEndpointManager::PrintConnections (*pid);
				}	
				break;

			case MSG_ID_ERROR:
				YARP_DBG(THIS_DBG) ((LM_DEBUG, "Error message received by %s!\n", name.c_str()));
				break;

			default:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Unknown message received by %s (tag is %d-->'%c', str is %s)!\n", name.c_str(), tag, tag, buf));
				}
				break;
			}
		}	/// end switch/case
      
		if (call_on_read)
		{
			OnRead();
			call_on_read = 0;
		}
	} /// if !terminated

	/// since this is started in this thread close it here.
	tsender.AskForEnd();
	tsender.pulseGo();
	tsender.Join();

	///
	/// tries to shut down the input socket threads.
	/// uses the special request for closing all input threads at once.
	///
	///
	YARPUniqueNameID needcloseall;
	needcloseall = *pid;
	needcloseall.setName ("__All__");
	YARPEndpointManager::Close (needcloseall);

	/// unregister the port name here.
	YARPNameService::UnregisterName (pid);

	/// free memory.
	YARPNameService::DeleteName (pid);
	pid = NULL;

	/// wakes up a potential thread waiting on a blocking Read().
	has_input = 1;
	something_to_read.Post();

	ACE_DEBUG ((LM_DEBUG, "***** main port thread 0x%x returning\n", GetIdentifier()));
}


///
/// this is called from YARPPort::Write to actually send something.
/// Currently it wakes the Port thread up through a socket connection that
///	Paul believes to be responsible for poor performance on Linux/NT.
///
void Port::Share(Sendable *nsendable)
{
	okay_to_send.Wait();
	out_mutex.Wait();
	p_sendable.Set(nsendable);
	out_mutex.Post();

	/// this simply pulses the mutex on the sender thread.
	/// cost an additional thread but hopefully saves a costly message
	/// through the port socket.
	tsender.pulseGo ();
}
//--------------------------------------------------------------------------------------
//       Class:  YARPSoundDeviceDriver
//      Method:  Body()
// Description:  Here, the body of the thread should be implemented
//--------------------------------------------------------------------------------------
void 
YARPSoundDeviceDriver::Body (void)
{
	SoundResources& d = RES(system_resources);
	MSG		msg;

	const int prio = ACE_Sched_Params::next_priority (ACE_SCHED_OTHER, GetPriority(), ACE_SCOPE_THREAD);
	SetPriority (prio);
	
	//----------------------------------------------------------------------
	//  Wait for a message sent by the audio driver
	//----------------------------------------------------------------------
	while (GetMessage(&msg, 0, 0, 0) == 1 && !IsTerminated()) {

		switch (msg.message) {
			case MM_WIM_DATA: //Buffer filled 
				/*********************************************************************************
				 * the msg.lParam contains a pointer to the WAVEHDR structure for the filled buffer. *
				 *********************************************************************************/
				if (((WAVEHDR *)msg.lParam)->dwBytesRecorded) {
					//----------------------------------------------------------------------
					//  Here write in the local buffer using the syncronization mutexes
					//----------------------------------------------------------------------
					if (d._bmutex.PollingWait () == 1) { // buffer acquired. Reading from the buffer
						if (d.m_InRecord)
							memcpy (d._rawBuffer, 
									((WAVEHDR *)msg.lParam)->lpData, 
                                    ((WAVEHDR *)msg.lParam)->dwBytesRecorded); // Note: is this right?
                                                                               // The buffer could not be full...
						if (d._canpost) {
							d._canpost = false;
							d._new_frame.Post();
						}
						d._bmutex.Post ();
					}
					else
					{
						//----------------------------------------------------------------------
						//  can't acquire, it means the buffer is still in use.
						//  silently ignores this condition.
						//----------------------------------------------------------------------
						ACE_DEBUG ((LM_DEBUG, "lost a frame, acq thread\n"));
					}
				}

				//----------------------------------------------------------------------
				//  Requeue the used buffer	
				//----------------------------------------------------------------------
				waveInAddBuffer(d.m_WaveInHandle, 
								(WAVEHDR *)msg.lParam, 
								sizeof(WAVEHDR));

				break;
				/* Our main thread is opening the WAVE device */
			case MM_WIM_OPEN:
				ACE_DEBUG ((LM_DEBUG, "yarpsounddriver: sound device opened\n"));
				break;
				/* Our main thread is closing the WAVE device */
			case MM_WIM_CLOSE:
				break;
			default:
				//ACE_DEBUG ((LM_DEBUG, "yarpsounddriver: received an unknown message\n"));
				break;
		}
	}

	ACE_DEBUG ((LM_DEBUG, "acquisition thread returning...\n"));
}