@@ -497,6 +497,74 @@ def stop(self):
497
497
def get_duration (self ):
498
498
return self .end - self .start
499
499
500
+ class Watchdog (object ):
501
+ '''
502
+ Calls specified function after duration, unless reset/stopped beforehand
503
+
504
+ @param timeout_duration how long to wait before calling handler
505
+ @param handler function to call after timeout_duration
506
+ @param args for handler
507
+ @param kwargs for handler
508
+ '''
509
+ def __init__ (self , timeout_duration , handler , args = (), kwargs = {}):
510
+ self .timeout_duration = timeout_duration
511
+ self .handler = handler
512
+ self .handler_args = args
513
+ self .handler_kwargs = kwargs
514
+
515
+ self .thread_checking_time = threading .Thread (target = self ._check_timer_loop )
516
+ self .timer_thread_lock = threading .Lock ()
517
+ self .start_time = time .time ()
518
+ self .canceled = False
519
+
520
+ self .thread_checking_time .start ()
521
+
522
+ def reset (self ):
523
+ '''
524
+ Resets the timer
525
+
526
+ Causes the handler function to be called after the next
527
+ timeout duration is reached
528
+
529
+ Also restarts the timer thread if it has existed
530
+ '''
531
+ with self .timer_thread_lock :
532
+ if self .canceled or not self .thread_checking_time .is_alive ():
533
+ self .thread_checking_time = threading .Thread (target = self ._check_timer_loop )
534
+ self .thread_checking_time .start ()
535
+
536
+ self .start_time = time .time ()
537
+ self .canceled = False
538
+
539
+ def stop (self ):
540
+ '''
541
+ Stop the watchdog, so it will not call handler
542
+ '''
543
+ with self .timer_thread_lock :
544
+ self .canceled = True
545
+
546
+ def _check_timer_loop (self ):
547
+ '''
548
+ Internal function for timer thread to loop
549
+
550
+ If elapsed time has passed, calls the handler function
551
+ Exists if watchdog was canceled, or handler was called
552
+ '''
553
+ while True :
554
+ with self .timer_thread_lock :
555
+ if self .canceled :
556
+ break
557
+ elapsed_time = time .time () - self .start_time
558
+ if elapsed_time > self .timeout_duration :
559
+ self .handler (* self .handler_args , ** self .handler_kwargs )
560
+ with self .timer_thread_lock :
561
+ self .canceled = True
562
+ break
563
+ else :
564
+ time .sleep (self .timeout_duration - elapsed_time )
565
+
566
+
567
+
500
568
501
569
def quadraticPlusJointLimitObjective (dq , J , dx , q , q_min , q_max , delta_joint_penalty = 5e-1 , lambda_dqdist = 0.01 , * args ):
502
570
'''
0 commit comments