void RobotControl::synchronizeTime()
{
	char buffer[1000];
        bool writeStatus;
	sprintf(buffer, "t %d\n", LoggerTime::timer());
        writeStatus = port.write(buffer, strlen(buffer));
        port.flush();
        sleepMs(200);
        //qDebug() << "Writing to port: " << buffer << " Stauts: " << writeStatus;
	int count = 0;
        const int C_MAX = 100;
	is_time_synced = false;
	while (!is_time_synced && count < C_MAX)
	{
            sprintf(buffer, "t %d\n", LoggerTime::timer());
            writeStatus = port.write(buffer, strlen(buffer));
            sleepMs(200);
            //qDebug() << "Writing to port: " << buffer << " Stauts: " << writeStatus;
            RobotOutput output = parse_robot_out();
            if (output.type == TIMESTAMP)
            {
                    is_time_synced = true;
                    delta_time = output.param2 - output.param1;
            }
            ++count;
	}
}
Example #2
0
bool clsResultPro::waitDut()
{
    blStop = true;

    double item1,item2;

    clsRS::getInst().sendCommand(":METER:SPEED MAX",false);

    while(blStop)
    {
        qApp->processEvents();
        emit move();
        sleepMs(80);

        if(Trigger(item1,item2))
        {
            if((item1>=this->Value/5.0 )&& (item1< this->Value*5.0))
            {
                // qDebug()<<"Short circuit";
                return true;
            }
            else
            {
                // qDebug()<<"Open circuit";
                return false;
            }
        }
        else
            return false;
    }

    return false;

}
Example #3
0
    void NewSearcher::searchPorts()
    {
        if ( !m_isFinished )
        {
            std::vector<NewSearcher*> searchers;

            m_validPorts.clear();

            for ( size_t index = 0; index < m_portList.size(); ++index )
            {
                NewSearcher* searcher = new NewSearcher(m_portList[index]);
                searcher->start();
                searchers.push_back(searcher);
            }


            for ( size_t index = 0; index < searchers.size(); ++index )
            {
                while ( !searchers[index]->isFinished() )
                {
                    sleepMs(1);
                }

                if ( searchers[index]->m_validPorts.size() > 0 )
                {
                    m_validPorts.insert(m_validPorts.end(), searchers[index]->m_validPorts.begin(), searchers[index]->m_validPorts.end());
                }

                delete searchers[index];
            }
        }
    }
Example #4
0
void FileWaitForDirDeleted(OovStringRef const path, int waitMs)
{
#ifndef __linux__
    int minWait = 100;
    int count = waitMs / minWait;
    bool deleted = false;
    bool success = true;
    for(int tries=0; tries<count && success; tries++)
    {
        if(!FileIsDirOnDisk(path, success))
        {
            deleted = true;
            break;
        }
        else
        {
            sleepMs(minWait);
        }
    }
    if(!success || !deleted)
    {
        OovString str = "Unable to delete directory: ";
        str += path;
        OovError::report(ET_Error, str);
    }
#endif
}
Example #5
0
	int main() {
		int pipe_fds[2];
		int n;
		char buf[0x101] = {0};
		pid_t pid;
		
		pipe(pipe_fds);

		char *cmd[] = {"/home/nikolai/motivational_abyss/playground/nw_analysis/hooklib/sr", NULL};

		if ((pid = fork()) == 0) { /* child */
			dup2(pipe_fds[1], 1); // set stdout of the process to the write end of the pipe
			execvp(cmd[0], cmd); // execute the program.
			fflush(stdout);
			perror(cmd[0]); // only reached in case of error
			exit(0);
		} else if (pid == -1) { /* failed */
			perror("fork");
			exit(1);
		} else { /* parent */

			while (1) {
				sleepMs(1500); // Wait a bit to let the child program run a little
				printf("Trying to read every 1500ms\n");
				if ((n = read(pipe_fds[0], buf, 0x100)) >= 0) { // Try to read stdout of the child process from the read end of the pipe
					buf[n] = 0; /* terminate the string */
					fprintf(stdout, "Got:\n%s", buf);
				} else {
					fprintf(stderr, "read failed\n");
					perror("read");
				}
			}
		}
	}
