Exemplo n.º 1
0
Arquivo: util.cpp Projeto: IlyaM/mongo
        void run() {
            assert( WrappingInt(0) <= WrappingInt(0) );
            assert( WrappingInt(0) <= WrappingInt(1) );
            assert( !(WrappingInt(1) <= WrappingInt(0)) );
            assert( (WrappingInt(0xf0000000) <= WrappingInt(0)) );
            assert( (WrappingInt(0xf0000000) <= WrappingInt(9000)) );
            assert( !(WrappingInt(300) <= WrappingInt(0xe0000000)) );

            assert( tdiff(3, 4) == 1 );
            assert( tdiff(4, 3) == -1 );
            assert( tdiff(0xffffffff, 0) == 1 );

            assert( isPrime(3) );
            assert( isPrime(2) );
            assert( isPrime(13) );
            assert( isPrime(17) );
            assert( !isPrime(9) );
            assert( !isPrime(6) );
            assert( nextPrime(4) == 5 );
            assert( nextPrime(8) == 11 );

            assert( endsWith("abcde", "de") );
            assert( !endsWith("abcde", "dasdfasdfashkfde") );

            assert( swapEndian(0x01020304) == 0x04030201 );

        }
Exemplo n.º 2
0
// calculates the avg. fps and simulation rate once every NITER iterations
// returns a simrate and fps of -1 for the first NITER iterations
void framerate(long simtime, double *simrate, int *fps)
{
    int j;
    static int i = 0;
    static long frmtime = -1;
    static double simsum = -1, frmsum = -1;
    static long simtimes[NITER], frmtimes[NITER];
    struct timespec now;
    static struct timespec markt;

    now = curtime();
    if (markt.tv_sec == 0 && markt.tv_nsec == 0)
        markt = now;
    else {
        frmtime = convtns(tdiff(now, markt));
        markt = now;

        simtimes[i] = simtime;
        frmtimes[i++] = frmtime;

        if (i == NITER) {
            simsum = frmsum = 0;
            for (j = 0; j < NITER; j++) {
                simsum += simtimes[j];
                frmsum += frmtimes[j];
            }
            i = 0;
        }
    }

    *simrate = (simsum == -1) ? -1 : (double) simsum / frmsum;
    *fps = (frmsum == -1) ? -1 : round((double) 1e9 * NITER / frmsum);

}
Exemplo n.º 3
0
void* thread_save_image(void*) {
    timespec time_save0, time_save1, t_sleep, t_rem;
    t_sleep.tv_sec = 0;
    t_sleep.tv_nsec = 10;

    for (;;) {
        // Wait for image capture
        if (save_frame_buffer.size() > 0) {
            clock_gettime( CLOCK_REALTIME, &time_save0);
            write_jpeg(save_frame_buffer.front());
            // write_png(save_frame_buffer.front());
            if (save_frame_buffer.size() > 4) {
                int bufsize = save_frame_buffer.front().width *
                    save_frame_buffer.front().height *
                    save_frame_buffer.size() / 1024.0; 
                std::cout << "\rBuffer queue: "
                          <<  bufsize << " kB                     " << std::flush;
            }
            std::cout << "d" << std::flush;
            pthread_mutex_lock( &save_buffer_mutex );
            save_frame_buffer.pop();
            pthread_mutex_unlock( &save_buffer_mutex );
            
            clock_gettime(CLOCK_REALTIME, &time_save1);
            double twrite = tdiff(time_save1, time_save0);
        } else {
            nanosleep(&t_sleep, &t_rem);
        }
    }
}
Exemplo n.º 4
0
//prints difference between stored date and present
void printDiff (State *s) {	
	s->next = NULL;
	FILE *in = fopen(makeFilePath(), "rb");
	if (in == NULL) {
		printf("No date stored. Try to store one by calling \"ctd -s [date]\"\n");
		return;
	}
	
	double jstored;
	fread(&jstored, sizeof(double), 1, in); 
	fclose(in);
	
	TDate *present = currentDate(NULL);
	
	double jpresent = toJulian(present);
	
	TDateDiff *diff = tdiff(jstored, jpresent);
	
	printDateDiff(diff);
	printf("\n");
	
	free(present);
	free(diff);

}
Exemplo n.º 5
0
// return capped length of time for the last cycle through main()'s loop
// (this value is used to tell the physics engine how much time to simulate.)
// also slow things down to MAXFPS; leave at least MINIDLEP% cpu idle
// TODO: avoid overflow with multi-second time deltas on 32 bit systems.
long timebal(void)
{
    long calctime, waitt, truewaitt, minidle, totalt;
    static long waitdiff;
    struct timespec now;
    static struct timespec markt, marktbeforeidle;


    now = curtime();
    if (markt.tv_sec == 0 && markt.tv_nsec == 0)
        markt = marktbeforeidle = now;

    calctime = convtns(tdiff(now, markt));
    marktbeforeidle = now;

    waitt = MINFT - calctime - waitdiff;
    // free a minimum of MINIDLEP% cpu
    minidle = calctime * MINIDLEP / 100;
    waitt = (waitt < minidle) ? minidle : waitt;

    waitns(waitt);
    markt = curtime();

    truewaitt = convtns(tdiff(markt, marktbeforeidle));
    if (waitdiff == 0)
        waitdiff = truewaitt - waitt;
    else
        waitdiff = (9 * waitdiff) / 10 + (truewaitt - waitt) / 10;

    totalt = calctime + truewaitt;
    // avoid positive feedback loop causing scheduled simulation time to
    // escalate on slower machines
    totalt = (totalt > MAXFT) ? MAXFT : totalt;

    return totalt;
}
Exemplo n.º 6
0
//prints difference between jvalue2 and jvalue1 every second
void countdown (double jvalue1, double jvalue2) {
	TDateDiff *diff = tdiff(jvalue2, jvalue1);
	while (
		diff->second || 
		diff->minute || 
		diff->hour || 
		diff->day || 
		diff->week) {
		
		printf(CLEARLINE);
		printDateDiff(diff);		
		fflush(stdout);
		decreaseDiff(diff);
		sleep(1);
	}
}
Exemplo n.º 7
0
bool isdupnonce(struct cgpu_info *cgpu, struct work *work, uint32_t nonce)
{
	struct dupdata *dup = (struct dupdata *)(cgpu->dup_data);
	struct timeval now;
	bool unique = true;
	K_ITEM *item;

	if (!dup)
		return false;

	cgtime(&now);
	dup->checked++;
	K_WLOCK(dup->nfree_list);
	item = dup->nonce_list->tail;
	while (unique && item) {
		if (DATAN(item)->work_id == work->id && DATAN(item)->nonce == nonce) {
			unique = false;
			applog(LOG_WARNING, "%s%d: Duplicate nonce %08x",
					    cgpu->drv->name, cgpu->device_id, nonce);
		} else
			item = item->prev;
	}
	if (unique) {
		item = k_unlink_head(dup->nfree_list);
		DATAN(item)->work_id = work->id;
		DATAN(item)->nonce = nonce;
		memcpy(&(DATAN(item)->when), &now, sizeof(now));
		k_add_head(dup->nonce_list, item);
	}
	item = dup->nonce_list->tail;
	while (item && tdiff(&(DATAN(item)->when), &now) > dup->timelimit) {
		item = k_unlink_tail(dup->nonce_list);
		k_add_head(dup->nfree_list, item);
		item = dup->nonce_list->tail;
	}
	K_WUNLOCK(dup->nfree_list);

	if (!unique)
		dup->dup++;

	return !unique;
}
Exemplo n.º 8
0
//prints differnce between the 2 given dates
void print2Diff (State *s) {
	s->next = NULL;
	
	TDate *date1 = parse(s->argv[1]);
	TDate *date2 = parse(s->argv[2]);
	
	if (!date1 || !date2) {
		printf("Could not parse dates. Check formatting\n");
		return;
	}
	
	TDateDiff *diff = tdiff(toJulian(date2), toJulian(date1));
	
	printDateDiff(diff);
	printf("\n");
	
	free(diff);
	free(date1);
	free(date2);
}
Exemplo n.º 9
0
static bool bitforce_detect_one(struct libusb_device *dev, struct usb_find_devices *found)
{
	char buf[BITFORCE_BUFSIZ+1];
	int err, amount;
	char *s;
	struct timeval init_start, init_now;
	int init_sleep, init_count;
	bool ident_first;

	struct cgpu_info *bitforce = usb_alloc_cgpu(&bitforce_drv, 1);

	if (!usb_init(bitforce, dev, found))
		goto shin;

	// Allow 2 complete attempts if the 1st time returns an unrecognised reply
	ident_first = true;
retry:
	init_count = 0;
	init_sleep = REINIT_TIME_FIRST_MS;
	cgtime(&init_start);
reinit:
	bitforce_initialise(bitforce, false);
	if ((err = usb_write(bitforce, BITFORCE_IDENTIFY, BITFORCE_IDENTIFY_LEN, &amount, C_REQUESTIDENTIFY)) < 0 || amount != BITFORCE_IDENTIFY_LEN) {
		applog(LOG_ERR, "%s detect (%s) send identify request failed (%d:%d)",
			bitforce->drv->dname, bitforce->device_path, amount, err);
		goto unshin;
	}

	if ((err = usb_read_nl(bitforce, buf, sizeof(buf)-1, &amount, C_GETIDENTIFY)) < 0 || amount < 1) {
		init_count++;
		cgtime(&init_now);
		if (us_tdiff(&init_now, &init_start) <= REINIT_TIME_MAX) {
			if (init_count == 2) {
				applog(LOG_WARNING, "%s detect (%s) 2nd init failed (%d:%d) - retrying",
					bitforce->drv->dname, bitforce->device_path, amount, err);
			}
			nmsleep(init_sleep);
			if ((init_sleep * 2) <= REINIT_TIME_MAX_MS)
				init_sleep *= 2;
			goto reinit;
		}

		if (init_count > 0)
			applog(LOG_WARNING, "%s detect (%s) init failed %d times %.2fs",
				bitforce->drv->dname, bitforce->device_path, init_count, tdiff(&init_now, &init_start));

		if (err < 0) {
			applog(LOG_ERR, "%s detect (%s) error identify reply (%d:%d)",
				bitforce->drv->dname, bitforce->device_path, amount, err);
		} else {
			applog(LOG_ERR, "%s detect (%s) empty identify reply (%d)",
				bitforce->drv->dname, bitforce->device_path, amount);
		}

		goto unshin;
	}
	buf[amount] = '\0';

	if (unlikely(!strstr(buf, "SHA256"))) {
		if (ident_first) {
			applog(LOG_WARNING, "%s detect (%s) didn't recognise '%s' trying again ...",
				bitforce->drv->dname, bitforce->device_path, buf);
			ident_first = false;
			goto retry;
		}
		applog(LOG_ERR, "%s detect (%s) didn't recognise '%s' on 2nd attempt",
			bitforce->drv->dname, bitforce->device_path, buf);
		goto unshin;
	}

	if (strstr(buf, "SHA256 SC")) {
#ifdef USE_BFLSC
		applog(LOG_DEBUG, "SC device detected, will defer to BFLSC driver");
#else
		applog(LOG_WARNING, "SC device detected but no BFLSC support compiled in!");
#endif
		goto unshin;
	}

	if (likely((!memcmp(buf, ">>>ID: ", 7)) && (s = strstr(buf + 3, ">>>")))) {
		s[0] = '\0';
		bitforce->name = strdup(buf + 7);
	} else {
		bitforce->name = (char *)blank;
	}

	// We have a real BitForce!
	applog(LOG_DEBUG, "%s (%s) identified as: '%s'",
		bitforce->drv->dname, bitforce->device_path, bitforce->name);

	/* Initially enable support for nonce range and disable it later if it
	 * fails */
	if (opt_bfl_noncerange) {
		bitforce->nonce_range = true;
		bitforce->sleep_ms = BITFORCE_SLEEP_MS;
		bitforce->kname = KNAME_RANGE;
	} else {
		bitforce->sleep_ms = BITFORCE_SLEEP_MS * 5;
		bitforce->kname = KNAME_WORK;
	}

	if (!add_cgpu(bitforce))
		goto unshin;

	update_usb_stats(bitforce);

	mutex_init(&bitforce->device_mutex);

	return true;

unshin:

	usb_uninit(bitforce);

shin:

	if (bitforce->name != blank) {
		free(bitforce->name);
		bitforce->name = NULL;
	}

	bitforce = usb_free_cgpu(bitforce);

	return false;
}
Exemplo n.º 10
0
static void insert_row(DB_ENV *db_env, struct table *t, DB_TXN *txn, long a, long b, long c, long d) {
    int r;

    // generate the primary key
    char key_buffer[8];
    a = htonl64(a);
    memcpy(key_buffer, &a, sizeof a);

    // generate the primary value
    char val_buffer[3*8];
    b = htonl64(b);
    memcpy(val_buffer+0, &b, sizeof b);
    c = htonl64(c);
    memcpy(val_buffer+8, &c, sizeof c);
    d = htonl64(d);
    memcpy(val_buffer+16, &d, sizeof d);

    DBT key = { .data = key_buffer, .size = sizeof key_buffer };
    DBT value = { .data = val_buffer, .size = sizeof val_buffer };
#if defined(TOKUDB)
    if (!force_multiple && t->ndbs == 1) {
        r = t->dbs[0]->put(t->dbs[0], txn, &key, &value, t->mult_flags[0]); assert(r == 0);
    } else {
        r = db_env->put_multiple(db_env, t->dbs[0], txn, &key, &value, t->ndbs, &t->dbs[0], t->mult_keys, t->mult_vals, t->mult_flags); assert(r == 0);
    }
#else
    assert(db_env);
    r = t->dbs[0]->put(t->dbs[0], txn, &key, &value, 0); assert(r == 0);
#endif
}

