// ------------------------------Pulse Handler----------------------------------
void PulseHandler(int simPV_L)
{
	// move the links back into limit range
	if ((simPV_L&64 )/64 == 0 )
	{
		if (temp_last_input == ROLLCW)	writeMsg(ROLLCCW);
		else							writeMsg(ROLLCW); 
	}
	else if ((simPV_L&32)/32 == 0)
	{
		if (temp_last_input == PITCHUP)	writeMsg(PITCHDW);
		else							writeMsg(PITCHUP); 
	}
	else if ((simPV_L&16)/16 == 0)
	{
		if (temp_last_input == ELBOWUP)	writeMsg(ELBOWDW);
		else							writeMsg(ELBOWUP); 
	}
	else if ((simPV_L&8)/8 == 0)
	{
		if (temp_last_input == SHOULDERUP)	writeMsg(SHOULDERDW);
		else								writeMsg(SHOULDERUP); 
	}
	else if ((simPV_L&4)/4 == 1)
	{
		if (temp_last_input == BASECW)	writeMsg(BASECCW);
		else							writeMsg(BASECW); 
	}
}
示例#2
0
文件: controller.cpp 项目: jcxz/MUL
void Controller::openVideoFile(QString &fileName)
{
    if(!player.setVideoFile(fileName)) {
        writeMsg("Player: Error opening video file");
        controlsEnabled(false);
    }
    else {
        controlsEnabled(true);
        writeMsg("Video successfully opened");
    }
}
// ------------------------------Auto Thread-------------------------------------
void* auto_thread(void*notused)
{
	int homed;
	homed = 0;
	while(1)
	{
		//printf("home: %i\n",homed);
		if ((last_input == BASECW)   	|| (last_input == BASECCW)  	||
		    (last_input == SHOULDERUP)  || (last_input == SHOULDERDW)	||
			(last_input == ELBOWUP)  	|| (last_input == ELBOWDW)		||
			(last_input == PITCHUP) 	|| (last_input == PITCHDW)		||
			(last_input == GRIPPEROP)   || (last_input == GRIPPERCLOSE) ||
			(last_input == ROLLCW)      || (last_input == ROLLCCW))
			homed = 0;
		if (memData.autoModeOn == ON)
		{
			if (last_input == HOMEROBOT)
			{
				printf("homing!\n");
				if (homed != 1)
				{
					homed = homing();
					last_input = MANUALON;
					writeMsg(last_input);
				}
				printf("home done\n");
				flushall();
				last_input = MANUALON;
				writeMsg(last_input);
			}
			if (last_input == MANUALOFF)
			{
				if (readLowerByte.lowIpReserved1 == 1)
				{
					printf("No block in the loader\n");
					flushall();
				}
				else
				{
					if (homed != 1)
						homing();
					homed = 0;
					auto_mode();
				}
				last_input = MANUALON;
				writeMsg(last_input);
				printf("auto done\n");
				flushall();
			}
		}
		delay(50);
	}
}
示例#4
0
文件: server.c 项目: ikasty/Homework
// 리스트에 새 클라이언트를 추가합니다.
Client* addClient(Client* newClient) {
    char buffer[256];
    char head[HEAD_SIZE], value[VALUE_SIZE];

    int n;

    if (newClient == 0) return 0;

    // 우선 클라이언트가 일반 클라이언트이지, shell 클라이언트인지를 알아냅니다.
    readMsg(newClient->socket, head, value);
    if ( !strcmp(head, MODE) && !strcmp(value, MODE_CLIENT) ) {
        // 일반 client 모드면 싱글 링크드리스트에 추가합니다.
        newClient->nextClient = 0;
        if (front != 0)
            newClient->nextClient = front;
        // 그냥 맨 앞에 넣습니다. 순서는 중요하지 않습니다.
        front = newClient;
        newClient->isShell = false;

    } else
    if ( !strcmp(head, MODE) && !strcmp(value, MODE_SHELL) ) {
        // shell client 모드면 shell 모드로 접속한 다른 클라이언트가 없는지 확인합니다.
        if (shellClient != 0) {
            writeMsg(newClient->socket, ERR, "SHELL_DUP");
            exit(1);
        }

        // shell 클라이언트는 리스트에 넣지 않고 따로 관리합니다.
        shellClient = newClient;
        newClient->isShell = true;
    } else {
        // 알 수 없는 client 접속
        writeMsg(newClient->socket, ERR, PROTO_ERR);
        return 0;
    }

    // 클라이언트의 이름을 설정합니다.
    sprintf(buffer, "Client(%d)", clientCount);
    clientCount++;
    writeMsg(newClient->socket, SET_NAME, buffer);

    // 클라이언트 정보를 출력합니다.
    Notice("Client");
    printf("(%d) connected, IP: %s, Port: %d\n", clientCount, newClient->ip, newClient->port);

    // 끝났습니다. 클라이언트에게 정상적으로 접속했다고 알립니다.
    readMsg(newClient->socket, head, value);
    writeMsg(newClient->socket, ACCEPT, "server_ok");

    return newClient;
}
示例#5
0
    void uiSetParameterValue(const uint32_t index, const float value) override
    {
        CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),);

        char tmpBuf[0xff+1];

        const CarlaMutexLocker cml(fWriteLock);

        writeMsg("control\n", 8);
        std::sprintf(tmpBuf, "%i\n", index);
        writeMsg(tmpBuf);
        std::sprintf(tmpBuf, "%f\n", value);
        writeMsg(tmpBuf);
    }
