int StructuredLearnerRpc::FindOrCreateSession(const Json::Value& root, Json::Value& response) {
  int sess_ind = -1;
  char sess_id[1000];
  char errStr[1000];
  if(strlen(root.get("session_id", "").asString().c_str()) < 1000)
    strcpy(sess_id, root.get("session_id", "").asString().c_str());
  else
    strcpy(sess_id, "");
  
  if(!strlen(sess_id)) {
    if(!NewSession(root, response) || !InitializeSession(root, response)) {
      JSON_ERROR("Failed to create new session in classify_example\n", -1);
    }
    sess_ind = num_sessions-1;//FindSession(response.get("session_id", "").asString().c_str());
    assert(sess_ind >= 0);
    //fprintf(stderr, "New Session %d\n", sess_ind);
  } else {
    sess_ind=FindSession(sess_id, true);
    if(sess_ind < 0) {
      sprintf(errStr, "Invalid session_id %s in classify_example()\n", sess_id);  JSON_ERROR(errStr, sess_ind); 
    }
    //fprintf(stderr, "Found Session %d %s\n", sess_ind, sess_id);
  }
  response["session_id"] = sessions[sess_ind].id;
  return sess_ind;
}
BOOL CSerialServer::RunDaemon()
{
	WORKSESSION		*pSession;
	char	szBuffer[2048+1];
	int		len;
	long	lCurTime;
	BOOL	bForever = TRUE;

	m_pSaveSession = pSession = NewSession(m_nFD, m_szDevice);
	if (pSession == NULL)
    {
		return FALSE;
    }

	if (!EnterSession(pSession))
	{
		LeaveSession(pSession);
		return FALSE;
	}

	for(;bForever && !m_bExitPending;)
	{
		// Passive mode에서는 수신을 하지 않는다.
		if (m_bPassiveMode)
		{
			USLEEP(1000000);
			continue;
		}

		len	= read(m_nFD, szBuffer, 2048);
		if (len == 0)
		{
			// Timeout Session 
			if (m_nTimeout != -1)
			{
				time(&lCurTime);
				if ((lCurTime-pSession->lLastInput) >= m_nTimeout)
				{
					pSession->lLastInput = lCurTime;
					if (!OnTimeoutSession(pSession))
						break;
				}
			}
			continue;
		}
		else if (len < 0)
		{
			// Terminate Session
			break;
		}
		else
		{
	 		// Receive Session
			time(&pSession->lLastInput);
			AddSessionRecvStream(pSession, szBuffer, len);
		}
	}
	LeaveSession(pSession);
	return FALSE;
}
	void TCPNetwork::Run()
	{
		//Set select parameters 
		auto readSet = m_readSet;
		auto writeSet = m_readSet;
		auto excptSet = m_readSet;
		timeval timeOut{ 0, 1000 };

		//Call select and check result
		auto selectRet = select(0, &readSet, &writeSet, &excptSet, &timeOut);
		auto isFDSetChanged = RunCheckSelectResult(selectRet);
		if (isFDSetChanged == false)
		{
			return;
		}

		//Process FD elements
		if (FD_ISSET(m_serverSocket, &readSet))
		{
			NewSession();
		}
		else
		{
			RunCheckSelectClient(readSet, writeSet, excptSet);
		}
	}
Example #4
0
int EDITAPI EDITFile( char *fn, char *hlib )
/***************************************************/
{
    CurrSession = FindSession( fn );
    if( CurrSession == NULL ) {
        if( StartingSessionInProgress ) {
            return( FALSE );
        }
        StartingSessionInProgress = TRUE;
        // new session must be created before we start the editor so
        // that we can process the WM_DDE_INITIATE message properly
        CurrSession = NewSession( fn, hlib );
        if( CurrSession == NULL ) {
            return( FALSE );
        }
        LinkSession( CurrSession );
        if( spawnlp( P_NOWAIT, _Editor, _Editor, "/W", fn, NULL ) == -1 ) {
            DeleteSession( NULLHANDLE );
            CurrSession = NULL;
            return( FALSE );
        }
    }
    WinSetFocus( HWND_DESKTOP, CurrSession->hwnd );
    return( TRUE );
}
	void TcpNetwork::Run()
	{
		auto read_set = m_Readfds;
		auto write_set = m_Readfds;
		auto exc_set = m_Readfds;

		timeval timeout{ 0, 1000 }; //tv_sec, tv_usec
		auto selectResult = select(0, &read_set, &write_set, &exc_set, &timeout);

		auto isFDSetChanged = RunCheckSelectResult(selectResult);
		if (isFDSetChanged == false)
		{
			return;
		}

		// Accept
		if (FD_ISSET(m_ServerSockfd, &read_set))
		{
			NewSession();
		}
		else // clients
		{
			RunCheckSelectClients(exc_set, read_set, write_set);
		}
	}