Example #6
0
OovStatusReturn FileWaitForDirDeleted(OovStringRef const path, int waitMs)
    {
    OovStatus status(true, SC_File);
#ifndef __linux__
    int minWait = 100;
    int count = waitMs / minWait;
    bool deleted = false;
    for(int tries=0; tries<count && status.ok(); tries++)
        {
        if(!FileIsDirOnDisk(path, status))
            {
            deleted = true;
            break;
            }
        else
            {
            sleepMs(minWait);
            }
        }
    if(status.ok() && !deleted)
        {
        status.set(false, SC_Time);
        }
    if(status.needReport())
        {
        OovString str = "Unable to delete directory: ";
        str += path;
        OovError::report(ET_Error, str);
        }
#endif
    return status;
    }
Example #7
0
/*the ticker thread function that executes the filters */
void * ms_ticker_run(void *arg)
{
	uint64_t realtime;
	int64_t diff;
	MSTicker *s=(MSTicker*)arg;
	int lastlate=0;
	int precision=2;
	int late;
	
	precision = set_high_prio(s);


	s->ticks=1;
	ms_mutex_lock(&s->lock);
	s->orig=s->get_cur_time_ptr(s->get_cur_time_data);

	while(s->run){
		s->ticks++;
		{
#if TICKER_MEASUREMENTS
			MSTimeSpec begin,end;/*used to measure time spent in processing one tick*/
			double iload;

			ms_get_cur_time(&begin);
#endif
			run_graphs(s,s->execution_list,FALSE);
#if TICKER_MEASUREMENTS
			ms_get_cur_time(&end);
			iload=100*((end.tv_sec-begin.tv_sec)*1000.0 + (end.tv_nsec-begin.tv_nsec)/1000000.0)/(double)s->interval;
			s->av_load=(smooth_coef*s->av_load)+((1.0-smooth_coef)*iload);
#endif
		}
		
		s->time+=s->interval;
		while(1){
			realtime=s->get_cur_time_ptr(s->get_cur_time_data)-s->orig;
			ms_mutex_unlock(&s->lock);
			diff=s->time-realtime;
			if (diff>0){
				/* sleep until next tick */
				sleepMs((int)diff);
			}else{
				late=(int)-diff;
				if (late>s->interval*5 && late>lastlate){
					ms_warning("%s: We are late of %d miliseconds.",s->name,late);
				}
				lastlate=late;
				break; /*exit the while loop */
			}
			ms_mutex_lock(&s->lock);
		}
		ms_mutex_lock(&s->lock);
	}
	ms_mutex_unlock(&s->lock);
	unset_high_prio(precision);
	ms_message("%s thread exiting",s->name);

	ms_thread_exit(NULL);
	return NULL;
}
Example #8
0
static uint8_t* getMemoryInternal(PluginData* data, const char* tempfile, size_t* readSize, uint16_t address, uint16_t addressEnd)
{
	*readSize = 0;

#ifndef _WIN32
	if (unlink(tempfile) < 0)
	{
		printf("c64_vice: Unable to delete %s (error %d)\n", tempfile, errno);
	}
#else
	// TODO: Implement me.
	/*
	if (DeleteFile(tempfile) != 0)
	{
		printf("failed to delete %s\n", timepfile); 
		return 0;
	}
	*/
#endif

    sendCommand(data, "save \"%s\" 0 %04x %04x\n", tempfile, address, addressEnd);

    // Wait 10 ms for operation to complete and if we can't open the file we try for a few times and if we still can't we bail

    sleepMs(10);

    for (int i = 0; i < 10; ++i)
    {
        uint8_t* mem = loadToMemory(data->tempFileFull, readSize);

        if (!mem)
        {
            sleepMs(1);
            continue;
        }

        printf("returing mem...\n");

        return mem;
    }

    printf("Unable to get memory...\n");

    return 0;
}
Example #9
0
void PacketUsbCdc::sleepMs( int ms )
{
  #ifdef Q_WS_WIN
  Sleep( ms );
  #endif
  #ifdef Q_WS_MAC
  sleepMs( ms );
  #endif
}
Example #10
0
void NewThread::stop()
{
    m_isRunning = false;

	while (!m_isFinished)
	{
		sleepMs(1);
	}
}
void RobotControl::initPort ()
{
	port.setBaudRate(BAUD57600);
	port.setFlowControl(FLOW_OFF);
	port.setParity(PAR_NONE);
	port.setDataBits(DATA_8);
	port.setStopBits(STOP_2);
        bool status = port.open(QIODevice::ReadWrite|QIODevice::Unbuffered);
        qDebug() << "Port Open Status: " << status;
        sleepMs(1000);
}
Example #12
0
void BucketsMaker::run()
{
    while (g_keepRunning) {
        sleepMs(100);
        try {
            doWork();
        }
        catch (...) {
            cerr << "Crashed BucketMaster thread" << endl;
            return;
        }
    }
}
int wait_for_data(PluginData* data, char** resBuffer, int* len) {
    const int maxTry = 1000;

    for (int i = 0; i < maxTry; ++i) {
        get_data(data, resBuffer, len);

        if (*len != 0)
            return 1;

        sleepMs(1);
    }

    return 0;
}
Example #14
0
void *th_DoReadKB( void *param ) {
	FNINPUT fCallBack;
	fCallBack = (FNINPUT)(param);
	
	while ( 1 ) {
		if ( fCallBack != NULL ) {
			fCallBack();
		} else {
			kbPutCh();
		}
		#if KB_MS_REFRESH > 0
		sleepMs( KB_MS_REFRESH );
		#endif
	}
	pthread_exit(NULL);
}	
Example #15
0
void *th_DoScreenRepaint( void *param ) {
	FNINPUT fCallBack;
	fCallBack = (FNINPUT)(param);
	
	while ( 1 ) {
		if ( fCallBack != NULL ) {
			fCallBack();
		} else {
			scrRepaint();
		}			
		#if SCR_MS_REFRESH != 0
		sleepMs( SCR_MS_REFRESH );
		#endif
	}

	pthread_exit( NULL );
}
Example #16
0
void * ms_ticker_run(void *arg)
{
	uint64_t realtime;
	int64_t diff;
	MSTicker *s=(MSTicker*)arg;
	int lastlate=0;
	int precision=2;
	int late;
	
	precision = set_high_prio();


	s->ticks=1;
	ms_mutex_lock(&s->lock);
	s->orig=s->get_cur_time_ptr(s->get_cur_time_data);

	while(s->run){
		s->ticks++;
		run_graphs(s,s->execution_list,FALSE);
		s->time+=s->interval;
		while(1){
			realtime=s->get_cur_time_ptr(s->get_cur_time_data)-s->orig;
			ms_mutex_unlock(&s->lock);
			diff=s->time-realtime;
			if (diff>0){
				/* sleep until next tick */
				sleepMs(diff);
			}else{
				late=-diff;
				if (late>s->interval*5 && late>lastlate){
					ms_warning("We are late of %d miliseconds.",late);
				}
				lastlate=late;
				break; /*exit the while loop */
			}
			ms_mutex_lock(&s->lock);
		}
		ms_mutex_lock(&s->lock);
	}
	ms_mutex_unlock(&s->lock);
	unset_high_prio(precision);
	ms_message("MSTicker thread exiting");

	ms_thread_exit(NULL);
	return NULL;
}
Example #17
0
void BootupAnimation::renderThread()
{
	while (m_state != StateIdle) {

		switch (m_state) {
		case (StateLogo):
			renderInStateLogo();
			break;
		case (StateActivity):
			renderInStateActivity();
			break;
		default:
			break;
		}

		sleepMs(s_frameTime);
	}
}
static bool load_image(PluginData* data, const char* filename) {
    char* res = 0;
    int len = 0;

    send_command(data, "load \"%s\" 0\n", filename);

    sleepMs(200);

    if (!get_data(data, &res, &len)) {
        log_debug("failed to get any data back from load...\n", "");
        return false;
    }

    log_debug("res %s\n", res);

    // TODO: Parse that we actually manage to load the image

    return true;
}
static bool get_dataToBuffer(PluginData* data, char* resBuffer, int bufferSize, int* len, int maxTry) {
    int res = 0;
    int lenCount = 0;

    if (!data->conn) {
        return false;
	}

    memset(resBuffer, 0, bufferSize);

    for (int i = 0; i < maxTry; ++i) {
        bool gotData = false;

        //log_debug("trying to get data %d\n", i);

        while (VICEConnection_pollRead(data->conn)) {
            res = VICEConnection_recv(data->conn, resBuffer, bufferSize - lenCount, 0);

            if (res == 0)
                break;

            gotData = true;

            resBuffer += res;
            lenCount += res;
        }

        if (gotData) {
            log_debug("got some data, len %d", lenCount);

            *len = lenCount;
            return true;
        }

        sleepMs(1);
    }

    log_debug("no data from VICE\nn", "");

    return false;
}
static void send_command(PluginData* data, const char* format, ...) {
    va_list ap;
    char buffer[2048];

    va_start(ap, format);
    vsprintf(buffer, format, ap);
    va_end(ap);

    int len = (int)strlen(buffer);

    if (!data->conn) {
        return;
	}

    int ret = VICEConnection_send(data->conn, buffer, len, 0);
    (void)ret;

    log_debug("sent command %s (%d - %d)\n", buffer, len, ret);

    sleepMs(1);
}
Example #21
0
gboolean Editor::onIdle(gpointer data)
    {
    if(mDebugOut.length())
        {
        GtkTextView *view = GTK_TEXT_VIEW(ControlWindow::getTabView(
            ControlWindow::CT_Control));
        Gui::appendText(view, mDebugOut);
        Gui::scrollToCursor(view);
        mDebugOut.clear();
        }
    eDebuggerChangeStatus dbgStatus = mDebugger.getChangeStatus();
    if(dbgStatus != DCS_None)
        {
        idleDebugStatusChange(dbgStatus);
        }
    getEditFiles().onIdle();
    OovIpcMsg msg;
    if(mEditorIpc.getMessage(msg))
        {
        OovString cmd = msg.getArg(0);
        if(cmd[0] == EC_ViewFile)
            {
            OovString fn = msg.getArg(1);
            OovString lineNumStr = msg.getArg(2);
            int lineNum = 1;
            size_t pos = lineNumStr.findSpace();
            if(pos != std::string::npos)
                {
                lineNumStr = lineNumStr.substr(0, pos);
                }
            if(lineNumStr.getInt(0, INT_MAX, lineNum))
                {
                }
            gEditor->getEditFiles().viewModule(fn, lineNum);
            }
        }
    sleepMs(5);
    return true;
    }