示例#6
0
    void uiSetMidiProgram(const uint8_t channel, const uint32_t bank, const uint32_t program) override
    {
        CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);

        char tmpBuf[0xff+1];

        const CarlaMutexLocker cml(fWriteLock);

        writeMsg("program\n", 8);
        std::sprintf(tmpBuf, "%i\n", channel);
        writeMsg(tmpBuf);
        std::sprintf(tmpBuf, "%i\n", bank);
        writeMsg(tmpBuf);
        std::sprintf(tmpBuf, "%i\n", program);
        writeMsg(tmpBuf);
    }
示例#7
0
///登录,发送登陆请求给服务器
void talk_to_svr::do_login(const std::string &username, const std::string &password)
{
    _username = username;
    _password = password;
    std::string writeMsg("login " + username + " " + password + "\n");
    service.post(MEM_FN1(do_write, writeMsg));
}
示例#8
0
void CBoostLog::logFromQueue()
{
   while (m_isRunning) {
      std::string msg;
      bool hasMsg = m_msgQueue.timedPop(msg, LOG_TIMEOUT);
      if (hasMsg) {
         writeMsg(msg);
      }
   }
   // make sure the queue is empty before quitting
   while (!m_msgQueue.empty()) {
      std::string msg;
      m_msgQueue.timedPop(msg, LOG_TIMEOUT);
      writeMsg(msg);
   }
}
// ------------------------------Main Loop---------------------------------------
void mainLoop()
{
	writeMsg(ESTOP);
	while(killFlg == 0)
	{	
		readMsg(1,0);
		// shared memory access
			// update system states in shared memory
			if (last_input == CONVEYORON)
				memData.conveyorOn = ON;
			else if ((last_input == CONVEYOROFF) || (last_input == ESTOP))
				memData.conveyorOn = OFF;
			if ((last_input == MANUALON) || (last_input == ESTOP))
				memData.autoModeOn = OFF;
			else if (last_input == MANUALOFF || last_input == HOMEROBOT)
				memData.autoModeOn = ON;	
			memData.upperByte = readUpperByte.hiInputSetByte;
			memData.lowerByte = readLowerByte.lowInputSetByte;
			memData.blkType = blockNumG;
		sem_wait(sem);
			*memLocation = memData;
		sem_post(sem);
		//  request status from GUIport and write to shared memory for every 50 ms
		delay(50);
	}
}
/*!
 * This method finally writes the message to the logfile.
 * You must set the message type.  
 */