//--------------------------------------------------------------
Session_ptr create_session_with_graph(
        tensorflow::GraphDef& graph_def,
        const string device,
        const tensorflow::SessionOptions& session_options)
{
    Session_ptr session(NewSession(session_options));
    if( !session) { ofLogError() << "Error creating session"; return nullptr; }

    if(!device.empty())
        tensorflow::graph::SetDefaultDevice(device, &graph_def);

    log_error(session->Create(graph_def), "Error creating graph for session");
    return session;
}
    int SessionManager::Poll(struct timeval &timeout)
    {
        SetupFdset();
        int ret = ::select( _nfds+1, _read_set, _write_set, _error_set, &timeout);

        if (ret > 0)
        {
            // new connection comes ?
            if (_listen.is_valid() &&  _read_set.is_set( _listen.query_socket() ) )
            {
                DEBUG("new session");
                NewSession();
            }

            SessionList list = SessionMapToList(_sessions);
            // poll read session
            for (SessionList::iterator it=list.begin(); it!=list.end(); it++)
            {
                ISession *session = *it;
                SOCKET s = session->query_socket();

                if (_read_set.is_set(s))
                {
                    // notify the listener
                    int nReturn = session->do_recv();
                    if (nReturn <= 0 )
                    {
                        DEBUG("session close connection");
                        if (nReturn == SOCKET_ERROR)
                        {
                            ERROR("socket wrong and close connection");
                            session->OnError(this, WSAGetLastError(), "socket wrong and close connection" );
                        }

                        // delete session
                        _sessions.erase(session->getid());
                        session->OnDisconnect(this);
                        delete session;
                    }
                    else
                    {
                        session->OnRead(this);
                    }
                }
            } //for

            // poll write and error session
            list = SessionMapToList(_nbconnect_sessions);
            for (SessionList::iterator it=list.begin(); it!=list.end(); it++)
            {
                ISession *session = *it;
                SOCKET s = session->query_socket();

                if (_error_set.is_set(s)) // error
                {
                    _nbconnect_sessions.erase(session->getid());
                    ERROR("connection non-blocking socket error");
                    session->OnError(this, WSAGetLastError(), "connection non-blocking socket error");
                    delete session;
                }
                else if (_write_set.is_set(s)) // write 
                {
                    // check error (when socket error it become writeable on linux)
                    // so must check.
                    int err = 0;
                    socklen_t errlen = sizeof(err);
                    ::getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &errlen);
                    if (err)
                    {
                        _nbconnect_sessions.erase(session->getid());
                        ERROR("connection non-blocking socket error");
                        session->OnError(this, WSAGetLastError(), "connection non-blocking socket error");
                        delete session;
                    }
                    else
                    {
                        // delete from non-blocking connection session
                        _nbconnect_sessions.erase(session->getid());
                        _sessions[session->getid()] = session;
                        session->OnConnect(this);
                    }
                }
            } //for

            // delete session of _delete_sessions
            for (SessionMap::iterator it=_delete_sessions.begin(); it!=_delete_sessions.end(); it++)
            {
                int id = it->first;
                ISession *session = it->second;

                if (_sessions.count(id) > 0)
                {
                    // delete session
                    _sessions.erase(id);
                    session->OnDisconnect(this);
                    delete session;
                }
                else if (_nbconnect_sessions.count(id) > 0)
                {
                    // just delete session
                    _nbconnect_sessions.erase(id);
                    delete session;
                }
            } //for
            _delete_sessions.clear();
        } // if

        return ret;
    }
