Beispiel #1
0
/*
 * Sends the stored DMX state to its associated DMX port.  If fewer than
 * frame_period microseconds have elapsed since the start of the last frame,
 * then this function will delay until that time, unless status->period_mode is
 * nonzero, in which case calls to send_state will be ignored until the
 * specified frame period has elapsed.  This function should be called at least
 * once per second.  Returns zero on success, nonzero on error.
 */
int send_state(dmx_state *status)
{
	struct timespec this_time;

	if(status == NULL) {
		fprintf(stderr, "NULL status parameter");
		return -1;
	}

	// Mark before break + rate control
	fsync(status->fd); // fsync on a tty probably doesn't do anything...
	if(status->period_mode) {
		// Skip frame rate control mode
		clock_gettime(CLOCK_MONOTONIC, &this_time);
		if(compare_timespec(&this_time, status->next_time) < 0) {
			return 0;
		}
	} else {
		// Sleep rate control mode
		while(clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, status->next_time, NULL) == -1 && errno==EINTR) {
			// Repeatedly do nothing as long as clock_nanosleep() gets
			// interrupted (this space intentionally left blank)
		}
	}
	clock_gettime(CLOCK_MONOTONIC, status->next_time);
	status->next_time->tv_nsec += status->frame_period * 1000;
	if(status->next_time->tv_nsec >= 1000000000) {
		status->next_time->tv_nsec -= 1000000000;
		status->next_time->tv_sec += 1;
	}

	// Break
	if(ioctl(status->fd, TIOCSBRK, 0)) {
		perror("Error setting break");
		return -1;
	}
	usleep(status->break_time);
	if(ioctl(status->fd, TIOCCBRK, 0)) {
		perror("Error clearing break");
		return -1;
	}

	// Mark after break
	usleep(status->mark_time);

	// Data
	if(write(status->fd, &status->start_code, 1) < 0) {
		perror("Error sending start code");
		return -1;
	}
	if(write(status->fd, status->dmx_values, status->channels_to_send) < 0) {
		perror("Error sending dmx data");
		return -1;
	}

	return 0;
}
Beispiel #2
0
void
RTClock::sleepNext ()
{
  timeradd (&last_, &interval_, &last_);
  struct timespec req = timespecFromTimeval (last_);
  req.tv_sec = last_.tv_sec;
  req.tv_nsec = 1000 * last_.tv_usec;
  clock_nanosleep (CLOCK_REALTIME, TIMER_ABSTIME, &req, NULL);
}
Beispiel #3
0
void *blink5Hz(void *bla)
{
	struct timespec request;
	request.tv_nsec = 200000000;
	request.tv_sec = request.tv_nsec / 1000000000;

	while(!SHUTDOWN)
	{
		while(count % 2 == 0)
		{
			GPIO_write(LED_PATH, LED_ON);
			clock_nanosleep(CLOCK_REALTIME, SLEEP_FLAG, &request, NULL);
			GPIO_write(LED_PATH, LED_OFF);
		 	clock_nanosleep(CLOCK_REALTIME, SLEEP_FLAG, &request, NULL);
		}
		clock_nanosleep(CLOCK_REALTIME, SLEEP_FLAG, &request, NULL);
	}
	return;
}
Beispiel #4
0
int sleepFor( int32_t seconds,int32_t nanoseconds)
{
   struct timespec sSleepTime,sRemainder;
   int returnVal;
   sSleepTime.tv_sec = seconds;
   sSleepTime.tv_nsec = nanoseconds;
//   printf("target sec: %d, target nsec: %d\n",seconds,nanoseconds);
   returnVal = clock_nanosleep(CLOCK_REALTIME,0,&sSleepTime,&sRemainder);
   return returnVal;
}
Beispiel #5
0
void* periodicPrint() {
	while(1) {
		printf("hei\n");
		struct timespec next;
		clock_gettime(CLOCK_REALTIME, &next);
	
		timespec_add_us(&next, 500000);
		clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &next, NULL);
	}
}
Beispiel #6
0
/*****************************************************************************
 * msleep
 *****************************************************************************/