void TTMessageLogger::logMsg(MsgType msgType, QString caller, QString msgString)
{
  QString write;
  
  if(msgType == INFO)
    write = "[info]";

  if(msgType == WARNING)
    write = "[warning]";

  if(msgType == ERROR)
   write = "[error]";

  if(msgType == DEBUG)
    write = "[debug]";

  write.append("[");
  write.append(QDateTime::currentDateTime().toString("hh:mm:ss"));
  write.append("][");
  write.append(caller);
  write.append("] ");
  write.append(msgString);

  if(logMode & CONSOLE)
    qDebug(write.toAscii().data());

  writeMsg(write);
}
示例#11
0
文件: LedCtr.cpp 项目: xluthvu/Pi
/*
 * Handle for common functions
 * Register Led Control with System after spawning
 */
bool Led_Ctr::ctrRegister()
{
	generic_msg *msg = NULL;
	sys_msg *sys = NULL;

	msg = prepHelloMsg(LED_C);
	writeMsg(msg);
	desMsg(msg);

	log->LOG_IN("Send REG message");
	/* Wait for REG_ACK from system with led configuration */
	while(true)
	{
		msg = readMsg();
		if (msg == NULL)
			continue;

		log->LOG_IN("Received a message from System: " + msg->msgType);
		if (msg->msgType == SYS)
		{
			sys = (sys_msg*)msg->data;
			if (sys->sysMsgType == SYS_REGISTER_OK)
			{
				/* Initialize Led agent instances from configuration */

				desMsg(msg);
				break;
			}
		}
	}

	return true;
}
示例#12
0
文件: Logger.cpp 项目: ic-hep/emi3
void logger::writeLog(std::string message, bool console) {

    if (console == true && message.length() > 0) {
        std::string timestapStr = timestamp();
        timestapStr.erase(timestapStr.end() - 1);
        std::cerr << "ERROR: " <<  timestapStr << " " <<  message << std::endl;
    }
    
    writeMsg(message);    
}
示例#13
0
    void uiSetCustomData(const char* const key, const char* const value) override
    {
        CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
        CARLA_SAFE_ASSERT_RETURN(value != nullptr,);

        const CarlaMutexLocker cml(fWriteLock);

        writeMsg("configure\n", 10);
        writeAndFixMsg(key);
        writeAndFixMsg(value);
    }