static inline float tdiff (struct timeval *a, struct timeval *b) {
    return (a->tv_sec - b->tv_sec) +1e-6*(a->tv_usec - b->tv_usec);
}

static void insert_all(DB_ENV *db_env, struct table *t, long nrows, long max_rows_per_txn, long key_range, long rows_per_report, bool do_txn) {
    int r;

    struct timeval tstart;
    r = gettimeofday(&tstart, NULL); assert(r == 0);
    struct timeval tlast = tstart;
    DB_TXN *txn = NULL;
    if (do_txn) {
        r = db_env->txn_begin(db_env, NULL, &txn, 0); assert(r == 0);
    }
    long n_rows_per_txn = 0;
    long rowi;
    for (rowi = 0; rowi < nrows; rowi++) {
        long a = rowi;
        long b = random64() % key_range;
        long c = random64() % key_range;
        long d = random64() % key_range;
        insert_row(db_env, t, txn, a, b, c, d);
        n_rows_per_txn++;
        
        // maybe commit
        if (do_txn && n_rows_per_txn == max_rows_per_txn) {
            r = txn->commit(txn, 0); assert(r == 0);
            r = db_env->txn_begin(db_env, NULL, &txn, 0); assert(r == 0);
            n_rows_per_txn = 0;
        }

        // maybe report performance
        if (((rowi + 1) % rows_per_report) == 0) {
            struct timeval tnow;
            r = gettimeofday(&tnow, NULL); assert(r == 0);
            float last_time = tdiff(&tnow, &tlast);
            float total_time = tdiff(&tnow, &tstart);
            printf("%ld %.3f %.0f/s %.0f/s\n", rowi + 1, last_time, rows_per_report/last_time, rowi/total_time); fflush(stdout);
            tlast = tnow;
        }
    }

    if (do_txn) {
        r = txn->commit(txn, 0); assert(r == 0);
    }
    struct timeval tnow;
    r = gettimeofday(&tnow, NULL); assert(r == 0);
    printf("total %ld %.3f %.0f/s\n", nrows, tdiff(&tnow, &tstart), nrows/tdiff(&tnow, &tstart)); fflush(stdout);
}