DWORD CSerialServer::ReadProc()
{
    OVERLAPPED osReader;						// Overlapped structure for read operations
    OVERLAPPED osStatus;						// Overlapped structure for status operations
    HANDLE     arEvents[3];						// Event Array	
    DWORD      dwStoredFlags;					// Local copy of event flags
    DWORD      dwCommEvent=0;					// Result from WaitCommEvent
    DWORD 	   dwRead;							// Bytes actually read
#ifndef WINCE
    DWORD      dwResult;						// Result from WaitForSingleObject
#endif
    BOOL       fWaitingOnRead;
    BOOL       fWaitingOnStat;
    BOOL       fThreadDone;
#ifndef WINCE
    DWORD      dwOvRes;							// Result from GetOverlappedResult
#endif

	m_pSaveSession = NewSession(m_hComPort, m_szDevice);
	OnEnterSession(m_pSaveSession);

    dwStoredFlags	= 0xFFFFFFFF;
    fWaitingOnRead	= FALSE;
    fWaitingOnStat	= FALSE;
    fThreadDone		= FALSE;

    // Create two overlapped structures, one for read events
    // and another for status events
	memset(&osReader, 0, sizeof(OVERLAPPED));
    osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (osReader.hEvent == NULL)
        XDEBUG("[CSerialServer] CreateEvent (Reader Event).\n");

	memset(&osStatus, 0, sizeof(OVERLAPPED));
    osStatus.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (osStatus.hEvent == NULL)
        XDEBUG("[CSerialServer] CreateEvent (Status Event).\n");

    arEvents[0] = m_hReadStopEvent;
    arEvents[1] = osReader.hEvent;
    arEvents[2] = osStatus.hEvent;

    // Initial Check, Forces Updates
	CheckModemStatus(TRUE);
	CheckComStat(TRUE);

	m_bRecvReady = TRUE;
    while(!fThreadDone && !m_bDisconnectPending)
	{
		if (m_bPassiveMode)
		{
			Sleep(100);
			continue;
		}

		if (!ReadFile(m_hComPort, m_szBuffer, DEFAULT_SIO_BUFFER, &dwRead, &osReader))
		{
			// Read not delayed?
			if (GetLastError() != ERROR_IO_PENDING)
				XDEBUG("[CSerialComm] ReadFile in ReaderAndStatusProc.\r\n");
		}
#ifndef WINCE
		else
		{
			// Read Completed Immediately
			if ((dwRead != MAX_READ_BUFFER) && m_bDisplayTimeouts)
				XDEBUG("[CSerialComm] Read timed out immediately.\r\n");
		}

		dwResult = WaitForMultipleObjects(3, arEvents, FALSE, STATUS_CHECK_TIMEOUT);
		switch(dwResult) {
          case WAIT_OBJECT_0 : // Thread Exit Event
			   fThreadDone = TRUE;
			   break;

		  case WAIT_OBJECT_0 + 1 : // Read Completed
			   if (!GetOverlappedResult(m_hComPort, &osReader, &dwRead, FALSE))
			   {
				   if (GetLastError() == ERROR_OPERATION_ABORTED)
					   XDEBUG("[CSerialComm] Read aborted.\r\n");
				   else ErrorHandler(const_cast<char*>("[CSerialServer] GetOverlappedResult (in Reader).\r\n"));
			   }
			   else
			   {	
				   // Read Completed Successfully
				   if ((dwRead != MAX_READ_BUFFER) && m_bDisplayTimeouts)
					   XDEBUG("[CSerialComm] Read timed out overlapped.\r\n");

				   if (dwRead > 0)
						OnReceiveSession(m_pSaveSession, (char *)m_szBuffer, dwRead);
			   }
			   fWaitingOnRead = FALSE;
			   break;

		  case WAIT_OBJECT_0 + 2 : // Status Completed
			   if (!GetOverlappedResult(m_hComPort, &osStatus, &dwOvRes, FALSE))
			   {
				   if (GetLastError() == ERROR_OPERATION_ABORTED)
						XDEBUG("[CSerialServer] WaitCommEvent aborted.\n");
				   else ErrorHandler(const_cast<char*>("[CSerialServer] GetOverlappedResult (in Reader).\r\n"));
			   }
			   else
			   {
				   // status check completed successfully
				   ReportStatusEvent(dwCommEvent);
			   }
			   fWaitingOnStat = FALSE;
			   break;

            case WAIT_TIMEOUT:
                // If status checks are not allowed, then don't issue the
                // modem status check nor the com stat check
                if (!m_bNoStatus)
				{
                    CheckModemStatus(FALSE);
                    CheckComStat(FALSE);
                }
                break;                       

            default:
                XDEBUG("[CSerialServer] WaitForMultipleObjects(Reader & Status handles).\r\n");
                break;
        }
#else
		if (dwRead > 0)
			OnReceiveSession(m_pSaveSession, (char *)m_szBuffer, dwRead);
#endif
    }

	OnLeaveSession(m_pSaveSession);
	DeleteSession(m_pSaveSession);

	// Set SendThread Exit Event
	SetEvent(m_hThreadExitEvent);
	m_bExitWriter = TRUE;

	WaitForSingleObject(m_hSendTerminateEvent, 5000);

    // Close event handles
    CloseHandle(osReader.hEvent);
    CloseHandle(osStatus.hEvent);

	// Set Terminate Signal
	SetEvent(m_hReadTerminateEvent);
	return 0;
}
Example #9
0
File: App.cpp Project: Stretto/mago
    int RunSingleSessionLoop( const wchar_t* sessionUuidStr )
    {
        HRESULT     hr = S_OK;
        MSG         msg;
        int         sessionCount = 0;
        UINT_PTR    timerId = 0;

        // Make these available for as soon as the server starts listening for calls
        gMainTid = GetCurrentThreadId();

        hr = InitSingleSessionLoop( sessionUuidStr );
        if ( FAILED( hr ) )
            return hr;

        // force the OS to make a message queue
        PeekMessage( &msg, NULL, 0, 0, FALSE );

        timerId = SetTimer( NULL, 1, ConnectTimeoutMillis, NULL );
        if ( timerId == 0 )
            return HRESULT_FROM_WIN32( GetLastError() );

        while ( GetMessage( &msg, NULL, 0, 0 ) )
        {
            if ( msg.hwnd == NULL )
            {
                switch ( msg.message )
                {
                case WM_TIMER:
                    KillTimer( NULL, timerId );
                    timerId = 0;
                    if ( NewSession() )
                    {
                        // Because NewSession just claimed the only debugging session, it means 
                        // that no other debugging session was opened, no other session can be 
                        // opened, and time ran out. So, quit.
                        PostQuitMessage( ConnectTimeoutErrorCode );
                    }
                    break;

                case WM_MAGO_SESSION_ADDED:
                    sessionCount++;
                    break;

                case WM_MAGO_SESSION_DELETED:
                    sessionCount--;
                    if ( sessionCount == 0 )
                    {
                        PostQuitMessage( 0 );
                    }
                    break;
                }
            }
        }

        if ( timerId != 0 )
            KillTimer( NULL, timerId );

        UninitRpcServer();

        return (int) msg.wParam;
    }