void msleep( mtime_t delay )
{
    struct timespec ts;
    ts.tv_sec = delay / 1000000;
    ts.tv_nsec = (delay % 1000000) * 1000;

#if defined( HAVE_CLOCK_NANOSLEEP )
    int val;
    while ( ( val = clock_nanosleep( CLOCK_MONOTONIC, 0, &ts, &ts ) ) == EINTR );
    if( val == EINVAL )
    {
        ts.tv_sec = delay / 1000000;
        ts.tv_nsec = (delay % 1000000) * 1000;
        while ( clock_nanosleep( CLOCK_REALTIME, 0, &ts, &ts ) == EINTR );
    }
#else
    while ( nanosleep( &ts, &ts ) && errno == EINTR );
#endif
}
Beispiel #7
0
void Timer::sync(Timer &t)
{
#if _POSIX_TIMERS > 0 && defined(HAVE_CLOCK_NANOSLEEP) && defined(POSIX_TIMERS)
    clock_nanosleep(_posix_clocking, TIMER_ABSTIME, &t.timer, NULL);
#elif defined(_MSWINDOWS_)
    SleepEx(t.get(), FALSE);
#else
    usleep(t.get());
#endif
}
Beispiel #8
0
/**
 * Sleep some amount of time.
 *
 * This service suspends the calling thread until the wakeup time specified by
 * @a rqtp, or a signal is delivered. The wakeup time is specified as a time
 * interval.
 *
 * If this service is interrupted by a signal and @a rmtp is not @a NULL, the
 * time remaining until the specified wakeup time is returned at the address @a
 * rmtp.
 *
 * The resolution of this service is one system clock tick.
 *
 * @param rqtp address of the wakeup time.
 *
 * @param rmtp address where the remaining time before wakeup will be stored if
 * the service is interrupted by a signal.
 *
 * @retval 0 on success;
 * @retval -1 with @a errno set if:
 * - EPERM, the caller context is invalid;
 * - EINVAL, the specified wakeup time is invalid;
 * - EINTR, this service was interrupted by a signal.
 *
 * @par Valid contexts:
 * - Xenomai kernel-space thread,
 * - Xenomai user-space thread (switches to primary mode).
 *
 * @see
 * <a href="http://www.opengroup.org/onlinepubs/000095399/functions/nanosleep.html">
 * Specification.</a>
 *
 */
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
{
	int err = clock_nanosleep(CLOCK_REALTIME, 0, rqtp, rmtp);

	if (!err)
		return 0;

	thread_set_errno(err);
	return -1;
}
Beispiel #9
0
void compensated_timer(void)
{
	int ret, x;
	cycles_t t1, t2, error;

	x=0;
	while(1){
		before = get_cycles();
		ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_RELTIME, &carrier_ts, NULL);
		if(ret)
			DIE("clock_nanosleep");
		delta = get_cycles() - before;

again:
		/* 
		 * If we are pass our max tolerance there is nothing we can do
		 * other than compensating the time base backward
		 */
		if(delta > MONOTONIC_PULSE_CYCLE){
			carrier_ts.tv_nsec = carrier_ts.tv_nsec - 
				((delta - MONOTONIC_PULSE_CYCLE)/CPU_CYCLE_PER_NSEC);
			fprintf(stderr, "#%Lu\n",carrier_ts.tv_nsec);

			/* 
			 * Here this is a cut & paste from above to avoid clobbering the
			 * main loop with if / else
			 */
			before = get_cycles();
			ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_RELTIME, &carrier_ts, NULL);
			/* Reset the time base to original value */
			carrier_ts.tv_nsec = V_SYNC_NSEC_PERIOD;
			if(ret)
				DIE("clock_nanosleep");
			delta = get_cycles() - before;
			goto again;
		}
		calibrated_ldelay(MONOTONIC_PULSE_CYCLE - delta);
		
		fprintf(stderr," %Lu\n", (get_cycles() - before));
		if(!(x%100))
			fprintf(stderr, ".");
	}
}
// Adds "delay" nanoseconds to timespecs and sleeps until that time
static void sleep_until(struct timespec *ts, int delay)
{

    ts->tv_nsec += delay;
    if(ts->tv_nsec >= 1000*1000*1000) {
        ts->tv_nsec -= 1000*1000*1000;
        ts->tv_sec++;
    }
    clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts,  NULL);
}
Beispiel #11
0
int nanosleep_lat_test(int clockid, long long ns)
{
	struct timespec start, end, target;
	long long latency = 0;
	int i, count;

	target.tv_sec = ns/NSEC_PER_SEC;
	target.tv_nsec = ns%NSEC_PER_SEC;

	if (clock_gettime(clockid, &start))
		return UNSUPPORTED;
	if (clock_nanosleep(clockid, 0, &target, NULL))
		return UNSUPPORTED;

	count = 10;

	/* First check relative latency */
	clock_gettime(clockid, &start);
	for (i = 0; i < count; i++)
		clock_nanosleep(clockid, 0, &target, NULL);
	clock_gettime(clockid, &end);

	if (((timespec_sub(start, end)/count)-ns) > UNRESONABLE_LATENCY) {
		printf("Large rel latency: %lld ns :", (timespec_sub(start, end)/count)-ns);
		return -1;
	}

	/* Next check absolute latency */
	for (i = 0; i < count; i++) {
		clock_gettime(clockid, &start);
		target = timespec_add(start, ns);
		clock_nanosleep(clockid, TIMER_ABSTIME, &target, NULL);
		clock_gettime(clockid, &end);
		latency += timespec_sub(target, end);
	}

	if (latency/count > UNRESONABLE_LATENCY) {
		printf("Large abs latency: %lld ns :", latency/count);
		return -1;
	}

	return 0;
}
Beispiel #12
0
int main()
{
	struct sigaction sa;
	pthread_t thread;
   sigemptyset(&sa.sa_mask);
   sa.sa_flags = 0;
   sa.sa_handler = sigintHandler;

	if (sigaction(SIGINT, &sa, NULL) == -1)
	{
		printf("MAIN: reserving sigaction failed!\n");
		return -1;
	}

	
	GPIO_export(SWITCH);
	GPIO_export(LED);
	GPIO_direction(SWITCH_DIRECTION_PATH,"in");
	GPIO_direction(LED_DIRECTION_PATH,"out");
	GPIO_write(LED_PATH, LED_OFF);

	if(pthread_create(&thread, NULL , blink5Hz , NULL))
	{
		printf("MAIN: error: Thread-creation failed!\n");
		return -1;
	}

	struct timespec request;
	request.tv_nsec = 50000000;
	request.tv_sec = request.tv_nsec / 1000000000;

	printf("Push the Button ..");fflush(stdout);
	while(!SHUTDOWN)
	{
		while(strcmp(GPIO_read(SWITCH_PATH),LOW) != 0)
			clock_nanosleep(CLOCK_REALTIME, SLEEP_FLAG, &request, NULL);

		while(strcmp(GPIO_read(SWITCH_PATH),HIGH) != 0)
			clock_nanosleep(CLOCK_REALTIME, SLEEP_FLAG, &request, NULL);
		
		count++;	
	}
}
Beispiel #13
0
void *timeout_helper(void *arg)
{
    struct to_info *tip;

    tip = (struct to_info *)arg;
    clock_nanosleep(CLOCK_REALTIME, 0, &tip->to_wait, NULL);
    (*tip->to_fn)(tip->to_arg);
    free(arg);
    return (0);
}
Beispiel #14
0
int main(){
   mqd_t mq;

   struct mq_attr attr;
	char QUEUE_NAME[] = "/test1";
	
	ssize_t bytes_read;
	int ret;

	struct timespec looptime;
	looptime.tv_sec = 1;
	looptime.tv_nsec = 0;
	
	testStruct msg;

   /* initialize the queue attributes */
   attr.mq_flags = 0;
   attr.mq_maxmsg = 1;
   attr.mq_msgsize = sizeof(testStruct);
   attr.mq_curmsgs = 0;

	//mq_unlink(QUEUE_NAME);
	
   /* create the message queue */
	mq = mq_open(QUEUE_NAME, O_WRONLY|O_NONBLOCK);
	
	int i;
	for(i = 0; i < 10; i++)
	{
		msg.a = i+1;
		msg.b = i+11;

   	ret = clock_nanosleep(CLOCK_REALTIME, NULL, &looptime, NULL);
		if(ret < 0)
		{
			printf("Problem with sleep\n");
		}

		/* send the message */
      bytes_read = mq_send(mq, (char *) &msg, 8, NULL);
		if(bytes_read < 0)
		{
			perror("");
			printf("error sending value to queue\n");
		}
		else
		{
			printf("sent: %d, %d\n",msg.a, msg.b);
		}
	}

	mq_close(mq);

	return 0;
};
static void run_leapsec(void)
{
	const struct timespec sleeptime = { 0, NSEC_PER_SEC / 2 };
	struct timespec now, leap, start;
	struct timex tx;

	clock_gettime(CLOCK_REALTIME, &now);
	start = now;
	tst_resm(TINFO, "test start at %s", strtime(&now));

	test_hrtimer_early_expiration();

	/* calculate the next leap second */
	now.tv_sec += 86400 - now.tv_sec % 86400;
	now.tv_nsec = 0;
	leap = now;
	tst_resm(TINFO, "scheduling leap second %s", strtime(&leap));

	/* start before the leap second */
	now.tv_sec -= SECONDS_BEFORE_LEAP;
	if (clock_settime(CLOCK_REALTIME, &now) < 0)
		tst_brkm(TBROK | TERRNO, cleanup, "clock_settime");
	tst_resm(TINFO, "setting time to        %s", strtime(&now));

	/* reset NTP time state */
	adjtimex_status(&tx, STA_PLL);
	adjtimex_status(&tx, 0);

	/* set the leap second insert flag */
	adjtimex_status(&tx, STA_INS);

	/* reliably sleep till after the leap second */
	while (tx.time.tv_sec < leap.tv_sec + SECONDS_AFTER_LEAP) {
		adjtimex_status(&tx, tx.status);
		clock_nanosleep(CLOCK_MONOTONIC, 0, &sleeptime, NULL);
	}

	test_hrtimer_early_expiration();

	adjtimex_status(&tx, STA_PLL);
	adjtimex_status(&tx, 0);

	/* recover from timer expiring state and restore time */
	clock_gettime(CLOCK_REALTIME, &now);
	start.tv_sec += now.tv_sec - (leap.tv_sec - SECONDS_BEFORE_LEAP);
	start.tv_nsec += now.tv_nsec;
	start.tv_sec += start.tv_nsec / NSEC_PER_SEC;
	start.tv_nsec = start.tv_nsec % NSEC_PER_SEC;
	tst_resm(TINFO, "restoring time to %s", strtime(&start));
	/* calls clock_was_set() in kernel to revert inconsistency */
	if (clock_settime(CLOCK_REALTIME, &start) < 0)
		tst_brkm(TBROK | TERRNO, cleanup, "clock_settime");

	test_hrtimer_early_expiration();
}
Beispiel #16
0
void *client(void *arg)
{
	struct rtipc_port_label plabel;
	struct sockaddr_ipc svsaddr;
	int ret, s, n = 0, len;
	struct timespec ts;
	char buf[128];

	s = socket(AF_RTIPC, SOCK_DGRAM, IPCPROTO_BUFP);
	if (s < 0)
		fail("socket");

	/*
	 * Set the port label. This name will be used to find the peer
	 * when connecting, instead of the port number. The label must
	 * be set _after_ the socket is bound to the port, so that
	 * BUFP does not try to register this label for the client
	 * port as well (like the server thread did).
	 */
	strcpy(plabel.label, BUFP_PORT_LABEL);
	ret = setsockopt(s, SOL_BUFP, BUFP_LABEL,
			 &plabel, sizeof(plabel));
	if (ret)
		fail("setsockopt");

	memset(&svsaddr, 0, sizeof(svsaddr));
	svsaddr.sipc_family = AF_RTIPC;
	svsaddr.sipc_port = -1;	/* Tell BUFP to search by label. */
	ret = connect(s, (struct sockaddr *)&svsaddr, sizeof(svsaddr));
	if (ret)
		fail("connect");

	for (;;) {
		len = strlen(msg[n]);
		ret = write(s, msg[n], len);
		if (ret < 0) {
			close(s);
			fail("write");
		}
		rt_printf("%s: sent %d bytes, \"%.*s\"\n",
			  __FUNCTION__, ret, ret, msg[n]);
		n = (n + 1) % (sizeof(msg) / sizeof(msg[0]));
		/*
		 * We run in full real-time mode (i.e. primary mode),
		 * so we have to let the system breathe between two
		 * iterations.
		 */
		ts.tv_sec = 0;
		ts.tv_nsec = 500000000; /* 500 ms */
		clock_nanosleep(CLOCK_REALTIME, 0, &ts, NULL);
	}

	return NULL;
}
Beispiel #17
0
void sleep_for_ms(uint64_t ms) {
    timespec ts;
    ts.tv_sec = ms / 1000;
    ts.tv_nsec = ms % 1000 * 1000000;

    while (clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL) == -1) {
        if (errno != EINTR) {
            roc_panic("clock_nanosleep(CLOCK_MONOTONIC): %s", errno_to_str().c_str());
        }
    }
}
Beispiel #18
0
int nssleep(long nsec) {
    struct timespec sleeptime;

    sleeptime.tv_sec = 0;
    sleeptime.tv_nsec = nsec;


    while (clock_nanosleep(CLOCK_MONOTONIC, 0, &sleeptime, NULL) == EINTR );

    return 0;
}
Beispiel #19
0
int main(int argc, char *argv[])
{
	struct timespec tssleep;
	int pid;
	struct sigaction act;

	if ((pid = fork()) == 0) {
		/* child here */

		act.sa_handler = handler;
		act.sa_flags = 0;
		if (sigemptyset(&act.sa_mask) != 0) {
			perror("sigemptyset() did not return success\n");
			return CHILDFAIL;
		}
		if (sigaction(SIGABRT, &act, 0) != 0) {
			perror("sigaction() did not return success\n");
			return CHILDFAIL;
		}
		tssleep.tv_sec = SLEEPSEC;
		tssleep.tv_nsec = 0;
		if (clock_nanosleep(CLOCK_REALTIME, 0, &tssleep, NULL) == EINTR) {
			return CHILDPASS;
		} else {
			printf("errno != EINTR\n");
			return CHILDFAIL;
		}
	} else {
		/* parent here */
		int i;

		sleep(1);

		if (kill(pid, SIGABRT) != 0) {
			printf("Could not raise signal being tested\n");
			return PTS_UNRESOLVED;
		}

		if (wait(&i) == -1) {
			perror("Error waiting for child to exit\n");
			return PTS_UNRESOLVED;
		}

		if (WIFEXITED(i) && WEXITSTATUS(i)) {
			printf("Test PASSED\n");
			return PTS_PASS;
		} else {
			printf("Test FAILED\n");
			return PTS_FAIL;
		}
	}

	return PTS_UNRESOLVED;
}
Beispiel #20
0
inline int rand_int()
{
	struct timespec ts;
	ts.tv_sec=0;
	ts.tv_nsec=1;
	clock_nanosleep(CLOCK_MONOTONIC,0,&ts,NULL);

	clock_gettime(CLOCK_MONOTONIC,&ts);
	unsigned seed=static_cast<unsigned>(0x0ffffffffl & ts.tv_nsec);
	return rand_r(&seed);
}
Beispiel #21
0
int test( void )
{
  struct timespec rqtp;
  struct timespec rmtp;
  int             result;

  rqtp.tv_sec = 0;
  rqtp.tv_nsec = 0;
  result = clock_nanosleep( CLOCK_REALTIME, 0, &rqtp, &rmtp );

  return result;
}
Beispiel #22
0
void calibrated_tx(void)
{
	int ret;
	cycles_t t1, t2, t3, delta;

	while(1){
		/* Here we mark the beginning of the cycle */
		t1 = get_cycles();
		fprintf(stderr,"%Lu\n", t1-t3);
		
		/* 
		 * Then we sleep for a period of time define as:
		 *  [(NSEC_PERIOD - TIMER_JITTER) - ((NSEC_PERIOD - TIMER_JITTER) + TIMER_JITTER)]
		 */
		ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_RELTIME, &carrier_ts, NULL);
		if(ret)
			DIE("clock_nanosleep");

		/* Calculater the real length of the sleep */
		delta = (get_cycles() - t1)/2;

		/* 
		 * If the sleep period is larger than the fundamental period (the timmer
		 * jitter is larger than TIMER_JITTER ) then error out
		 * TODO We need to ripple that value to the next sample
		 */
		if(delta > MONOTONIC_PULSE_CYCLE){
			fprintf(stderr,"#");
			return;
		}
		/*
		 * Then we trigger the padding LPJ to reach the exact value of 
		 * MONOTONIC_PULSE_CYCLE
		 */
		calibrated_ldelay(MONOTONIC_PULSE_CYCLE - delta);
		
		/* 
		 * Then we mark the time after the whole cycle
		 * t2 - t1 should be very close to MONOTONIC_PULSE_CYCLE
		 */
		t2 = get_cycles();

		/*
		 * Then we start TX ops
		 * REMEMBER that we can be interrupted at any point in time 
		 * so the fundamental TX algo must be time adjusted as well
		 */
		calibrated_stream_tx(128, data);
		//WE need to prob back that jitter to the top of the loop
		t3 = get_cycles();
		fprintf(stderr,"%Lu\n", t3-t1);
	}
}
Beispiel #23
0
    void DcpuThread::sleep(uint64_t sleepTime) {
    	timespec sleepUntil;
		sleepUntil.tv_sec = sleepTime / SECOND_IN_NS;
		sleepUntil.tv_nsec = sleepTime % SECOND_IN_NS;

		// keep sleeping until we don't get an interrupted error code
		int errorCode;
		while ((errorCode = clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &sleepUntil, NULL)) == EINTR);
		if (errorCode != 0) {
			throw logic_error(str(format("clock_nanosleep: %s") % strerror(errorCode)));
		}
    }
