00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045 #include <stdio.h>
00046 #include <sys/types.h>
00047 #include <sys/socket.h>
00048 #include <netinet/in.h>
00049 #include <strings.h>
00050 #include <string.h>
00051 #include <arpa/inet.h>
00052 #include <stdlib.h>
00053 #include <unistd.h>
00054 #include <signal.h>
00055 #include <errno.h>
00056 #include <pthread.h>
00057 #include <time.h>
00058 #include <sys/time.h>
00059 #include "timer.h"
00060
00061 #define JITTER_MAX 1000
00062
00063 long jitter(long period);
00064
00065 int delay_uS(int uS) {
00066 struct timeval to;
00067 long time_error;
00068 to.tv_sec = 0;
00069 to.tv_usec = uS;
00070 select(0,NULL,NULL,NULL,&to);
00071 time_error=jitter((long)uS);
00072 if ((time_error>JITTER_MAX)||(time_error<-JITTER_MAX)) {
00073 printf("%ld\n",time_error);
00074 }
00075 return (0);
00076 }
00077
00078 void *periodic_thread(void *arg) {
00079 int status;
00080 timer_struct_t *tp = (timer_struct_t *) arg;
00081
00082 while (1) {
00083 delay_uS(tp->timer_period);
00084 tp->timeout=1;
00085 }
00086 status = pthread_detach(pthread_self());
00087 return NULL;
00088 }
00089
00090 long jitter(long period) {
00091 static struct timeval tv_last;
00092 static int init=1;
00093 struct timeval tv;
00094 long delta;
00095 long error;
00096 gettimeofday(&tv,NULL);
00097 if (!init) {
00098 if (tv.tv_usec<tv_last.tv_usec) {
00099 delta=(1000000-tv_last.tv_usec)+tv.tv_usec;
00100 }
00101 else {
00102 delta=tv.tv_usec-tv_last.tv_usec;
00103 }
00104 tv_last.tv_usec=tv.tv_usec;
00105 error=delta-period;
00106 }
00107 else {
00108 tv_last.tv_usec=tv.tv_usec;
00109 error=0;
00110 init=0;
00111 }
00112 return(error);
00113 }
00114
00115