int main(int argc, char *argv[]) {
#if defined(TOKDUB)
    char *db_env_dir = "insertm.env.tokudb";
#else
    char *db_env_dir = "insertm.env.bdb";
#endif
    int db_env_open_flags = DB_CREATE | DB_PRIVATE | DB_INIT_MPOOL | DB_INIT_TXN | DB_INIT_LOCK | DB_INIT_LOG;
    long rows = 100000000;
    long rows_per_txn = 1000;
    long rows_per_report = 100000;
    long key_range = 100000;
    bool do_txn = true;
    u_int32_t pagesize = 0;
    u_int64_t cachesize = 1000000000;
    int ndbs = 4;
#if defined(TOKUDB)
    u_int32_t checkpoint_period = 60;
#endif

    int i;
    for (i = 1; i < argc; i++) {
        char *arg = argv[i];
        if (strcmp(arg, "--verbose") == 0) {
            verbose++;
            continue;
        }
        if (strcmp(arg, "--ndbs") == 0 && i+1 < argc) {
            ndbs = atoi(argv[++i]);
            continue;
        }
        if (strcmp(arg, "--rows") == 0 && i+1 < argc) {
            rows = atol(argv[++i]);
            continue;
        }
        if (strcmp(arg, "--rows_per_txn") == 0 && i+1 < argc) {
            rows_per_txn = atol(argv[++i]);
            continue;
        }
        if (strcmp(arg, "--rows_per_report") == 0 && i+1 < argc) {
            rows_per_report = atol(argv[++i]);
            continue;
        }
        if (strcmp(arg, "--key_range") == 0 && i+1 < argc) {
            key_range = atol(argv[++i]);
            continue;
        }
        if (strcmp(arg, "--txn") == 0 && i+1 < argc) {
            do_txn = atoi(argv[++i]);
            continue;
        }
        if (strcmp(arg, "--pagesize") == 0 && i+1 < argc) {
            pagesize = atoi(argv[++i]);
            continue;
        }
        if (strcmp(arg, "--cachesize") == 0 && i+1 < argc) {
            cachesize = atol(argv[++i]);
            continue;
        }
        if (strcmp(arg, "--force_multiple") == 0 && i+1 < argc) {
            force_multiple = atoi(argv[++i]);
            continue;
        }
#if defined(TOKUDB)
        if (strcmp(arg, "--checkpoint_period") == 0 && i+1 < argc) {
            checkpoint_period = atoi(argv[++i]);
            continue;
        }
#endif

        assert(0);
    }

    int r;
    char rm_cmd[strlen(db_env_dir) + strlen("rm -rf ") + 1];
    snprintf(rm_cmd, sizeof(rm_cmd), "rm -rf %s", db_env_dir);
    r = system(rm_cmd); assert(r == 0);

    r = mkdir(db_env_dir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); assert(r == 0);

    // create and open the env
    DB_ENV *db_env = NULL;
    r = db_env_create(&db_env, 0); assert(r == 0);
    if (!do_txn)
        db_env_open_flags &= ~(DB_INIT_TXN | DB_INIT_LOG);
    if (cachesize) {
        const u_int64_t gig = 1 << 30;
        r = db_env->set_cachesize(db_env, cachesize / gig, cachesize % gig, 1); assert(r == 0);
    }
#if defined(TOKUDB)
    r = db_env->set_generate_row_callback_for_put(db_env, my_generate_row_for_put); assert(r == 0);
#endif
    r = db_env->open(db_env, db_env_dir, db_env_open_flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); assert(r == 0);
#if defined(TOKUDB)
    if (checkpoint_period) {
        r = db_env->checkpointing_set_period(db_env, checkpoint_period); assert(r == 0);
        u_int32_t period;
        r = db_env->checkpointing_get_period(db_env, &period); assert(r == 0 && period == checkpoint_period);
    }
#endif


    // create the db
    DB *dbs[ndbs];
    for (i = 0; i < ndbs; i++) {
        DB *db = NULL;
        r = db_create(&db, db_env, 0); assert(r == 0);
        DB_TXN *create_txn = NULL;
        if (do_txn) {
            r = db_env->txn_begin(db_env, NULL, &create_txn, 0); assert(r == 0);
        }
        if (pagesize) {
            r = db->set_pagesize(db, pagesize); assert(r == 0);
        }
        char db_filename[32]; sprintf(db_filename, "test%d", i);
        r = db->open(db, create_txn, db_filename, NULL, DB_BTREE, DB_CREATE, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); assert(r == 0);

#if defined(TOKUDB)
        DESCRIPTOR_S new_descriptor;
        int index_num = htonl(i);
        new_descriptor.dbt.data = &index_num;
        new_descriptor.dbt.size = sizeof i;
        r = db->change_descriptor(db, create_txn, &new_descriptor.dbt, 0); assert(r == 0);
#else
        db->app_private = (void *) (intptr_t) i;
        if (i > 0) {
            r = dbs[0]->associate(dbs[0], create_txn, db, my_secondary_key, 0); assert(r == 0);
        }
#endif
        if (do_txn) {
            r = create_txn->commit(create_txn, 0); assert(r == 0);
        }
        dbs[i] = db;
    }

    // insert all rows
    struct table table;
    table_init(&table, ndbs, dbs, 4 * 8, 4 * 8);

    insert_all(db_env, &table, rows, rows_per_txn, key_range, rows_per_report, do_txn);

    table_destroy(&table);

    // shutdown
    for (i = 0; i < ndbs; i++) {
        DB *db = dbs[i];
        r = db->close(db, 0); assert(r == 0); db = NULL;
    }
    r = db_env->close(db_env, 0); assert(r == 0); db_env = NULL;

    return 0;
}
Exemplo n.º 11
0
int main (int argc, char **argv)
{

    
    char* ntry = (char*)"";
    if (argc > 1) {
        ntry = argv[1];
    }

    double fps = FPS;
    double target_dur = 1.0/fps;
    double tol = 1.0e-3;
    double total_dur = 0.0;

    dc1394_t * d = dc1394_new(); 
    if (!d) {
        return 1;
    }
    dc1394camera_list_t * list;
    dc1394error_t err = dc1394_camera_enumerate (d, &list);
    DC1394_ERR_RTN(err,"Failed to enumerate cameras");
    if (list->num == 0) {                                                  /* Verify that we have at least one camera */
        dc1394_log_error("No cameras found");
        return 1;
    }

    gCamera.init(d, list->ids[0].guid);
    if (!gCamera.cam()) {
        dc1394_log_error("Failed to initialize camera with guid %ld", list->ids[0].guid);
        dc1394_camera_free_list (list);

        return 1;
    }
    dc1394_camera_free_list (list);

    /*-----------------------------------------------------------------------
     *  have the camera start sending us data
     *-----------------------------------------------------------------------*/
    err = gCamera.start_transmission();
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Could not start camera iso transmission");

    
    /*-----------------------------------------------------------------------
     *  capture one frame
     *-----------------------------------------------------------------------*/
    uint32_t width = 0;
    uint32_t height = 0;
    gCamera.get_image_size(&width, &height);
    cv::Mat mapping = cv::getRotationMatrix2D(cv::Point2f(width/2.0, height/2.0), 180.0, 1.0);

#ifdef USE_SDL
    static char *var = (char*)"SDL_VIDEO_WINDOW_POS=\"1280,480\"";
    int ret = putenv(var);
    
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        std::cerr << "DC1394: Unable to initialize SDL: " <<  SDL_GetError() << std::endl;
        return 1;
    }
    atexit(SDL_Quit);
    SDL_Surface *screen;
    screen = SDL_SetVideoMode(width, height, 24, SDL_HWSURFACE);
    if (screen == NULL) {
        std::cerr << "DC1394: Unable to set SDL video mode:" << SDL_GetError() << std::endl;
    }
    SDL_Event event;