static inline int energymon_clock_nanosleep(struct timespec* ts) {
#ifdef __MACH__
  // TODO: Sleep for any remaining time if interrupted
  return nanosleep(ts, NULL);
#else
  int ret;
  // continue sleeping only if interrupted
  while ((ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
                                ts, NULL)) == EINTR);
  return ret;
#endif
}
Beispiel #25
0
static unsigned long long calibrate(void)
{
	struct timespec start, end, delta;
	const int crunch_loops = 10000;
	unsigned long long ns, lps;
	unsigned long count;
	struct timespec req;
	char label[8];
	int n;

	count = 0;
	clock_gettime(CLOCK_MONOTONIC, &start);
	do_work(crunch_loops, &count);
	clock_gettime(CLOCK_MONOTONIC, &end);
	
	timespec_sub(&delta, &end, &start);
	ns = delta.tv_sec * ONE_BILLION + delta.tv_nsec;
	crunch_per_sec = (unsigned long long)((double)ONE_BILLION / (double)ns * crunch_loops);

	for (n = 0; n < nrthreads; n++) {
		sprintf(label, "t%d", n);
		create_fifo_thread(threads[n], label, counts[n]);
		sem_wait(&ready);
	}

	pthread_mutex_lock(&lock);
	started = 1;
	pthread_cond_broadcast(&barrier);
	pthread_mutex_unlock(&lock);

	req.tv_sec = 1;
	req.tv_nsec = 0;
	clock_nanosleep(CLOCK_MONOTONIC, 0, &req, NULL);

	for (n = 0, lps = 0; n < nrthreads; n++) {
		lps += counts[n];
		pthread_kill(threads[n], SIGDEMT);
	}

	atomic_set(&throttle, 1);
	smp_wmb();

	for (n = 0; n < nrthreads; n++) {
		pthread_cancel(threads[n]);
		pthread_join(threads[n], NULL);
	}

	started = 0;
	atomic_set(&throttle, 0);

	return lps;
}
Beispiel #26
0
static void *run(void *data)
{
	(void)data; /* unused parameter. silence warning. */
	init_nl();
	raw_sample_buf_init();
	init_realtime();
	set_sample_period(SAMPLE_PERIOD_US);

	struct timespec deadline;
	clock_gettime(CLOCK_MONOTONIC, &deadline);

	int sample_no = 0;
	char *iface = strdup(g_iface);
	struct iface_stats *stats_frame = raw_sample_buf_produce_next();
	snprintf(stats_frame->iface, MAX_IFACE_LEN, "%s", iface);
	stats_frame->sample_period_us = sample_period_us;

	for (;;) {
		update_stats(&(stats_frame->samples[sample_no]), iface,
		             deadline);

		sample_no++;
		sample_no %= SAMPLES_PER_FRAME;

		/* set the iface, samples per period at start of each frame*/
		if (sample_no == 0) {
			pthread_mutex_lock(&g_iface_mutex);
			free(iface);
			iface = strdup(g_iface);

			stats_frame = raw_sample_buf_produce_next();
			snprintf(stats_frame->iface, MAX_IFACE_LEN, "%s",
			         iface);
			pthread_mutex_unlock(&g_iface_mutex);
			stats_frame->sample_period_us = sample_period_us;
			stats_handler(raw_sample_buf_consume_next());
		}

		deadline.tv_nsec += 1000 * sample_period_us;

		/* Normalize the time to account for the second boundary */
		if (deadline.tv_nsec >= 1000000000) {
			deadline.tv_nsec -= 1000000000;
			deadline.tv_sec++;
		}

		clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &deadline,
		                NULL);
	}

	return NULL;
}
Beispiel #27
0
int main(int argc, char **argv, char **envp)
{
	struct pollfd fdset[2];
	int nfds = 2;
	int gpio_fd, timeout, rc;
	char *buf[MAX_BUF];
	unsigned int gpio;
	int len;

   struct timespec t;
   struct sched_param param;
   /* default interval = 50000ns = 50us
    * cycle duration = 100us
    */
   int interval=50000;
   int i=0;

   /* set permissions of parallelport */
   //ioperm(PORT,1,1);

   if(argc>=2 && atoi(argv[1])>0)
   {
      printf("using realtime, priority: %d\n",atoi(argv[1]));
      param.sched_priority = atoi(argv[1]);
      /* enable realtime fifo scheduling */
      if(sched_setscheduler(0, SCHED_FIFO, &param)==-1){
         perror("sched_setscheduler failed");
         exit(-1);
      }
   }
   if(argc>=3)
      interval=atoi(argv[2]);

   /* get current time */
   clock_gettime(0,&t);
   /* start after one second */
   t.tv_sec++;
	gpio = 139;

	gpio_export(gpio);
	gpio_set_dir(gpio, 1);
   for(i=10000;i;i--){
      /* wait untill next shot */
      clock_nanosleep(0, TIMER_ABSTIME, &t, NULL);
      /* do the stuff */
      out();
      /* calculate next shot */
      t.tv_nsec+=interval;
      tsnorm(&t);
   }
   return 0;
}
Beispiel #28
0
/**
 * Record data from a single Sensor; to be run in a seperate thread
 * @param arg - Cast to Sensor* - Sensor that the thread will handle
 * @returns NULL (void* required to use the function with pthreads)
 */