示例#14
0
static int msg2netlog(msg* message){
  if(message != NULL){
    FILE* fp = fopen(logFile,"aw");
    if(fp != NULL){
      fprintf(fp, "%s", time2string());
      writeMsg(fileno(fp), message);
      fclose(fp);
      return 1;
    }
  }
  return 0;
}
示例#15
0
void Msg::sendmsgUser(const QString& from, const QStringList& list, bool quiet) {
    QString txt1(from + " sends a message to you: " + list[1]);
    QString message(QDate::currentDate().toString("dd/MM/yyyy ") + QTime::currentTime().toString("hh:mm:ss ") + from + " : " + list[1]);
    QString to(manager()->databasePlugin()->canonicalName(list[0]));
    if((manager()->connectionPlugin()->serverSend(to,txt1) || manager()->databasePlugin()->isRegisteredUser(to))
       && writeMsg(to,message) && !quiet) {
        QString txt2("You send a message to " + to + ": " + list[1]);
        manager()->connectionPlugin()->serverSend(from,txt2);
    } else if(!quiet) {
		QString error("Invalid user");
		manager()->connectionPlugin()->serverSend(from,error);
    }
}
示例#16
0
bool Fifo::writeIfConnected(const folly::AsyncTransportWrapper* transport,
                            MessageDirection direction,
                            const struct iovec* iov,
                            size_t iovcnt) noexcept {
  if (!isConnected()) {
    return false;
  }


  auto written = writeMsg(fd_, buildMsgHeader(transport, direction),
                          iov, iovcnt);
  if (!written && errno == EPIPE) {
    disconnect();
  }
  return written;
}
示例#17
0
void parsePVSThenEcho(char *prompt, int from, int to){
  msg* message;
  int length;
  message = readPVSMsg(prompt, from);
  if(message != NULL){
    length = parseString(message->data, message->bytesUsed);
    message->bytesUsed = length;
    if(sendMsg(to, message) < 0){
      fprintf(stderr, "sendMsg in parsePVSThenEcho failed\n");
    } else {
      if(WRAPPER_DEBUG)writeMsg(STDERR_FILENO, message);
      announce("\nparseThenEcho wrote %d bytes\n", message->bytesUsed);
    }
    freeMsg(message);
  }
}
int getData(boolean tx, double timeStamp, int fd, char buff[], int size) {

   memset(buff, 0, size);

   int rc = recv(fd, buff, D_INFO, 0);
   int errNum = NET_ERROR_NUM;
   if ((rc <= 0) && (errNum != EWOULDBLOCK)) {
      fprintf(stderr, "recv() failed. Error = %d\n", errNum); fflush(stderr);
      return -GDB_FATAL_ERROR;
   }
   if (rc > 0) {
      writeMsg(tx, buff, rc);
      return rc;
   }
   return -GDB_NON_FATAL_ERROR;
}
示例#19
0
int LogManager::writeLog(const char *fmt, ...) {
	//static to prevent reallocation every function call
	static char msg[DEFAULT_MSG_LEN] = "";
	va_list inserts;
	
	va_start(inserts, fmt);
	vsprintf(msg, fmt, inserts);
	va_end(inserts);
	
	//write message
	int status = writeMsg(msg);
	if(strflush)
		logfile<<std::endl;
	else
		logfile<<"\n";
	return status;
}
//------------------------------Timer Thread--------------------------------------
void* timer_thread(void*notused)
{
	int time_count;
	int rcvid_timer;
	while(1)
	{	
		rcvid_timer = MsgReceivePulse(timerChid, &timerPulse, sizeof(timerPulse), NULL);
		if (rcvid_timer==-1)
		{
			printf("Error in timer pulse!\n");
			flushall();
		}
		else
		{writeMsg(COMMEND_RESET);}
		delay(50);
			
	}
}
示例#21
0
文件: sal_lib.c 项目: HackLinux/iopc
void parseSalThenEcho(int from, int to){
  msg* message;
  int length;
  announce("parseSalThenEcho\t:\tCalling wrapper_readSalMsg\n");
  message = wrapper_readSalMsg(from);
  if(message != NULL){
    announce("parseSalThenEcho\t:\twrapper_readSalMsg returned %d bytes\n", message->bytesUsed);
    length = parseString(message->data, message->bytesUsed);
    message->bytesUsed = length;
    if(sendMsg(to, message) < 0){
      fprintf(stderr, "sendMsg in parseSalThenEcho failed\n");
    } else {
      if(SALWRAPPER_DEBUG)writeMsg(STDERR_FILENO, message);
      announce("\nparseThenEcho wrote %d bytes\n", message->bytesUsed);
    }
    freeMsg(message);
  }
}
示例#22
0
void parseMaudeThenEcho(int from, int to){
  msg* message;
  int length;
  announce("parseMaudeThenEcho\t:\tCalling readMaudeMsg\n");
  message = readMaudeMsg(from);
  if(message != NULL){
    announce("parseMaudeThenEcho\t:\treadMaudeMsg returned %d bytes\n", message->bytesUsed);
    if(WATCH_MAUDE)logMsg("maude", MAUDE_LOGFILE, message);
    length = parseString(message->data, message->bytesUsed);
    message->bytesUsed = length;
    if(sendMsg(to, message) < 0){
      fprintf(stderr, "sendMsg in parseMaudeThenEcho failed\n");
    } else {
      if(MAUDE_WRAPPER_DEBUG)writeMsg(STDERR_FILENO, message);
      announce("\nparseThenEcho wrote %d bytes\n", message->bytesUsed);
    }
    freeMsg(message);
  }
}
示例#23
0
void
DCMessenger::sendBlockingMsg( classy_counted_ptr<DCMsg> msg )
{
	msg->setMessenger( this );
	Sock *sock = m_daemon->startCommand (
		msg->m_cmd,
		msg->getStreamType(),
		msg->getTimeout(),
		&msg->m_errstack,
		msg->name(),
		msg->getRawProtocol(),
		msg->getSecSessionId());

	if( !sock ) {
		msg->callMessageSendFailed( this );
		return;
	}

	writeMsg( msg, sock );
}
示例#24
0
/*!
 * This method finally writes the message to the logfile.
 * You must set the message type.
 */