#endif

#ifndef LICKOMETER    
    pthread_t save_thread, acq_thread;
    pthread_create( &save_thread, NULL, &thread_save_image, NULL);
#endif

    pthread_t save_thread, acq_thread;
    pthread_create( &acq_thread, NULL, &thread_acq_image, NULL);

    timespec t_sleep, t_rem;
    t_sleep.tv_sec = 0;
    t_sleep.tv_nsec = 1000;
    
#ifndef STANDALONE
    int s;
    if ((s = socket(SOCKTYPE, SOCK_STREAM, 0)) < 0) {
        perror("DC1394: client: socket");
        cleanup_and_exit(gCamera);
        return 1;
    }

    /*
     * Create the address we will be connecting to.
     */
#ifndef INET
    sockaddr_un sa;
    sa.sun_family = AF_UNIX;

    std::ostringstream tmpfn;
    tmpfn << "fwsocket" << ntry;
    std::cout << "DC1394: socket name " << tmpfn.str() << std::endl;
    
    int nameLen = strlen(tmpfn.str().c_str());
    if (nameLen >= (int) sizeof(sa.sun_path) -1) { /* too long? */
        cleanup_and_exit(gCamera);
        return 1;
    }
    
    sa.sun_path[0] = '\0';  /* abstract namespace */
    strcpy(sa.sun_path+1, tmpfn.str().c_str());
    int len = 1 + nameLen + offsetof(struct sockaddr_un, sun_path);
#else
    sockaddr_in sa;
    bzero((char *) &sa, sizeof(sa));
    sa.sin_family = AF_INET;
    hostent *server = gethostbyname("128.40.156.129");
    bcopy((char *)server->h_addr, 
          (char *)&sa.sin_addr.s_addr,
          server->h_length);
    sa.sin_port = htons(35000);
    int len = sizeof(sa);
#endif    
    /*
     * Try to connect to the address.  For this to
     * succeed, the server must already have bound
     * this address, and must have issued a listen()
     * request.
     *
     * The third argument indicates the "length" of
     * the structure, not just the length of the
     * socket name.
     */
    std::cout << "DC1394: Waiting for connection... " << std::flush;
    while (true) {
        // wait for connection:
        if (connect(s, (sockaddr*)&sa, len) < 0) {
            nanosleep(&t_sleep, &t_rem);
        } else {
            break;
        }
    }
    std::cout << "done" << std::endl;
    bool connected = false;
    std::vector<char> data(BUFSIZE);
    int nrec = recv(s, &data[0], data.size(), 0);
    std::string datastr(data.begin(), data.end());
    if (nrec<=0) {
        std::cerr << "DC1394: Didn't receive start message; exiting now" << std::endl;
        cleanup_and_exit(gCamera);
	close(s);
        return 1;
    }
    connected = true;
    
    std::string ready = "ready";
    while (send(s, ready.c_str(), ready.size(), 0) < 0) {
        perror("DC1394: client: send");
    }

    int flags = 0;
    if (-1 == (flags = fcntl(s, F_GETFL, 0)))
        flags = 0;

    if (fcntl(s, F_SETFL, flags | O_NONBLOCK)==-1) {
        perror("DC1394: client: unblock");
    }
