Debian Codegraph @

protolib/include/protoTimer.h

raw
1 /*********************************************************************
2 *
3 * AUTHORIZATION TO USE AND DISTRIBUTE
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that:
7 *
8 * (1) source code distributions retain this paragraph in its entirety,
9 *
10 * (2) distributions including binary code include this paragraph in
11 * its entirety in the documentation or other materials provided
12 * with the distribution, and
13 *
14 * (3) all advertising materials mentioning features or use of this
15 * software display the following acknowledgment:
16 *
17 * "This product includes software written and developed
18 * by Brian Adamson, Justin Dean, and Joe Macker of the Naval
19 * Research Laboratory (NRL)."
20 *
21 * The name of NRL, the name(s) of NRL employee(s), or any entity
22 * of the United States Government may not be used to endorse or
23 * promote products derived from this software, nor does the
24 * inclusion of the NRL written and developed software directly or
25 * indirectly suggest NRL or United States Government endorsement
26 * of this product.
27 *
28 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
29 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
30 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
31 ********************************************************************/
32
33
34 #ifndef _PROTO_TIMER
35 #define _PROTO_TIMER
36
37 #include "protoDebug.h"
38 #include "protoDefs.h" // for ProtoSystemTime()
39 #include "protoTime.h"
40 #include "protoTree.h" // for ProtoSortedTree
41 #include <math.h>
42
43 #define _SORTED_TIMERS 1
44
45 /**
46 * @class ProtoTimer
47 *
48 * @brief This is a generic timer class which will notify a ProtoTimer::Listener upon timeout.
49 *
50 * A list of ProtoTimers is managed by the ProtoTimerMgr class after they are "activated".
51 * The ProtoDispatcher's "main loop" calls ProtoTimerMgr::OnSystemTimeout at regular intervals
52 * to determine if any timer objects have timed out. If so, the callback function
53 * associated with the ProtoTimer::Listener is invoked.
54 *
55 */
56 class ProtoTimer
57 #ifdef _SORTED_TIMERS
58 : public ProtoSortedTree::Item
59 #endif // _SORTED_TIMERS
60 {
61 friend class ProtoTimerMgr;
62
63 public:
64 ProtoTimer();
65 ~ProtoTimer();
66
67 /**
68 * This function sets what class instance (timer listener) and method will be
69 * invoked upon a timer timeout..
70 *
71 * Note there are two forms for the listener method here. The newer form has a "void"
72 * return type and requires less consideration for its implementation. The older
73 * (likely to be deprecated) form has a "bool" return type that is used to indicate
74 * whether the ProtoTimer instance (and likely its listener) are any longer valid
75 * (and implies whether or not it should be reinstalled if it is a repeating timer).
76 * The current ProtoTimerMgr automates the detection/management of this case, thus
77 * the newer, easier-to-use form. The old form is retained simply for backwards
78 * compatibility.
79 *
80 * IMPORTANT: For the "legacy" listener method form and _older_ Protolib versions, the
81 * 'bool' return value of this function MUST be set appropriately. When returning "true"
82 * the 'repeat_count' will be decremented and the timer will be reactivated or
83 * deactivated accordingly. So, if the timer is rescheduled, canceled, or deleted during
84 * the listener method invocation, the method MUST return "false'. Again, NOTE that
85 * the _current_ Protolib automatically tracks timer change/deletion and the return value
86 * is now ignored.
87
88 * NOTE: For VC++ 6.0 Debug builds, you _cannot_ use pre-compiled
89 * headers with this template code. Also, "/ZI" or "/Z7" compile options
90 * must NOT be specified. (or else VC++ 6.0 experiences an "internal compiler error")
91 *
92 * @param theListener a pointer to the "listening" object
93 * @param timeoutHandler a pointer to the listener's callback function.
94 *
95 */
96
97
98 // This is our new "ProtoTimer::SetListener()" where the listener timeoutHandler
99 // has a "void" return type instead of the old "bool" since we don't care about
100 // the return type anymore. (yay!)
101 template <class LTYPE>
102 bool SetListener(LTYPE* theListener, void(LTYPE::*timeoutHandler)(ProtoTimer&))
103 {
104 if (NULL != listener) delete listener;
105 listener = theListener ? new LISTENER_TYPE<LTYPE>(theListener, timeoutHandler) : NULL;
106 return (NULL == listener) ? (NULL != theListener) : true;
107 }
108
109 // This is the old "ProtoTimer::SetListener()" we keep for backwards-compatibility
110 // WARNING: This _will_ be deprecated in the future
111 template <class LTYPE>
112 bool SetListener(LTYPE* theListener, bool(LTYPE::*timeoutHandler)(ProtoTimer&))
113 {
114 if (NULL != listener) delete listener;
115 listener = theListener ? new OLD_LISTENER_TYPE<LTYPE>(theListener, timeoutHandler) : NULL;
116 return (NULL == listener) ? (NULL != theListener) : true;
117 }
118
119 /**
120 * This method sets the interval (in seconds) after which the
121 * timer will "fire" (i.e., the listener/method specified by
122 * ProtoTimer::SetListener() is invoked).
123 *
124 * @param theInterval timer interval in seconds
125 */
126 // Our ProtoTime class currently only handles 1 usec granularity (for non-zero timeouts)
127 // so we enforce that constraint here.
128 void SetInterval(double theInterval)
129 {interval = (theInterval >= 1.0e-06) ? theInterval : ((theInterval > 0.0) ? 1.0e-06 : 0.0);}
130
131 double GetInterval() const {return interval;}
132 /**
133 * Timer repetition (0 = one shot, -1 = infinite repetition)
134 *
135 * @param numRepeat number of timer repetitions (0 is one-shot)
136 */
137 void SetRepeat(int numRepeat)
138 {repeat = numRepeat;}
139 int GetRepeat() const
140 {return repeat;}
141
142 /// Provided for "advanced" timer monitoring/control
143 void ResetRepeat()
144 {repeat_count = repeat;}
145 /// Provided for "advanced" timer monitoring/control
146 void DecrementRepeatCount()
147 { if (repeat_count > 0) repeat_count--; }
148 /// Provided for "advanced" timer monitoring/control
149
150 int GetRepeatCount() {return repeat_count;}
151 /// Provided for "advanced" timer monitoring/control
152
153 /// This must be used with wisdom!
154 void SetRepeatCount(int repeatCount)
155 {repeat_count = repeatCount;}
156
157 // Activity status/control
158 /**
159 * Returns true if timer is associated with a ProtoTimerMgr
160 */
161 bool IsActive() const {return (NULL != mgr);}
162 double GetTimeRemaining() const;
163 const ProtoTime GetTimeout() const {return timeout;}
164 void Reset()
165 {
166 ResetRepeat();
167 if (IsActive()) Reschedule();
168 }
169 bool Reschedule();
170 void Scale(double factor);
171 void Deactivate();
172
173 // Ancillary
174 void SetUserData(const void* userData) {user_data = userData;}
175 const void* GetUserData() {return user_data;}
176
177 /**
178 * Installer commands
179 */
180 enum Command {INSTALL, MODIFY, REMOVE};
181 #ifdef _SORTED_TIMERS
182 void UpdateKey()
183 {timeout_key.SetValue(timeout);}
184 void InvalidateKey()
185 {timeout_key.Invalidate();}
186 bool KeyIsValid() const
187 {return timeout_key.IsValid();}
188
189 // ProtoSortedTree::Item required overrides
190 const char* GetKey() const
191 {return timeout_key.GetKey();}
192 unsigned int GetKeysize() const
193 {return timeout_key.GetKeysize();}
194 #endif // _SORTED_TIMERS
195
196 private:
197 /**
198 * Invokes the "listener's" callback function.
199 *
200 * TODO: Update with new timer functionality.
201 *
202 * @retval Returns the result of the listener's callback function if
203 * a listener exists for the timer.
204 */
205 void DoTimeout()
206 {if (NULL != listener) listener->on_timeout(*this);}
207
208 /**
209 * @class Listener
210 *
211 * @brief Listener base class
212 */
213 class Listener
214 {
215 public:
216 /// virtual destructor
217 virtual ~Listener() {}
218 /// virtual on_timeout function
219 virtual void on_timeout(ProtoTimer& theTimer) = 0;
220 };
221 /**
222 * @class LISTENER_TYPE
223 *
224 * @brief Template for Listener classes. (This will be deprecated)
225 */
226 template <class LTYPE>
227 class LISTENER_TYPE : public Listener
228 {
229 public:
230 /**
231 * Listener constructor
232 *
233 * @param theListener pointer to the "listening" object
234 * @param timeoutHandler *pointer to the Listener's callback function.
235 */
236 LISTENER_TYPE(LTYPE* theListener, void(LTYPE::*timeoutHandler)(ProtoTimer&))
237 : listener(theListener), timeout_handler(timeoutHandler) {}
238 /**
239 * @retval Returns the result of the Listeners timeout handler.
240 */
241 void on_timeout(ProtoTimer& theTimer)
242 {(listener->*timeout_handler)(theTimer);}
243 /**
244 * Duplicates the Listener member and returns a pointer to the new
245 * object.
246 */
247 Listener* duplicate()
248 {return (static_cast<Listener*>(new LISTENER_TYPE<LTYPE>(listener, timeout_handler)));}
249 private:
250 LTYPE* listener;
251 void (LTYPE::*timeout_handler)(ProtoTimer&);
252 }; // end class ProtoTimer::OLD_LISTENER_TYPE
253
254 /**
255 * @class OldListener
256 *
257 * @brief OldListener base class (will be deprecated)
258 */
259 class OldListener : public Listener
260 {
261 public:
262 /// virtual destructor
263 virtual ~OldListener() {}
264 /// virtual on_timeout function
265 void on_timeout(ProtoTimer& theTimer)
266 {old_on_timeout(theTimer);}
267 private:
268 virtual bool old_on_timeout(ProtoTimer& theTimer) = 0;
269 };
270
271 /**
272 * @class OLD_LISTENER_TYPE
273 *
274 * @brief Template for Listener classes. (This will be deprecated)
275 */
276 template <class LTYPE>
277 class OLD_LISTENER_TYPE : public OldListener
278 {
279 public:
280 /**
281 * Listener contstructor
282 *
283 * @param theListener pointer to the "listening" object
284 * @param timeoutHandler *pointer to the Listener's callback function.
285 */
286 OLD_LISTENER_TYPE(LTYPE* theListener, bool(LTYPE::*timeoutHandler)(ProtoTimer&))
287 : listener(theListener), timeout_handler(timeoutHandler) {}
288 /**
289 * @retval Returns the result of the Listeners timeout handler.
290 */
291 bool old_on_timeout(ProtoTimer& theTimer)
292 {return (listener->*timeout_handler)(theTimer);}
293 /**
294 * Duplicates the Listener member and returns a pointer to the new
295 * object.
296 */
297 OldListener* duplicate()
298 {return (static_cast<OldListener*>(new OLD_LISTENER_TYPE<LTYPE>(listener, timeout_handler)));}
299 private:
300 LTYPE* listener;
301 bool (LTYPE::*timeout_handler)(ProtoTimer&);
302 }; // end class ProtoTimer::OLD_LISTENER_TYPE
303
304 Listener* listener;
305
306 double interval;
307 int repeat;
308 int repeat_count;
309
310 const void* user_data;
311 ProtoTime timeout;
312 bool is_precise;
313 class ProtoTimerMgr* mgr;
314 #ifdef _SORTED_TIMERS
315 ProtoTime::Key timeout_key;
316 #else
317 ProtoTimer* prev;
318 ProtoTimer* next;
319 #endif // if/else _SORTED_TIMERS
320 }; // end class ProtoTimer
321
322 #ifdef _SORTED_TIMERS
323 class ProtoTimerList : public ProtoListTemplate<ProtoTimer> {};
324 class ProtoTimerTable : public ProtoSortedTreeTemplate<ProtoTimer> {};
325 #endif // _SORTED_TIMERS
326
327 /**
328 * @class ProtoTimerMgr
329 *
330 * @brief This class manages ProtoTimer instances when they are "activated".
331 * The ProtoDispatcher(see below) derives from this to manage ProtoTimers
332 * for an application. (The ProtoSimAgent base class contains a ProtoTimerMgr
333 * to similarly manage timers for a simulation instance).
334 */
335 class ProtoTimerMgr
336 {
337 friend class ProtoTimer;
338
339 public:
340 /// Default constructor
341 ProtoTimerMgr();
342 /// Default destructor
343 virtual ~ProtoTimerMgr();
344
345 // ProtoTimer activation/deactivation
346 virtual void ActivateTimer(ProtoTimer& theTimer);
347 virtual void DeactivateTimer(ProtoTimer& theTimer);
348
349 /**
350 * @retval Returns "true" if there are any active timers
351 */
352 bool IsActive() const
353 {return (NULL != GetShortHead());}
354
355 /**
356 * @retval Returns any time remaining for the active short timer or -1
357 */
358 double GetTimeRemaining() const
359 {
360 ProtoTimer* next = GetShortHead();
361 return ((NULL != next) ? next->GetTimeRemaining() : -1.0);
362 }
363
364 /// Call this when the timer mgr's one-shot system timer fires
365 void OnSystemTimeout();
366
367 /// Special call to allow early dispatch of timeouts
368 void DoSystemTimeout()
369 {
370 bool updateStatus = update_pending;
371 update_pending = true;
372 OnSystemTimeout();
373 update_pending = updateStatus;
374 }
375
376 virtual void GetSystemTime(struct timeval& currentTime);
377
378 #ifdef _SORTED_TIMERS
379 // These are for testing
380 ProtoTimerTable& GetTimerTable() {return timer_table;}
381 ProtoTimerList& GetTimerList() {return timer_list;}
382 ProtoTimerTable& GetLongTable() {return long_timer_table;}
383 #endif // _SORTED_TIMERS
384
385 protected:
386 /// System timer association/management definitions and routines
387 virtual bool UpdateSystemTimer(ProtoTimer::Command command,
388 double delay) = 0;// {return true;}
389
390 private:
391 // Methods used internally
392 void ReactivateTimer(ProtoTimer& theTimer, const ProtoTime& now);
393 void InsertLongTimer(ProtoTimer& theTimer);
394 bool InsertLongTimerReverse(ProtoTimer& theTimer);
395 void RemoveLongTimer(ProtoTimer& theTimer);
396 void InsertShortTimer(ProtoTimer& theTimer);
397 bool InsertShortTimerReverse(ProtoTimer& theTimer);
398 void RemoveShortTimer(ProtoTimer& theTimer);
399 void Update();
400
401 #ifdef _SORTED_TIMERS
402 ProtoTimer* GetShortHead() const
403 {
404 ProtoTimer* next = timer_list.GetHead();
405 return (NULL != next) ? next : timer_table.GetHead();
406 }
407 ProtoTimer* GetLongHead() const {return long_timer_table.GetHead();}
408 #else
409 ProtoTimer* GetShortHead() const {return short_head;}
410 ProtoTimer* GetLongHead() const {return long_head;}
411 #endif // if/else _SORTED_TIMERS
412
413 bool GetNextTimeout(ProtoTime& nextTimeout) const
414 {
415 ProtoTimer* next = GetShortHead();
416 if (NULL != next)
417 {
418 nextTimeout = next->timeout;
419 return true;
420 }
421 else
422 {
423 return false;
424 }
425 }
426 void GetPulseTime(ProtoTime& pulseTime) const
427 {
428 pulseTime = pulse_mark;
429 pulseTime += (1.0 - pulse_timer.GetTimeRemaining());
430 }
431 bool OnPulseTimeout(ProtoTimer& theTimer);
432
433 static const double PRECISION_TIME_THRESHOLD;
434
435 void GetCurrentSystemTime(struct timeval& currentTime)
436 {
437 #if (defined(SIMULATE) && defined(NS2))
438 GetSystemTime(currentTime);
439 #else
440 ProtoSystemTime(currentTime);
441 #endif // if/else (SIMULATE && NS2)
442 }
443
444 // We need this to support some of our SIM code so it can
445 // find its simulation context
446 void GetCurrentProtoTime(ProtoTime& currentTime)
447 {
448 #if (defined(SIMULATE) && defined(NS2))
449 GetSystemTime(currentTime.AccessTimeVal());
450 #else
451 currentTime.GetCurrentTime();
452 #endif // if/else (SIMULATE && NS2)
453 }
454
455 // Member variables
456 bool update_pending;
457 bool timeout_scheduled;
458 ProtoTime scheduled_timeout;
459 ProtoTimer pulse_timer; // one second pulse timer
460 ProtoTime pulse_mark;
461
462 #ifdef _SORTED_TIMERS
463 unsigned int timer_list_count;
464 ProtoTimerList timer_list;
465 ProtoTimerTable timer_table;
466 ProtoTimerTable long_timer_table;
467 #else
468 ProtoTimer* long_head;
469 ProtoTimer* long_tail;
470 ProtoTimer* short_head;
471 ProtoTimer* short_tail;
472 #endif // if/else _SORTED_TIMERS
473 ProtoTimer* invoked_timer; // timer whose listener is being invoked
474 }; // end class ProtoTimerMgr
475
476 #endif // _PROTO_TIMER