void TTMessageLogger::logMsg(MsgType msgType, QString caller, int line, QString msgString, bool show)
{
    QString msgTypeStr;
    QFileInfo fInfo(caller);
    QString msgCaller = fInfo.baseName();

    //if (!logEnabled && msgType != ERROR) return;

    if (logLevel == NONE & ((msgType != ERROR) & (msgType != FATAL))) return;

    if (logLevel == MINIMAL & ((msgType != ERROR) & (msgType != FATAL) &
                               (msgType != WARNING))) return;

    if (logLevel == EXTENDED & ((msgType != ERROR)   & (msgType != FATAL) &
                                (msgType != WARNING) & (msgType != INFO))) return;

    if(msgType == INFO)
        msgTypeStr = "info";

    if(msgType == WARNING)
        msgTypeStr = "warning";

    if(msgType == ERROR)
        msgTypeStr = "error";

    if(msgType == DEBUG)
        msgTypeStr = "debug";

    QString logMsgStr = (line > 0)
                        ? QString("[%1][%2][%3:%4] %5").arg(msgTypeStr).arg(QDateTime::currentDateTime().toString("hh:mm:ss")).arg(msgCaller).arg(line).arg(msgString)
                        : QString("[%1][%2][%3] %4").arg(msgTypeStr).arg(QDateTime::currentDateTime().toString("hh:mm:ss")).arg(msgCaller).arg(msgString);

    // show message window
    if (show)
        ;

    if (logMode & CONSOLE || msgType == ERROR)
        qDebug(logMsgStr.toUtf8().data());

    writeMsg(logMsgStr);
}
示例#25
0
int TCPSockClient::do_register(void)
{
	int push_id = PUSH_BEGIN + m_index;

	std::stringstream sstream;
	sstream << push_id;
	std::string server_id;
	sstream >> server_id;

	unsigned source = crc32_hash((const unsigned char*) server_id.c_str(),
			server_id.length());
	VncDataPackage package;
	package.setSourceAndTarget(source, SERVER_ID);
	package.setCommandId(0x00010004, 0);

	package.setStringParam(server_id);
	std::string returnbuf = package.getProtocolBuffer();
	writeMsg(this->m_sockfd, (char *) returnbuf.c_str(),
			returnbuf.length());
	return 0;
}
// ------------------------------Handler Loop--------------------------------
void* Handlerloop_thread(void*notused)
{
	// Initialize simulator pulse value
	simPulseVal = 120;
	while(killFlg == 0)
	{
		// Keep calling PulseHandler until all joint is within limit
		while(((simPulseVal&64) + (simPulseVal&32) + (simPulseVal&16) + (simPulseVal&8) + (simPulseVal&4)) != 120)
		{
			//printf("\nin while\n");
			PulseHandler(simPulseVal);
			if (((simPulseVal&64) + (simPulseVal&32) + (simPulseVal&16) + (simPulseVal&8) + (simPulseVal&4)) == 120)
			{
				writeMsg(COMMEND_RESET);
				delay(50);
				//printf("SIM: Pulse: %i %i %i %i %i \n\n", (simPulseVal&64)/64, (simPulseVal&32)/32, (simPulseVal&16)/16, (simPulseVal&8)/8, (simPulseVal&4)/4);
			}
		}
		delay(50);
	}
}
// ------------------------------GUI Monitor Thread-------------------------------
void* GUI_thread(void*notused)
{
	int guiPulseVal;

	highOutput.hiOutputSetByte = 0;
	lowOutput.lowOutputSetByte = 0;
	while(1)
	{
		// Receive message from GUI
		MsgReceivePulse (2,&guiPulse,sizeof(guiPulse),NULL);
		// initialize guiPulseVal
		// extract the pulse value
		if (guiPulse.value.sival_int != COMMEND_RESET)
		{
			guiPulseVal = 0; 
			guiPulseVal = guiPulse.value.sival_int;
			last_input  = guiPulseVal;
		}
		// print GUI pulse
//		printf("GUI: Pulse: %i \n", guiPulseVal);
//		printf("Temp: Temp = %i \n", temp_guiPulse);
		// Quit loop if guiPulseVal == GUIQUIT
		if (guiPulseVal == GUIQUIT) {killFlg = 1; break;}
		// Command simulator
		writeMsg(guiPulseVal);
		if ((guiPulseVal == BASECW) 	|| (guiPulseVal == BASECCW)  	||
		    (guiPulseVal == SHOULDERUP) || (guiPulseVal == SHOULDERDW)	||
			(guiPulseVal == ELBOWUP)	|| (guiPulseVal == ELBOWDW)		||
			(guiPulseVal == PITCHUP) 	|| (guiPulseVal == PITCHDW)		||
			(guiPulseVal == UNLOADLEFT) || (guiPulseVal == UNLOADRIGHT)	||
			(guiPulseVal == GRIPPEROP)  || (guiPulseVal == GRIPPERCLOSE))
		{
			timer_settime(timerid, 0, &timer,NULL);
		}
	}
}
示例#28
0
文件: server.c 项目: ikasty/Homework
void doShell(Client* shellClient) {
    Client* p;
    char head[HEAD_SIZE], value[VALUE_SIZE];

    char fileBuffer[FILE_BUFFER_SIZE + 1];
    char fileChunk[FILE_CHUNK_SIZE];
    char filename[256];
    unsigned long fileSize;
    int fd;
    FILE* fp;

    FDEBUG(("shell start\n"));
    while (1) {
        // shell 담당 서버는 shell 클라이언트로부터 신호를 받아야만 일합니다.
        readMsg(shellClient->socket, head, value);

        if ( !strcmp(head, ADD) ) {
            // 파일 추가
            FDEBUG(("get ADD message\n"));
            fileSize = 0;

            // 우선 해당 이름으로 파일을 엽니다.
            strcpy(filename, value);
            fd = open(filename, O_WRONLY | O_CREAT, 0644);
            if (fd == -1) {
                writeMsg(shellClient->socket, ERR, "fileopen_err");
                continue;
            }

            // 다른 일반 클라이언트들에게도 이 사실을 알립니다.
            writeMsg(shellClient->socket, ACCEPT, "fileadd");
            p = front;
            while (p) {
                writeMsg(p->pipe[1], ADD, filename);
                p = p->nextClient;
            }

            // 파일 구분자를 입력받습니다.
            readMsg(shellClient->socket, head, fileChunk);
            writeMsg(shellClient->socket, ACCEPT, "filechunk");
            p = front;
            while (p) {
                writeMsg(p->pipe[1], CHUNK, fileChunk);
                p = p->nextClient;
            }

            // 파일을 읽어서 클라이언트에게 전달합니다. 서버에도 한 부 저장합니다.
            FDEBUG(("start reading file\n"));
            while (true) {
                memset(fileBuffer, 0, sizeof(fileBuffer));
                readData(shellClient->socket, fileBuffer);

                p = front;
                while (p) {
                    writeData(p->pipe[1], fileBuffer);
                    p = p->nextClient;
                }

                // 파일 전송이 끝나면 끝냅니다.
                if ( !strcmp(fileBuffer, fileChunk) ) break;
                // 아니라면 서버에 저장하고 다음 부분을 보내달라고 요청합니다.
                else writeData(fd, fileBuffer);
                writeMsg(shellClient->socket, CHUNK, fileChunk);
                fileSize += strlen(fileBuffer);
            }
            // 파일을 전부 기록했습니다. 닫고 EOF 메시지를 전달합니다.
            close(fd);
            writeMsg(shellClient->socket, ACCEPT, "eof");
            p = front;
            while (p) {
                writeMsg(p->pipe[1], ACCEPT, "eof");
                p = p->nextClient;
            }

            // 결과를 출력합니다.
            Notice("ADD ");
            printf("[%s][%ldbyte] from Client(%d)\n", filename, fileSize, shellClient->clientNo);

        } else
        if ( !strcmp(head, DEL) ) {
            // 삭제할 파일의 크기를 구합니다.
            fp = fopen(value, "r");
            fseek(fp, 0L, SEEK_END);
            fileSize = ftell(fp);
            fclose(fp);

            // 결과를 출력합니다.
            Notice ("DELETE ");
            printf("[%s][%ldbyte] from Client(%d)\n", value, fileSize, shellClient->clientNo);

            // 파일을 삭제하고 다른 클라이언트에게 알립니다.
            remove( value );

            p = front;
            while (p) {
                writeMsg(p->pipe[1], head, value);
                p = p->nextClient;
            }

        }
    }
}
示例#29
0
		void Connection::handle_read(const boost::system::error_code& e, std::size_t bytes_transferred)
		{
			//parse  and  make it a Json::Value then transport it to gate, let gate deal with it
			m_bReadInProgress = false;
			if (!e)
			{
				//mutex lock
				boost::recursive_mutex::scoped_lock(m_ReadMtx);
				boost::tribool result;
				boost::tie(result, boost::tuples::ignore) = m_RequestParser.parse(
					m_Request, m_ReadBuffer.data(), m_ReadBuffer.data() + bytes_transferred);

				if (result)
				{
					//request_handler_.handle_request(request_, reply_);
					//boost::asio::async_write(m_Socket, m_Reply.to_buffers(),
					//	boost::bind(&Connection::handle_write, shared_from_this(),
					//	boost::asio::placeholders::error));
					
					LogW << m_Request.uri << LogEnd;

					if (!is_service_command(m_Request.uri))
					{
						if (!is_request_resource(m_Request.uri))
						{
							m_Reply = reply::stock_reply(reply::bad_request);
							boost::asio::async_write(m_Socket, m_Reply.to_buffers(),
								boost::bind(&Connection::handle_write, shared_from_this(),
								boost::asio::placeholders::error));
							return;
						}
						else
						{
							//get a file
							boost::filesystem::path rss_path(m_Request.uri);
							boost::filesystem::path cur_cpath = boost::filesystem::current_path();
							boost::filesystem::path file_path = cur_cpath / rss_path; //pathÖ§³ÖÖØÔØ/ÔËËã·û
							if (!boost::filesystem::exists(file_path) || !boost::filesystem::is_regular_file(file_path))
							{
								m_Reply = reply::stock_reply(reply::bad_request);
								boost::asio::async_write(m_Socket, m_Reply.to_buffers(),
									boost::bind(&Connection::handle_write, shared_from_this(),
									boost::asio::placeholders::error));
								return;
							}
							std::string content = util::fileSystem::loadJsonFile(file_path.string());
							writeResourceMsg(content);
							return;
						}
					}

					Json::Value jreq;
					int ret = 0;
					if (m_Request.method == "GET")
					{
						ret = m_RequestParser.parse_content(GET_METHOD, m_Request.uri, jreq);
					}
					else
					{
						ret = m_RequestParser.parse_content(POST_METHOD,  m_Request.content, jreq);
					}
					if (ret != 0)
					{
						m_Reply = reply::stock_reply(reply::bad_request);
						boost::asio::async_write(m_Socket, m_Reply.to_buffers(),
							boost::bind(&Connection::handle_write, shared_from_this(),
							boost::asio::placeholders::error));
						return;
					}
					jreq["net_id"] = this->m_nConnId;
					LogW << jreq.toStyledString() << LogEnd;
					
					gateSvr.on_http_req(this, jreq);
					NetMessage netMsg;
					netMsg.setMessage("{\"status\":\"ok\"}");
					writeMsg(netMsg);
				}
				else if (!result)
				{
					m_Reply = reply::stock_reply(reply::bad_request);
					boost::asio::async_write(m_Socket, m_Reply.to_buffers(),					
						boost::bind(&Connection::handle_write, shared_from_this(),
						boost::asio::placeholders::error));
				}
				else
				{
					m_Socket.async_read_some(boost::asio::buffer(m_ReadBuffer),	
						boost::bind(&Connection::handle_read, shared_from_this(),
						boost::asio::placeholders::error,
						boost::asio::placeholders::bytes_transferred));
				}
			}
			else
			{
				//ʧ°Ü·µ»Øbad request
			}
		}