Example #22
0
/* position: o c */
int filterwheel_send(int position)
{
	int bytes_to_send = 1;
	char buffer[80];
#ifdef POSIX
	printf("write to filterwheel: %i \n", position);
	write(fd, &position, bytes_to_send);
	while(1){
		read(fd, buffer, 80);

		if (strstr(buffer, "done") != NULL) {
			return 0;
		}
		sleepMs(100);
	}
	return 0;
#else
	/* Send specified text (remaining command line arguments) */
	DWORD bytes_written, total_bytes_written = 0;
	return WriteFile(hSerial, bytes_to_send, 5, &bytes_written, NULL);
#endif
}
static void launch_vice_with_config(PluginData* data) {
    int r, cmdIndex = 1;
    uv_process_options_t options = { 0 };

    log_debug("spawning vice...\n", "");

    char* args[10];
    args[0] = (char*)data->config.vice_exe;

    // TODO: Must generate the breakpoint file from the json one

    args[cmdIndex++] = "-remotemonitor";

    if (data->config.breakpoint_file) {
        //args[cmdIndex++] = "-moncommands";
        //args[cmdIndex++] = "examples/c64_vice/test_mon.txt";
    }

    //args[cmdIndex++] = (char*)data->config.prg_file;
    args[cmdIndex++] = NULL;

    options.exit_cb = 0;
    options.file = data->config.vice_exe;
    options.args = args;

    if ((r = uv_spawn(uv_default_loop(), &data->process, &options))) {
        MESSAGE_FUNCS->error("Unable to launch VICE", uv_strerror(r));
        return;
    }

    sleepMs(3000);

    connect_to_local_host(data);

    // if connected we load the image and make sure we get a reply back

    if (VICEConnection_isConnected(data->conn)) {
        log_debug("connected to vice...\n", "");

        if (!load_image(data, data->config.prg_file)) {
            return;
		}

        log_debug("image loaded ...\n", "");

        // parse the

        parse_mon_file(data, data->config.breakpoint_file);

        log_debug("start from basic...\n", "");

        // start vice!

        log_debug("started from basic\n", "");

        uint16_t address = 0; //get_basic_start(data);

        parse_mon_file(data, data->config.breakpoint_file);

        if (address != 0) {
            log_debug("start from %x\n", address);
            send_command(data, "g %x\n", address);
        }

        return;
    }

    log_debug("unable to make connection with vice\n", "");
}
Example #24
0
int main(int argc, char *argv []){
        int t;
        t=atoi(argv[1]);
        sleepMs(t);
        return 0;
}
Example #25
0
void ItemsMaker::doWork()
{
    int r = rand_r(&m_randSeed);
    r = r % (int)m_sleepMs();

    int first = -1;
    string bucket;
    ItemsListPtr items;
    {
        boost::lock_guard<boost::mutex> lock(g_data.m_mutex);
        if (g_data.m_buckets.empty()) {
            return;
        }

        int n = r % g_data.m_buckets.size();
        BucketsMap::iterator iter = g_data.m_buckets.begin();

        for (int i = 0; iter != g_data.m_buckets.end(); i++, iter++) {
            if (i == n) {
                break;
            }
        }

        if (iter == g_data.m_buckets.end()) {
            cout << "ItemsMaker: Failed to find bucket" << endl;
            return;
        }

        bucket = iter->first;
        items = iter->second;
        if (!items->empty()) {
            first = *items->begin();
        }
    }

    if (r < m_multipliyer() * m_reconnectProbability()) {
        m_sock.disconnect();
        sleepMs(20);
        m_sock.connect("localhost", m_port);
    }

    int prob = m_multipliyer() * m_createProbability();
    if (r < prob) {
        // Add item
        string cmd = string("create ") + bucket + " 1111";
        execCommand(m_sock, cmd, m_buffer);

        int id;
        int n = sscanf(m_buffer.raw(), "%d", &id);
        if (n == 1) {
            boost::lock_guard<boost::mutex> lock(g_data.m_mutex);
            items->push_back(id);
        }
        else {
            //cout << "Failed to add item: " << m_buffer.raw() << endl;
        }
        return;
    }

    prob += m_multipliyer() * m_deleteProbability();
    if (r < prob && !items->empty()) {
        // Delete item
        string cmd = string("delete ") + bucket + " " + boost::lexical_cast<string>(first);
        execCommand(m_sock, cmd, m_buffer);

        if (strcmp(m_buffer.raw(), "ok") == 0) {
            boost::lock_guard<boost::mutex> lock(g_data.m_mutex);
            if (*items->begin() == first) {
                items->erase(items->begin());
            }
        }
        else {
            //cout << "Failed to delete item: " << m_buffer.raw() << endl;
        }
        return;
    }

    prob += m_multipliyer() * m_updateProbability();
    if (r < prob && !items->empty()) {
        // Update item
        string cmd = string("update ") + bucket + " " + boost::lexical_cast<string>(first) + " 2222";
        execCommand(m_sock, cmd, m_buffer);

        if (strcmp(m_buffer.raw(), "ok") != 0) {
            //cout << "Failed to update item: " << m_buffer.raw() << endl;
        }
        return;
    }

    prob += m_multipliyer() * m_readProbability();
    if (r < prob && !items->empty()) {
        // Read item
        string cmd = string("read ") + bucket + " " + boost::lexical_cast<string>(first);
        execCommand(m_sock, cmd, m_buffer);
    }

    prob += m_multipliyer() * m_invalidProbability();
    if (r < prob && !items->empty()) {
        // Invalid command
        string cmd = string("invalide command");
        execCommand(m_sock, cmd, m_buffer);
    }
}
Example #26
0
int main( int argc, char *argv[] ) {

//	p_gate g0;
//	p_gate g1;
//	p_wire w_reset, w_clock;
//	p_bus  b_signals;

	//------------------------------------------------------------------------
	//	Callback Init

	lfunct_accoda( &p_all_inits, (FN_VOID_VOID) Init );
	lfunct_accoda( &p_all_inits, (FN_VOID_VOID) boardInit );
	lfunct_accoda( &p_all_inits, (FN_VOID_VOID) PowerInit );
	lfunct_accoda( &p_all_inits, (FN_VOID_VOID) ClockInit );
	lfunct_accoda( &p_all_inits, (FN_VOID_VOID) ResetInit );
	lfunct_accoda( &p_all_inits, (FN_VOID_VOID) MProcInit );
	lfunct_accoda( &p_all_inits, (FN_VOID_VOID) MemoryInit );
	lfunct_accoda( &p_all_inits, (FN_VOID_VOID) Programma );
	
	p_ListFunct p_fList;
	for ( p_fList = p_all_inits; p_fList != NULL; p_fList = p_fList->nList ) {
		p_fList->fFunc();
	}

	//------------------------------------------------------------------------
	//	Callback self connect

	lfunct_accoda( &p_all_self_connect, (FN_VOID_VOID) devPower->self_connect );
	lfunct_accoda( &p_all_self_connect, (FN_VOID_VOID) devMProc->self_connect );
	lfunct_accoda( &p_all_self_connect, (FN_VOID_VOID) devMemory->self_connect );

	for ( p_fList = p_all_self_connect; p_fList != NULL; p_fList = p_fList->nList ) {
		p_fList->fFunc();
	}

	//------------------------------------------------------------------------
	//	Callback task

	lfunct_accoda( &p_all_tasks, (FN_VOID_VOID) all_wires_add_tick );
//	lfunct_accoda( &p_all_tasks, (FN_VOID_VOID) devPower->task );
//	lfunct_accoda( &p_all_tasks, (FN_VOID_VOID) devReset->task );
	lfunct_accoda( &p_all_tasks, (FN_VOID_VOID) devClock->task );
	lfunct_accoda( &p_all_tasks, (FN_VOID_VOID) devMProc->task );
	lfunct_accoda( &p_all_tasks, (FN_VOID_VOID) devMemory->task );

	//------------------------------------------------------------------------
	//	Visualizzazione
	//lFnDisp_accoda( &p_all_display, *(gatesShow)(&pWindows->Bus) );
	devMProc->mp_gate[ MP__CLOCK ]->Wire->visible 	= W_VISIBLE;
	//devMProc->mp_gate[ MP_VCC ]->Wire->visible 		= W_VISIBLE;
	//devMProc->mp_gate[ MP_GND ]->Wire->visible 		= W_VISIBLE;
	//devMProc->mp_gate[ MP__RESET ]->Wire->visible 	= W_VISIBLE;	
	devMProc->mp_gate[ MP__M1 ]->Wire->visible 		= W_VISIBLE;
	devMProc->mp_gate[ MP__MREQ ]->Wire->visible 	= W_VISIBLE;
	devMProc->mp_gate[ MP__RD ]->Wire->visible 		= W_VISIBLE;
	devMProc->mp_gate[ MP__WR ]->Wire->visible 		= W_VISIBLE;
	
	devMProc->mp_gate[ MP_Data_00 ]->Wire->visible 	= W_VISIBLE;
	devMProc->mp_gate[ MP_Data_01 ]->Wire->visible 	= W_VISIBLE;
	devMProc->mp_gate[ MP_Data_02 ]->Wire->visible 	= W_VISIBLE;
	devMProc->mp_gate[ MP_Data_03 ]->Wire->visible 	= W_VISIBLE;
	devMProc->mp_gate[ MP_Data_04 ]->Wire->visible 	= W_VISIBLE;
	devMProc->mp_gate[ MP_Data_05 ]->Wire->visible 	= W_VISIBLE;
	devMProc->mp_gate[ MP_Data_06 ]->Wire->visible 	= W_VISIBLE;
	devMProc->mp_gate[ MP_Data_07 ]->Wire->visible 	= W_VISIBLE;
	
	//------------------------------------------------------------------------
	//	Board

	//b_signals = new_bus( "SIGNALS", NULL );
	//bus_add_wire( b_signals,  devClock->w_clock );

	//------------------------------------------------------------------------
	//	Esecuzione procedure

	while ( 1 ) {

		for ( p_fList = p_all_tasks; p_fList != NULL; p_fList = p_fList->nList ) {
			p_fList->fFunc();
		}

		mprocShow( &pWindows->MProc );
#ifdef _C_CYGWIN
		busShow( &pWindows->Bus );
//		gatesShow( &pWindows->Gates );
		memoryShow( &pWindows->Memory );
#endif
		
		sleepMs(200);
	}

	//------------------------------------------------------------------------
	//	FINE

	return 0;

}
Example #27
0
void BucketsMaker::doWork()
{
    int r = rand_r(&m_randSeed);
    r = r % (int)m_sleepMs();

    bool buckets_empty;
    string first_bucket;
    {
        boost::lock_guard<boost::mutex> lock(g_data.m_mutex);
        buckets_empty = g_data.m_buckets.empty();
        if (!buckets_empty) {
            first_bucket = g_data.m_buckets.begin()->first;
        }
    }

    if (r < m_multipliyer() * m_reconnectProbability()) {
        m_sock->disconnect();
        sleepMs(20);
        m_sock->connect("localhost", m_port);
    }

    int prob = m_multipliyer() * m_addProbability();
    if (r < prob || buckets_empty) {
        // Add bucket
        int nextId = g_data.m_maxBucketId + 1;
        string bucket = string("buck_") + boost::lexical_cast<string>(nextId);
        string cmd = string("add ") + bucket;
        execCommand(*m_sock, cmd, *m_buffer);

        if (strcmp(m_buffer->raw(), "ok") == 0) {
            boost::lock_guard<boost::mutex> lock(g_data.m_mutex);
            ItemsListPtr items(new list<int>);
            g_data.m_buckets[bucket] = items;
            g_data.m_maxBucketId = nextId;
        }
        else {
            cout << "Failed to add bucket: " << m_buffer->raw() << endl;
        }
        return;
    }

    prob += m_multipliyer() * m_deleteProbability();
    if (r < prob && !buckets_empty) {
        // Delete bucket
        string cmd = string("drop ") + first_bucket;
        execCommand(*m_sock, cmd, *m_buffer);

        if (strcmp(m_buffer->raw(), "ok") == 0) {
            boost::lock_guard<boost::mutex> lock(g_data.m_mutex);
            g_data.m_buckets.erase(g_data.m_buckets.begin());
        }
        else {
            cout << "Failed to delete bucket: " << m_buffer->raw() << endl;
        }
        return;
    }

    prob += m_multipliyer() * m_listProbability();
    if (r < prob) {
        // List buckets
        string cmd = "list";
        execCommand(*m_sock, cmd, *m_buffer);
        return;
    }

    prob += m_multipliyer() * m_invalidProbability();
    if (r < prob) {
        // Invalid command
        string cmd = "invalid command";
        execCommand(*m_sock, cmd, *m_buffer);
        return;
    }
}
Example #28
0
UsbSerial::UsbStatus UsbSerial::usbOpen( )
{
  QMutexLocker locker( &usbOpenMutex );
  
  // Linux Only
  #if (defined(Q_WS_LINUX))
	  printf( "OSC over USB not implemented in Linux\n" );
    return NOT_OPEN;
  #endif

  //Mac-only
	#ifdef Q_WS_MAC
		if( deviceOpen )  //if it's already open, do nothing.
		  return ALREADY_OPEN;

		kern_return_t kernResult;
		io_iterator_t iterator = 0;
		
		kernResult = getDevicePath( iterator, deviceFilePath, sizeof(deviceFilePath) );
		IOObjectRelease( iterator ); // clean up
		
		if (!deviceFilePath[0] )
    {
			//printf("Didn't find a Make Controller.\n");
			return NOT_OPEN;
    }
		
		// now try to actually do something
		deviceHandle = ::open( deviceFilePath, O_RDWR | O_NOCTTY | ( ( blocking ) ? 0 : O_NDELAY ) );
		if ( deviceHandle < 0 )
	  {
	    //printf( "Could not open the port (Error %d)\n", deviceHandle );
	    return NOT_OPEN;
	  } else
		{
	    deviceOpen = true;
			sleepMs( 10 ); //give it a moment after opening before trying to read/write
			// printf( "USB opened at %s\n", deviceFilePath );
			messageInterface->message( 1, "Usb> Make Controller connected.\n" );
	  }
	  return OK;
		
	#endif //Mac-only UsbSerial::open( )
	
  //Windows-only
	#ifdef Q_WS_WIN
		if( deviceOpen )  //if it's already open, do nothing.
		  return ALREADY_OPEN;
		TCHAR* openPorts[32];
		int foundOpen = ScanEnumTree( TEXT("SYSTEM\\CURRENTCONTROLSET\\ENUM\\USB"), openPorts);
		//messageInterface->message( 1, "Found open: %d\n", foundOpen );
		int i;
		for( i = 0; i < foundOpen; i++ )
		{
			if( openPorts[i] != NULL )
			{
				if( openDevice( openPorts[i] ) == 0 )
				{
					messageInterface->message( 1, "Usb> Make Controller connected at %ls\n", openPorts[i] );
					Sleep( 10 );  // wait after opening it before trying to read/write
					deviceOpen = true;
			 		// now set up to get called back when it's unplugged
					bool result;
					result = DoRegisterForNotification( &deviceNotificationHandle );
					
					return OK;
				}
				//else
				  //messageInterface->message( 1, "Found device but could not open: %ls\n", openPorts[i] );
			}
			//else
			  //messageInterface->message( 1, "Did not find any potential ports\n" );
		}
	  return NOT_OPEN;
	#endif //Windows-only UsbSerial::open( )
}