#endif
    
    /* pthread_mutex_lock( &camera_mutex );
       gCamera.wait_for_trigger();
       pthread_mutex_unlock( &camera_mutex );

       Wait for acq_frame_buffer to fill instead
    */
    

    int ncount = 0;
    cv::Mat im(cv::Size(width, height), CV_8UC1);
    cv::Mat thresh = cv::Mat::ones(cv::Size(width, height), CV_8UC1);
    cv::Mat prevs(cv::Size(width, height), CV_8UC1);
    cv::Mat gray(cv::Size(width, height), CV_8UC1);
    
    // wait for image:
    int nframes = get_image(im, mapping, false, -1, "", ncount);
    std::cout << "DC1394: Waiting for first image to arrive... " << std::flush;
    int nwait = 0;
    while (!nframes) {
        nanosleep(&t_sleep, &t_rem);
        std::cout << "." << std::flush;
        nframes = get_image(im, mapping, false, -1, "", ncount);
        nwait++;
#ifdef STANDALONE
	if (nwait > 1000) {
#else
	if (nwait > 100000) {
#endif
            std::cout << "Time out, stopping now\n";
            cleanup_and_exit(gCamera);
	}
    }
    timespec time0;
    clock_gettime(CLOCK_REALTIME, &time0);
    std::cout << "DC1394: image arrived: "
              << IplImage(im).depth << " bits, "
              << IplImage(im).nChannels << " channels, "
              << IplImage(im).widthStep << " step width"  << std::endl;

#ifdef USE_SDL
    SDL_Surface *surface =
        SDL_CreateRGBSurfaceFrom((void*)im.data,
                                 im.cols,
                                 im.rows,
                                 IplImage(im).depth*IplImage(im).nChannels,
                                 IplImage(im).widthStep,
                                 0xffffff, 0xffffff, 0xffffff, 0);
    screen = SDL_GetVideoSurface();
    if(SDL_BlitSurface(surface, NULL, screen, NULL) == 0)
        SDL_UpdateRect(screen, 0, 0, 0, 0);
#else
    cv::namedWindow("DC1394", CV_WINDOW_AUTOSIZE);
    cvMoveWindow("DC1394", 1280, 480);

    cv::imshow("DC1394", im);
#endif

    timespec time1 = time0;
    timespec time2 = time0;
    timespec time3 = time0;
    timespec time4 = time0;
    timespec t_disconnect = time0;
    timespec t_notrigger = time0;

#ifdef STANDALONE
    int s = -1;
#endif

    std::string fn = "";
#ifdef LICKOMETER
    std::string fn_lick = "";
    FILE* fp_lick = NULL;
#endif
    int key = 0;
    int nloop = 0;
    while (true) {
        clock_gettime( CLOCK_REALTIME, &time1);
#ifndef STANDALONE
        std::vector<char> data(BUFSIZE);
        int nrec = recv(s, &data[0], data.size(), 0);
        std::string datastr(data.begin(), data.end());
#endif

        nframes += get_image(im, mapping, false, s, fn, ncount);

#ifndef STANDALONE

        // no update from blender in a long time, terminate process
        if (datastr.find("1")==std::string::npos) {
            if (connected) {
                t_disconnect = time1;
                connected = false;
            } else {
                if (tdiff(time1, t_disconnect) > TIMEOUT) {
                    std::cout << "DC1394: Received termination signal" << std::endl;
                    close(s);
                    pthread_cancel(acq_thread);
                    pthread_cancel(save_thread);
                    return 0;
                }
            }
        } else {
            connected = true;
        }

	/* Explicit termination */
        if (datastr.find("quit")!=std::string::npos) {
            std::cout << "DC1394: Game over signal." << std::endl;
            std::string sclose = "close";
            while (send(s, sclose.c_str(), sclose.size(), 0) < 0) {
                perror("DC1394: client: send");
            }
            close(s);
            pthread_cancel(acq_thread);
            pthread_cancel(save_thread);
            return 0;
        }

        // Stop recording
        if (datastr.find("stop") != std::string::npos && fn != "") {
            fn = "";
#ifdef LICKOMETER
	    fn_lick = "";
	    if (fp_lick) {
                fclose(fp_lick);
		fp_lick = NULL;
            }
#endif
            std::cout << "DC1394: Stopping video" << std::endl;
            connected = true;
            ncount = 0;
        }

        // Start recording
        if (datastr.find("avi") != std::string::npos && datastr.find("stop") == std::string::npos && fn == "") {
            std::size_t startpos = datastr.find("begin")+5; 
            std::size_t endpos = datastr.find("end") - datastr.find("begin") - 5; 
            fn = datastr.substr(startpos, endpos);
            fn = std::string(trunk) + "data/" + fn;
#ifdef LICKOMETER
	    fn_lick = fn + "_lick";
	    fp_lick = fopen(fn_lick.c_str(), "wb");
            std::cout << "DC1394: Recording lick detection, writing to " << fn_lick << std::endl;
#else
            boost::filesystem::path path(fn);
            boost::filesystem::path writepath(path);

            // Test whether dir exists:
            if (!boost::filesystem::exists(writepath)) {
                std::cout << "DC1394: Creating directory " << writepath << std::endl;
                boost::filesystem::create_directories(writepath);
            }
            fn += "/";

            /* check save frame buffer */
            std::size_t nfb = save_frame_buffer.size();
            if (nfb)
                std::cerr << "DC1394: Frame buffer isn't empty!" << std::endl;

            std::cout << "DC1394: Starting video, writing to " << fn << std::endl;
            connected = true;
            ncount = 0;
#endif
        }
#endif // #nstandalone

#ifdef USE_SDL
        if (SDL_PollEvent(&event)) {
#ifdef STANDALONE
            /* Any of these event types will end the program */
            if (event.type == SDL_QUIT
                || event.type == SDL_KEYDOWN
                || event.type == SDL_KEYUP) {
                std::cout << std::endl;
                std::cout << std::endl << "DC1394: Total number of frames was " << nframes << std::endl;
                std::cout << std::endl << "DC1394: Frame buffer: " << acq_frame_buffer.size() << " frames left" << std::endl;
                close(s);
                pthread_cancel(acq_thread);
                pthread_cancel(save_thread);
                return 0;
            }
#endif // STANDALONE
        }
        surface->pixels = (void*)im.data;
        // SDL_CreateRGBSurfaceFrom((void*)IplImage(im).imageData,
        //                          IplImage(im).width,
        //                          IplImage(im).height,
        //                          IplImage(im).depth*IplImage(im).nChannels,
        //                          IplImage(im).widthStep,
        //                          1, 1, 1, 0);
        screen = SDL_GetVideoSurface();
        if(SDL_BlitSurface(surface, NULL, screen, NULL) == 0)
            SDL_UpdateRect(screen, 0, 0, 0, 0);
#else // not SDL
        key = cv::waitKey(2);
        cv::imshow("DC1394", im);
        if (key == 1114155 || key == 65579 || key==43 /*+*/) {
            uint32_t gain = 0;
            err = dc1394_feature_get_value(gCamera.cam(), DC1394_FEATURE_GAIN, &gain);
            DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't get gain");
            if (gain < gCamera.get_maxgain()-10) {
                gain += 10;
                pthread_mutex_lock( &camera_mutex );
                err = dc1394_feature_set_value(gCamera.cam(), DC1394_FEATURE_GAIN, gain);
                pthread_mutex_unlock( &camera_mutex );
                std::cout << "DC1394: New gain value: " << gain << std::endl;
                DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't set gain");
            }
        }
        if (key == 1114207 || key == 45 /*-*/) {
            uint32_t gain = 0;
            err = dc1394_feature_get_value(gCamera.cam(), DC1394_FEATURE_GAIN, &gain);
            DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't get gain");
            if (gain > gCamera.get_mingain()+10) {
                gain -= 10;
                pthread_mutex_lock( &camera_mutex );
                err = dc1394_feature_set_value(gCamera.cam(), DC1394_FEATURE_GAIN, gain);
                pthread_mutex_unlock( &camera_mutex );
                DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't set gain");
            }
        }
#endif // not SDL

#ifdef LICKOMETER        
	/* IS THIS ALL YOU NEED THEN?
	   Lick detection */
	/* Not required because the captured image is already gray
	   cv::Mat gray = bgr2gray(im); */
	gray = thresholding(im, LICK_FRAME_THRESHOLD);

        if (nloop != 0) {
	    cv::absdiff(prevs, gray, thresh);
	    double pixel_sum_thresh = cv::sum(thresh)[0];
	    double pixel_sum_gray = cv::sum(gray)[0];
	    if (pixel_sum_thresh > LICK_SUM_THRESHOLD) {
	      std::cout << "DC1394: Lick" << std::endl;
	    }
	    if (fp_lick != NULL) {
                fwrite(&pixel_sum_thresh, sizeof(pixel_sum_thresh), 1, fp_lick);
	        fwrite(&pixel_sum_gray, sizeof(pixel_sum_gray), 1, fp_lick);
	    }
	}

	prevs = gray.clone();
	nloop++;
#endif
#ifdef STANDALONE
        if (key == 1048689 || key == 113 /*q*/) {
            std::cout << "DC1394: Mean frame rate was " << nframes/total_dur << " fps" << std::endl;
            pthread_cancel(acq_thread);
            pthread_cancel(save_thread);
            return 0;
        }
        if (key == 1048691 /*s*/) {
            fn = "";
            std::cout << "DC1394: Stopping video" << std::endl;
            ncount = 0;
        }
        if (key == 1048690 /*r*/) {
            fn = trunk + std::string("tmp/");
            std::cout << "DC1394: Starting video, writing to " << fn << std::endl;
            ncount = 0;
        }
#endif // #standalone
        clock_gettime( CLOCK_REALTIME, &time2);
        double loop_dur = tdiff(time2, time3);
        clock_gettime( CLOCK_REALTIME, &time3);
        double meanfps = 0;

        total_dur = tdiff(time3, time0);
        if (total_dur > 0)
            meanfps = nframes / total_dur;
        double currentfps = ret / loop_dur;
        std::cout << "DC1394: Current fps: " << std::setprecision(7) << currentfps
                  << " Average fps: " << std::setprecision(7) << meanfps << "\r" << std::flush;
#ifdef STANDALONE
        // std::cout << capture_dur << "\t" << target_dur << "\t" << rem << "\t" << loop_dur << std::endl;
#endif
    }

    if (d) {
        dc1394_free(d);
    }

#ifndef STANDALONE
    close(s);
#endif
    return 0;
}
Exemplo n.º 12
0
static int64_t avalon2_scanhash(struct thr_info *thr)
{
	struct avalon2_pkg send_pkg;
	struct timeval current_stratum;

	struct pool *pool;
	struct cgpu_info *avalon2 = thr->cgpu;
	struct avalon2_info *info = avalon2->device_data;

	int64_t h;
	uint32_t tmp, range, start;
	int i;

	if (thr->work_restart || thr->work_update || !info->first) {
		applog(LOG_DEBUG, "Avalon2: New stratum: restart: %d, update: %d, first: %d",
		       thr->work_restart, thr->work_update, info->first);
		thr->work_update = false;
		thr->work_restart = false;
		get_work(thr, thr->id); /* Make sure pool is ready */

		pool = current_pool();
		if (!pool->has_stratum)
			quit(1, "Avalon2: Miner Manager have to use stratum pool");
		if (pool->coinbase_len > AVA2_P_COINBASE_SIZE) {
			applog(LOG_ERR, "Avalon2: Miner Manager pool coinbase length have to less then %d", AVA2_P_COINBASE_SIZE);
			return 0;
		}
		if (pool->merkles > AVA2_P_MERKLES_COUNT) {
			applog(LOG_ERR, "Avalon2: Miner Manager merkles have to less then %d", AVA2_P_MERKLES_COUNT);
			return 0;
		}

		cgtime(&info->last_stratum);
		cg_rlock(&pool->data_lock);
		info->pool_no = pool->pool_no;
		copy_pool_stratum(pool);
		avalon2_stratum_pkgs(info->fd, pool, thr);
		cg_runlock(&pool->data_lock);

		/* Configuer the parameter from outside */
		adjust_fan(info);
		info->set_voltage = opt_avalon2_voltage_min;
		info->set_frequency = opt_avalon2_freq_min;

		/* Set the Fan, Voltage and Frequency */
		memset(send_pkg.data, 0, AVA2_P_DATA_LEN);

		tmp = be32toh(info->fan_pwm);
		memcpy(send_pkg.data, &tmp, 4);

		applog(LOG_ERR, "Avalon2: Temp max: %d, Cut off temp: %d",
		       get_current_temp_max(info), opt_avalon2_overheat);
		if (get_current_temp_max(info) >= opt_avalon2_overheat)
			tmp = encode_voltage(0);
		else
			tmp = encode_voltage(info->set_voltage);
		tmp = be32toh(tmp);
		memcpy(send_pkg.data + 4, &tmp, 4);

		tmp = be32toh(info->set_frequency);
		memcpy(send_pkg.data + 8, &tmp, 4);

		/* Configure the nonce2 offset and range */
		range = 0xffffffff / total_devices;
		start = range * avalon2->device_id;

		tmp = be32toh(start);
		memcpy(send_pkg.data + 12, &tmp, 4);

		tmp = be32toh(range);
		memcpy(send_pkg.data + 16, &tmp, 4);

		/* Package the data */
		avalon2_init_pkg(&send_pkg, AVA2_P_SET, 1, 1);
		while (avalon2_send_pkg(info->fd, &send_pkg, thr) != AVA2_SEND_OK)
			;

		if (unlikely(info->first < 2))
			info->first++;
	}

	/* Stop polling the device if there is no stratum in 3 minutes, network is down */
	cgtime(&current_stratum);
	if (tdiff(&current_stratum, &(info->last_stratum)) > (double)(3.0 * 60.0))
		return 0;

	polling(thr);

	h = 0;
	for (i = 0; i < AVA2_DEFAULT_MODULARS; i++) {
		h += info->enable[i] ? (info->local_work[i] - info->hw_work[i]) : 0;
	}
	return h * 0xffffffff;
}
Exemplo n.º 13
0
int write_png(const saveframe& sframe) {
    FILE *fp;
    png_structp png_ptr;
    png_infop info_ptr;
    png_colorp palette;
    png_color_8 sig_bit;
    int pass, number_passes;

    /* open the file */
    fp = fopen(sframe.fname.c_str(), "wb");
    if (fp == NULL) {
        std::cerr << "Couldn't create file" << std::endl;
        return 0;
    }
    /* Create and initialize the png_struct with the desired error
     * handler functions.
     * If you want to use the default stderr and longjump method,
     * you can supply NULL for the last three parameters (which we do).
     * We also check that the library version is compatible with
     * the one used at compile time, in case we are using dynamically
     * linked libraries.  REQUIRED.
     */
    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
                                      NULL, NULL, NULL);

    if (png_ptr == NULL) {
        fclose(fp);
        std::cerr << "Couldn't create write struct" << std::endl;
        return 0;
    }

    /* Allocate/initialize the image information data.  REQUIRED */
    info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL)
    {
        fclose(fp);
        png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
        std::cerr << "Couldn't create info struct" << std::endl;
        return 0;
    }

    /* Set error handling.  REQUIRED if you aren't supplying your own
     * error handling functions in the png_create_write_struct() call.
     */
    if (setjmp(png_ptr->jmpbuf))
    {
        /* If we get here, we had a problem reading the file */
        fclose(fp);
        png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
        std::cerr << "Couldn't create info struct" << std::endl;
        return 0;
    }

    png_set_compression_level(png_ptr, Z_BEST_SPEED);
    png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_UP);

    /* One of the following I/O initialization functions is REQUIRED */
    /* set up the output control if you are using standard C streams */
    png_init_io(png_ptr, fp);
    if (setjmp(png_ptr->jmpbuf))
    {
        /* If we get here, we had a problem reading the file */
        fclose(fp);
        png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
        std::cerr << "Couldn't init io" << std::endl;
        return 0;
    }

    /* Set the image information here.  Width and height are up to 2^31,
     * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also
     * depend on the color_type selected.
     * color_type is one of PNG_COLOR_TYPE_GRAY,
     * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE,
     * PNG_COLOR_TYPE_RGB, or PNG_COLOR_TYPE_RGB_ALPHA.
     * Interlacing is either PNG_INTERLACE_NONE or PNG_INTERLACE_ADAM7,
     * and the compression_type and filter_type MUST currently be
     * PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
     */
    png_set_IHDR(png_ptr, info_ptr, sframe.width, sframe.height,
                 8,
                 PNG_COLOR_TYPE_GRAY,
                 PNG_INTERLACE_NONE,
                 PNG_COMPRESSION_TYPE_BASE,
                 PNG_FILTER_TYPE_BASE);
    if (setjmp(png_ptr->jmpbuf))
    {
        /* If we get here, we had a problem reading the file */
        fclose(fp);
        png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
        std::cerr << "Couldn't set header" << std::endl;
        return 0;
    }

    /* Write the file header information.  REQUIRED */
    png_write_info(png_ptr, info_ptr);
    if (setjmp(png_ptr->jmpbuf))
    {
        /* If we get here, we had a problem reading the file */
        fclose(fp);
        png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
        std::cerr << "Couldn't write info" << std::endl;
        return 0;
    }

    /* The easiest way to write the image is to write it in one go. */
    if (pngdata.size()!=sframe.height)
        pngdata.resize(sframe.height);
    for (int nr=0; nr<sframe.height; ++nr) {
        pngdata[nr] = (png_bytep) &(sframe.data[nr*sframe.width]);
    }
    std::cout << "Writing image... " << std::flush;

    timespec time0, time1;
    clock_gettime( CLOCK_REALTIME, &time0);
    png_write_image(png_ptr, &(pngdata[0]));
    if (setjmp(png_ptr->jmpbuf))
    {
        /* If we get here, we had a problem reading the file */
        fclose(fp);
        png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
        std::cerr << "Couldn't write image" << std::endl;
        return 0;
    }

    clock_gettime( CLOCK_REALTIME, &time1);
    double frame_dur = tdiff(time1, time0);
    std::cout << frame_dur*1e3 << std::endl;
    
    /* It is REQUIRED to call this to finish writing the rest of the file */
    png_write_end(png_ptr, info_ptr);

    /* clean up after the write, and free any memory allocated */
    png_destroy_write_struct(&png_ptr, (png_infopp)NULL);

    /* close the file */
    fclose(fp);

    /* that's it */
    return 1;
}
Exemplo n.º 14
0
static bool bitforce_detect_one(struct libusb_device *dev, struct usb_find_devices *found)
{
    char buf[BITFORCE_BUFSIZ+1];
    char devpath[20];
    int err, amount;
    char *s;
    struct timeval init_start, init_now;
    int init_sleep, init_count;
    bool ident_first;

    struct cgpu_info *bitforce = NULL;
    bitforce = calloc(1, sizeof(*bitforce));
    bitforce->drv = &bitforce_drv;
    bitforce->deven = DEV_ENABLED;
    bitforce->threads = 1;

    if (!usb_init(bitforce, dev, found)) {
        applog(LOG_ERR, "%s detect (%d:%d) failed to initialise (incorrect device?)",
               bitforce->drv->dname,
               (int)(bitforce->usbinfo.bus_number),
               (int)(bitforce->usbinfo.device_address));
        goto shin;
    }

    sprintf(devpath, "%d:%d",
            (int)(bitforce->usbinfo.bus_number),
            (int)(bitforce->usbinfo.device_address));


    // Allow 2 complete attempts if the 1st time returns an unrecognised reply
    ident_first = true;
retry:
    init_count = 0;
    init_sleep = REINIT_TIME_FIRST_MS;
    gettimeofday(&init_start, NULL);
reinit:
    bitforce_initialise(bitforce, false);
    if ((err = usb_write(bitforce, BITFORCE_IDENTIFY, BITFORCE_IDENTIFY_LEN, &amount, C_REQUESTIDENTIFY)) < 0 || amount != BITFORCE_IDENTIFY_LEN) {
        applog(LOG_ERR, "%s detect (%s) send identify request failed (%d:%d)",
               bitforce->drv->dname, devpath, amount, err);
        goto unshin;
    }

    if ((err = usb_ftdi_read_nl(bitforce, buf, sizeof(buf)-1, &amount, C_GETIDENTIFY)) < 0 || amount < 1) {
        init_count++;
        gettimeofday(&init_now, NULL);
        if (us_tdiff(&init_now, &init_start) <= REINIT_TIME_MAX) {
            if (init_count == 2) {
                applog(LOG_WARNING, "%s detect (%s) 2nd init failed (%d:%d) - retrying",
                       bitforce->drv->dname, devpath, amount, err);
            }
            nmsleep(init_sleep);
            if ((init_sleep * 2) <= REINIT_TIME_MAX_MS)
                init_sleep *= 2;
            goto reinit;
        }

        if (init_count > 0)
            applog(LOG_WARNING, "%s detect (%s) init failed %d times %.2fs",
                   bitforce->drv->dname, devpath, init_count, tdiff(&init_now, &init_start));

        if (err < 0) {
            applog(LOG_ERR, "%s detect (%s) error identify reply (%d:%d)",
                   bitforce->drv->dname, devpath, amount, err);
        } else {
            applog(LOG_ERR, "%s detect (%s) empty identify reply (%d)",
                   bitforce->drv->dname, devpath, amount);
        }

        goto unshin;
    }
    buf[amount] = '\0';

    if (unlikely(!strstr(buf, "SHA256"))) {
        if (ident_first) {
            applog(LOG_WARNING, "%s detect (%s) didn't recognise '%s' trying again ...",
                   bitforce->drv->dname, devpath, buf);
            ident_first = false;
            goto retry;
        }
        applog(LOG_ERR, "%s detect (%s) didn't recognise '%s' on 2nd attempt",
               bitforce->drv->dname, devpath, buf);
        goto unshin;
    }

    if (likely((!memcmp(buf, ">>>ID: ", 7)) && (s = strstr(buf + 3, ">>>")))) {
        s[0] = '\0';
        bitforce->name = strdup(buf + 7);
    } else {
        bitforce->name = (char *)blank;
    }

    // We have a real BitForce!
    applog(LOG_DEBUG, "%s (%s) identified as: '%s'",
           bitforce->drv->dname, devpath, bitforce->name);

    /* Initially enable support for nonce range and disable it later if it
     * fails */
    if (opt_bfl_noncerange) {
        bitforce->nonce_range = true;
        bitforce->sleep_ms = BITFORCE_SLEEP_MS;
        bitforce->kname = KNAME_RANGE;
    } else {
        bitforce->sleep_ms = BITFORCE_SLEEP_MS * 5;
        bitforce->kname = KNAME_WORK;
    }

    bitforce->device_path = strdup(devpath);

    if (!add_cgpu(bitforce))
        goto unshin;

    update_usb_stats(bitforce);

    mutex_init(&bitforce->device_mutex);

    return true;

unshin:

    usb_uninit(bitforce);

shin:

    free(bitforce->device_path);

    if (bitforce->name != blank)
        free(bitforce->name);

    if (bitforce->drv->copy)
        free(bitforce->drv);

    free(bitforce);

    return false;
}
Exemplo n.º 15
0
// Issue request and await reply (blocking).
int playerc_client_request(playerc_client_t *client,
                           playerc_device_t *deviceinfo,
                           uint8_t subtype,
                           const void *req_data, void **rep_data)
{
  int peek;
  struct timeval start;
  struct timeval curr;
  player_msghdr_t req_header, rep_header;
  memset(&req_header, 0, sizeof(req_header));


  if(deviceinfo == NULL)
  {
    req_header.addr.interf = PLAYER_PLAYER_CODE;
    req_header.type = PLAYER_MSGTYPE_REQ;
  }
  else
  {
    req_header.addr = deviceinfo->addr;
    req_header.type = PLAYER_MSGTYPE_REQ;
  }
  req_header.subtype = subtype;


  if (playerc_client_writepacket(client, &req_header, req_data) < 0)
    return -1;

  // Read packets until we get a reply.  Data packets get queued up
  // for later processing.
  gettimeofday(&start,NULL);
  for(curr = start; tdiff(start,curr)< client->request_timeout; gettimeofday(&curr,NULL))
  {
    // Peek at the socket
    if((peek = playerc_client_internal_peek(client,10)) < 0)
      return -1;
    else if(peek == 0)
      continue;

    // There's data on the socket, so read a packet (blocking).
    if(playerc_client_readpacket(client, &rep_header, client->data) < 0)
      return -1;

    if (rep_header.type == PLAYER_MSGTYPE_DATA || rep_header.type == PLAYER_MSGTYPE_SYNCH)
    {
      // Queue up any incoming data and sync packets for later processing
      playerc_client_push(client, &rep_header, client->data);
    }
    else if(rep_header.type == PLAYER_MSGTYPE_RESP_ACK)
    {
      // Using TCP, we only need to check the interface and index
      if (rep_header.addr.interf != req_header.addr.interf ||
          rep_header.addr.index != req_header.addr.index ||
          rep_header.subtype != req_header.subtype)
      {
        PLAYERC_ERR6("got the wrong kind of reply (%d %d %d != %d %d %d).",rep_header.addr.interf,
                rep_header.addr.index, rep_header.subtype, req_header.addr.interf, req_header.addr.index,
                req_header.subtype);
        return -1;
      }
      if (rep_header.size > 0)
      {
        if (rep_data)
        {
          *rep_data = playerxdr_clone_message(client->data,rep_header.addr.interf, rep_header.type, rep_header.subtype);
        }
        playerxdr_cleanup_message(client->data,rep_header.addr.interf, rep_header.type, rep_header.subtype);
      }
      return(0);
    }
    else if (rep_header.type == PLAYER_MSGTYPE_RESP_NACK)
    {
      // Using TCP, we only need to check the interface and index
      if (rep_header.addr.interf != req_header.addr.interf ||
          rep_header.addr.index != req_header.addr.index ||
          rep_header.subtype != req_header.subtype)
      {
        PLAYERC_ERR("got the wrong kind of reply (not good).");
        return -1;
      }
      PLAYERC_ERR("got NACK from request");
      return -2;
    }
  }

  PLAYERC_ERR4("timed out waiting for server reply to request %s:%d:%s:%d", interf_to_str(req_header.addr.interf), req_header.addr.index, msgtype_to_str(req_header.type), req_header.subtype);
  return -1;
}
Exemplo n.º 16
0
Arquivo: timer.c Projeto: fortsage/nio
long int sys_timer_count() {
	return tdiff(start, end);
}
Exemplo n.º 17
0
int main(int argc, char *argv[]) {
  int optchar;
#ifndef PROFILE_BUILD
  bool graphicDemoFlag = false;
#endif
  bool imageOnlyFlag = false;
  unsigned int numFrames = 1;
  extern int optind;

  // Process command line options.
  while ((optchar = getopt(argc, argv, "gi")) != -1) {
    switch (optchar) {
      case 'g':
#ifndef PROFILE_BUILD
        graphicDemoFlag = true;
#endif
        break;
      case 'i':
        imageOnlyFlag = true;
#ifndef PROFILE_BUILD
        graphicDemoFlag = true;
#endif
        break;
      default:
        printf("Ignoring unrecognized option: %c\n", optchar);
        continue;
    }
  }

  if (!imageOnlyFlag) {
    // Shift remaining arguments over.
    int remaining_args = argc - optind;
    for (int i = 1; i <= remaining_args; i++) {
      argv[i] = argv[i + optind - 1];
    }

    // Check to make sure number of arguments is correct.
    if (remaining_args < 1) {
      printf("Usage: %s [-g] [-i] <numFrames> <optional input_file>\n", argv[0]);
      printf("  -g : show graphics\n");
      printf("  -i : show first image only (ignore numFrames)\n");
      exit(-1);
    }

    numFrames = atoi(argv[1]);
    if (remaining_args > 1) {
      input_file_path = argv[2];
    } else {
      input_file_path = DEFAULT_INPUT_FILE_PATH;
    }

    printf("Input file path is: %s\n", input_file_path);
    printf("Number of frames = %u\n", numFrames);
  }

  // Create and initialize the Line simulation environment.
  LineDemo *lineDemo = LineDemo_new();
  LineDemo_setInputFile(input_file_path);
  LineDemo_initLine(lineDemo);
  LineDemo_setNumFrames(lineDemo, numFrames);

  const fasttime_t start_time = gettime();

#ifndef PROFILE_BUILD
  // Run demo.
  if (graphicDemoFlag) {
    graphicMain(argc, argv, lineDemo, imageOnlyFlag);
  } else {
    lineMain(lineDemo);
  }
#else
  lineMain(lineDemo);
#endif

  const fasttime_t end_time = gettime();

  // Output results.
  printf("---- RESULTS ----\n");
  printf("Elapsed execution time: %fs\n",
         tdiff(start_time, end_time));
  printf("%u Line-Wall Collisions\n",
         LineDemo_getNumLineWallCollisions(lineDemo));
  printf("%u Line-Line Collisions\n",
         LineDemo_getNumLineLineCollisions(lineDemo));
  printf("---- END RESULTS ----\n");

  // delete objects
  LineDemo_delete(lineDemo);

  return 0;
}
Exemplo n.º 18
0
Pochoir_Boundary_End