void * Sensor_Loop(void * arg)
{
	Sensor * s = (Sensor*)(arg);
	Log(LOGDEBUG, "Sensor %d starts", s->id);

	// Until the sensor is stopped, record data points
	while (s->activated)
	{
		
		bool success = s->read(s->user_id, &(s->current_data.value));

		struct timespec t;
		clock_gettime(CLOCK_MONOTONIC, &t);
		s->current_data.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());	
		
		if (success)
		{
			if (s->sanity != NULL)
			{
				if (!s->sanity(s->user_id, s->current_data.value))
				{
					Fatal("Sensor %s (%d,%d) reads unsafe value", s->name, s->id, s->user_id);
				}
			}
			s->averaged_data.time_stamp += s->current_data.time_stamp;
			s->averaged_data.value = s->current_data.value;
			
			if (++(s->num_read) >= s->averages)
			{
				s->averaged_data.time_stamp /= s->averages;
				s->averaged_data.value /= s->averages;
				Data_Save(&(s->data_file), &(s->averaged_data), 1); // Record it
				s->num_read = 0;
				s->averaged_data.time_stamp = 0;
				s->averaged_data.value = 0;
			}
		}
		else
		{
			// Silence because strain sensors fail ~50% of the time :S
			//Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id);
		}


		clock_nanosleep(CLOCK_MONOTONIC, 0, &(s->sample_time), NULL);
		
	}
	
	// Needed to keep pthreads happy
	Log(LOGDEBUG, "Sensor %s (%d,%d) finished", s->name,s->id,s->user_id);
	return NULL;
}
int runTraj(char* s, struct hubo_ref *r, struct timespec *t) {
	int i = 0;
// int interval = 10000000; // 100 hz (0.01 sec)

 	char str[1000];
	FILE *fp;		// file pointer
	fp = fopen(s,"r");
	if(!fp) {
		printf("No Trajectory File!!!\n");
		return 1;  // exit if not file
	}

//	printf("Reading %s\n",s);
        while(fgets(str,sizeof(str),fp) != NULL) {
	//	printf("i = %d\n",i);
	//	i = i+1;
                // wait until next shot
                clock_nanosleep(0,TIMER_ABSTIME,t, NULL);

// ------------------------------------------------------------------------------
// ---------------[ DO NOT EDIT AVBOE THIS LINE]---------------------------------
// ------------------------------------------------------------------------------
		int len = strlen(str)-1;
		if(str[len] == "\n") {
			str[len] = 0;
		}

		getArg(str, r); 	
// ------------------------------------------------------------------------------
// ---------------[ DO NOT EDIT BELOW THIS LINE]---------------------------------
// ------------------------------------------------------------------------------

		// Cheeting No more RAP or LAP
/*
		r->ref[RHP] = 0.0;
		r->ref[LHP] = 0.0;
		r->ref[RAP] = 0.0;
		r->ref[LAP] = 0.0;
		r->ref[RKN] = 0.0;
		r->ref[LKN] = 0.0;
		r->ref[RAR] = 0.0;
		r->ref[LAR] = 0.0;
		r->ref[RHR] = 0.0;
		r->ref[LHR] = 0.0;
*/
        	ach_put( &chan_hubo_ref, r, sizeof(*r));
		//printf("Ref r = %s\n",ach_result_to_string(r));
                t->tv_nsec+=interval;
                tsnorm(t);
        }

}
Beispiel #30
0
int main (int argc, char **argv) {
	struct timespec next;
	E("clock_gettime", clock_gettime(CLK, &next));
	close(0); // we don't use stdin
	if (argc>=2) bpm = atol(argv[1]);
	struct timespec diff=timediff(bpm);
	struct mm_msg m = {MM_CLOCK, 0, 0, 0};
	for (;;) {
		mm_write(1, &m);
		addto(&next, &diff);
		if (clock_nanosleep(CLK, TIMER_ABSTIME, &next, NULL))
			err(1,"clock_nanosleep"); }
	return 0; }