Mercurial > hg > beaglert
annotate core/VirtualClock.cpp @ 139:4e2dd3eb1d28 ClockSync
The reported offset is now meaningful. The whole thing is waaay too jittery.
author | Giulio Moro <giuliomoro@yahoo.it> |
---|---|
date | Sun, 13 Sep 2015 21:34:47 +0100 |
parents | e77e2e712fbc |
children | 44d07fa9bd03 |
rev | line source |
---|---|
giuliomoro@135 | 1 #include "VirtualClock.h" |
giuliomoro@135 | 2 void VirtualClock::init(){ |
giuliomoro@135 | 3 firstRun=true; |
giuliomoro@135 | 4 movingAverage.setLength(31); //TODO: a better filtering algorithm ( Did you say Kalman?) |
giuliomoro@135 | 5 period=-1; |
giuliomoro@135 | 6 } |
giuliomoro@135 | 7 |
giuliomoro@135 | 8 VirtualClock::VirtualClock(){ |
giuliomoro@135 | 9 init(); |
giuliomoro@135 | 10 } |
giuliomoro@135 | 11 void VirtualClock::sync(){ |
giuliomoro@135 | 12 sync(1); |
giuliomoro@135 | 13 } |
giuliomoro@135 | 14 void VirtualClock::sync(double count){ |
giuliomoro@135 | 15 myClock_t currentTime=Clock::getTimeUs(); |
giuliomoro@135 | 16 if(firstRun==true){ |
giuliomoro@135 | 17 firstRun=false; |
giuliomoro@135 | 18 startTime=currentTime; |
giuliomoro@135 | 19 } else { |
giuliomoro@135 | 20 period=movingAverage.add((currentTime-lastSync)/count); //TODO: replace with Kalman filter |
giuliomoro@135 | 21 } |
giuliomoro@135 | 22 lastSync=currentTime; |
giuliomoro@139 | 23 // printf("lastSync: %lld\n",lastSync-startTime); |
giuliomoro@135 | 24 } |
giuliomoro@135 | 25 |
giuliomoro@135 | 26 double VirtualClock::getNow(){ |
giuliomoro@139 | 27 myClock_t currentSystemTime=Clock::getTimeUs(); |
giuliomoro@135 | 28 if(period<=0){ |
giuliomoro@139 | 29 return currentSystemTime; |
giuliomoro@135 | 30 } |
giuliomoro@135 | 31 // double beginningOfPeriod=lastSync; // TODO: if sync() does not get called every time (but e.g. only every so often), |
giuliomoro@135 | 32 // then this line (and the class) needs editing |
giuliomoro@139 | 33 myClock_t elapsed=(currentSystemTime-startTime); |
giuliomoro@139 | 34 double now=elapsed/(double)period; |
giuliomoro@139 | 35 // printf("elapsed=%lld; sincelastSync=%lld; period=%f; now=%f\n", elapsed, currentSystemTime-lastSync, period, now); |
giuliomoro@139 | 36 return now; |
giuliomoro@135 | 37 } |
giuliomoro@135 | 38 |
giuliomoro@135 | 39 double VirtualClock::getPeriod(){ |
giuliomoro@135 | 40 return period; |
giuliomoro@135 | 41 } |