int main(int argc, char * argv[])
{
	const int BASE = 1024;
	int t;
	struct timeval start, end;
    double min_tdiff = INF;
    int N_SIZE = 0, T_SIZE = 0;

    if (argc < 3) {
        printf("argc < 3, quit! \n");
        exit(1);
    }
    N_SIZE = StrToInt(argv[1]);
    T_SIZE = StrToInt(argv[2]);
    printf("N_SIZE = %d, T_SIZE = %d\n", N_SIZE, T_SIZE);
    Pochoir_Shape_2D heat_shape_2D[] = {{1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, -1, -1}, {0, 0, -1}, {0, 0, 1}, {0, 0, 0}};
	Pochoir_Array_2D(double) a(N_SIZE, N_SIZE), b(N_SIZE+2, N_SIZE+2);
    Pochoir_2D heat_2D(heat_shape_2D);

	printf("a(T+1, J, I) = 0.125 * (a(T, J+1, I) - 2.0 * a(T, J, I) + a(T, J-1, I)) + 0.125 * (a(T, J, I+1) - 2.0 * a(T, J, I) + a(T, J, I-1)) + a(T, J, I)\n");

    Pochoir_Kernel_2D(heat_2D_fn, t, i, j)
	   a(t+1, i, j) = 0.125 * (a(t, i+1, j) - 2.0 * a(t, i, j) + a(t, i-1, j)) + 0.125 * (a(t, i, j+1) - 2.0 * a(t, i, j) + a(t, i, j-1)) + a(t, i, j);
    Pochoir_Kernel_End

    a.Register_Boundary(heat_bv_2D);
    heat_2D.Register_Array(a);
    b.Register_Shape(heat_shape_2D);

	for (int i = 0; i < N_SIZE+2; ++i) {
	for (int j = 0; j < N_SIZE+2; ++j) {
        if (i == 0 || i == N_SIZE-1 ||
            j == 0 || j == N_SIZE-1) {
            b(0, i, j) = b(1, i, j) = 0;
        } else {
            a(0, i-1, j-1) = 1.0 * (rand() % BASE); 
            a(1, i-1, j-1) = 0; 
            b(0, i, j) = a(0, i-1, j-1);
            b(1, i, j) = 0;
        }
	} }

    for (int times = 0; times < TIMES; ++times) {
	    gettimeofday(&start, 0);
        heat_2D.Run(T_SIZE, heat_2D_fn);
	    gettimeofday(&end, 0);
        min_tdiff = min(min_tdiff, (1.0e3 * tdiff(&end, &start)));
    }
	printf("Pochoir consumed time : %.3f ms\n", min_tdiff);

    min_tdiff = INF;
    /* cilk_for + zero-padding */
    for (int times = 0; times < TIMES; ++times) {
	gettimeofday(&start, 0);
	for (int t = 0; t < T_SIZE; ++t) {
    cilk_for (int i = 1; i < N_SIZE+1; ++i) {
	for (int j = 1; j < N_SIZE+1; ++j) {
       b.interior(t+1, i, j) = 0.125 * (b.interior(t, i+1, j) - 2.0 * b.interior(t, i, j) + b.interior(t, i-1, j)) + 0.125 * (b.interior(t, i, j+1) - 2.0 * b.interior(t, i, j) + b.interior(t, i, j-1)) + b.interior(t, i, j); 
    } } }
	gettimeofday(&end, 0);
    min_tdiff = min(min_tdiff, (1.0e3 * tdiff(&end, &start)));
    }
	printf("Parallel Loop consumed time : %.3f ms \n", min_tdiff); 

#if 1
	t = T_SIZE;
	for (int i = 0; i < N_SIZE; ++i) {
	for (int j = 0; j < N_SIZE; ++j) {
		check_result(t, i, j, a.interior(t, i, j), b.interior(t, i+1, j+1));
	} } 
#endif
	return 0;
}
Exemplo n.º 19
0
/**
 * Select a lut item to be immediately executed.
 */