示例#30
0
int main(int argc, char** argv){
  if(argc != 1){
    fprintf(stderr, "Usage: %s\n", argv[0]);
  }

  self_debug_flag  = PVS_ACTOR_DEBUG;
  self = argv[0];

  ec_neg1( iop_install_handlers(chld_handler, intr_handler) );

  ec_neg1( pipe(pin) );
  ec_neg1( pipe(perr) );
  ec_neg1( pipe(pout) );

  /*it's time to fork */
  ec_neg1( child = fork() );

  if(child == 0){
    /* i'm destined to be pvs */
    ec_neg1( dup2(pin[0],  STDIN_FILENO) );
    ec_neg1( dup2(perr[1], STDERR_FILENO) );
    ec_neg1( dup2(pout[1], STDOUT_FILENO) );

    ec_neg1( close(pin[0])  );
    ec_neg1( close(perr[1]) );
    ec_neg1( close(pout[1]) );

    ec_neg1( execvp(pvs_exe, pvs_argv) );

  } else {
    /* i'm the boss */
    pthread_t errThread;
    fdBundle  errFdB;

    /* for monitoring the error stream */
    errFdB.fd = perr[0];
    errFdB.exit = &child_died;

    ec_neg1( close(pin[0])  );
    ec_neg1( close(perr[1]) );
    ec_neg1( close(pout[1]) );
    
    /* sleep(2); */
    
    ec_rv( pthread_create(&errThread, NULL, echoErrorsSilently, &errFdB) );
      
    announce("Listening to PVS\n");
    parsePVSThenEcho("\ncl-user(", pout[0], STDOUT_FILENO);

    write(pin[1], "(in-package 'pvs)\n", strlen("(in-package 'pvs)\n"));
    
    announce("Listening to PVS\n");

    parsePVSThenEcho("\npvs(", pout[0], STDOUT_FILENO);
    
    while(1){
      int length, retval;
      msg *query = NULL, *response = NULL;
      char *sender, *command;
      
      announce("Listening to IO\n");
      query = acceptMsg(STDIN_FILENO);
      if(query == NULL) continue;
      retval = parseActorMsg(query->data, &sender, &command);
      
      write(pin[1], command, strlen(command));
      write(pin[1], "\n", 1);
      
      announce("Listening to PVS\n");
      
      response = readPVSMsg("\npvs(", pout[0]);
      if(response != NULL){
	length = parseString(response->data, response->bytesUsed);
	response->bytesUsed = length;
	
	sendFormattedMsgFP(stdout, "%s\n%s\n%s\n", sender, self, response->data);
	
	if(self_debug_flag)writeMsg(STDERR_FILENO, response);
	announce("\nparseThenEcho wrote %d bytes\n", response->bytesUsed);
      }
      
      freeMsg(query);
      freeMsg(response);
      
    }
  }
  exit(EXIT_SUCCESS);

EC_CLEANUP_BGN
  exit(EXIT_FAILURE);
EC_CLEANUP_END

}