Example #10
0
    void Tensorflow::consume(IConsumer::info consume_info,
                             ssi_size_t stream_in_num,
                             ssi_stream_t stream_in[]) {

        ssi_real_t *dataptr = ssi_pcast(ssi_real_t, stream_in[0].ptr);

        tensorflow::Session *session;
        tensorflow::Status status = NewSession(tensorflow::SessionOptions(), &session);
        if (!status.ok()) {
            ssi_wrn("status: %s \n", status.ToString().c_str());
            return;
        }

        tensorflow::GraphDef graph_def;

#if __ANDROID__
        status = ReadTextProto(tensorflow::Env::Default(), "/sdcard/android_xmlpipe/frozen_graph.pb", &graph_def);
#else
        status = ReadTextProto(tensorflow::Env::Default(),
                               "/home/mainuser/code/SSI/mobileSSI/plugins/tensorflow/test_files/frozen_graph.pb",
                               &graph_def);
#endif

        if (!status.ok()) {
            ssi_wrn("status: %s \n", status.ToString().c_str());
            return;
        }

        status = session->Create(graph_def);
        if (!status.ok()) {
            ssi_wrn("status: %s \n", status.ToString().c_str());
            return;
        }

        int number_dim = stream_in[0].dim;
        int number_test = stream_in[0].num; // 4072
        int number_classes = 4;

        tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({number_test, number_dim}));
        auto dst = input_tensor.flat<float>().data();
        for (int i = 0; i < stream_in[0].num; i++) {
            std::copy_n(dataptr + i * number_dim, number_dim, dst);
            dst += number_dim;
        }

        std::vector<std::pair<std::string, tensorflow::Tensor>> inputs = {{"input_TT", input_tensor}};
        std::vector<tensorflow::Tensor> outputs;
        status = session->Run(inputs, {"output_TT"}, {}, &outputs);
        if (!status.ok()) {
            ssi_wrn("status: %s \n", status.ToString().c_str());
            return;
        }

        std::vector<int> number_hits(number_classes, 0);
        for (std::vector<tensorflow::Tensor>::iterator it = outputs.begin(); it != outputs.end(); ++it) {
            auto items = it->shaped<float, 2>({number_test, number_classes});
            for (int i = 0; i < number_test; i++) {
                int arg_max = 0;
                float val_max = items(i, 0);
                for (int j = 0; j < number_classes; j++) {
                    if (items(i, j) > val_max) {
                        arg_max = j;
                        val_max = items(i, j);
                    }
                }
                for (int i = 0; i < number_classes; i++) {
                    if (arg_max == i) {
                        number_hits[i]++;
                    }
                }
            }
        }

        std::string classes[] = {"ambient_animals", "rain", "running_water", "traffic"};
        for (int i = 0; i < number_classes; i++) {
            float accuracy = (float) number_hits[i] / number_test;
            ssi_wrn("accuracy for class %s : %f \n", classes[i].c_str(), accuracy);
            _probs[i] = accuracy;
        }
        session->Close();

        _handler->handle(consume_info.time, consume_info.dur, 4, 0, _probs, _class_names, 0, 0);
    }