int ov680_fwi_run_force(enum ov680_fwi_section section, uint32_t index)
{
	struct msm_camera_i2c_reg_conf *arr = NULL;
	uint16_t size = 0;
	int rc = 0;
	struct timespec t1,t0;

	mutex_lock(&ov680_props.fw_mutex);
	ov680_verb("Run section - section=%d, index=%d\n", section, index);

	if (!ov680_fwi_ops[section].enabled) {
		ov680_info("Section (%d) is disabled.\n",
			   section);
		goto end;
	}

	if(ov680_props.ov680_fw_image[section].enabled && ov680_props.ov680_fw_image[section].subsections[index].enabled)
	{
		arr = ov680_props.ov680_fw_image[section].subsections[index].conf;
		size = ov680_props.ov680_fw_image[section].subsections[index].size;
	}
	else
	{
		ov680_err("Section %d not enabled", section);
		rc = -EBUSY;
		goto end;
	}

	ov680_dbg("Begin %s(%d)[index=%d].\n",ov680_props.ov680_fw_image[section].name,section, index);

	getnstimeofday(&t0);
	rc = ov680_props.s_ctrl.sensor_i2c_client->
	    i2c_func_tbl->i2c_write_conf_tbl(ov680_props.s_ctrl.sensor_i2c_client,
					     arr, size,
					     MSM_CAMERA_I2C_BYTE_DATA);
	getnstimeofday(&t1);
	ov680_perf("Section[%s] Sub[%s] took - %d us", ov680_props.ov680_fw_image[section].name, ov680_props.ov680_fw_image[section].subsections[index].name, tdiff(&t1, &t0));

	if(rc){
		ov680_err("!!! cci write failed [%d], retry once again !!!", rc);
		rc = ov680_props.s_ctrl.sensor_i2c_client->
		    i2c_func_tbl->i2c_write_conf_tbl(ov680_props.s_ctrl.sensor_i2c_client,
						     arr, size,
						     MSM_CAMERA_I2C_BYTE_DATA);
	}
	ov680_dbg("End %s(%d)[index=%d].\n",ov680_props.ov680_fw_image[section].name,section, index);
end:
	mutex_unlock(&ov680_props.fw_mutex);
	return rc;
}