Module System
[hide private]
[frames] | no frames]

Source Code for Module System

 1  # -*- coding: iso-8859-1 -*- 
 2   
 3  """Models the whole thing. 
 4      Process, controller and a main loop.""" 
 5   
 6  import threading 
 7  import time 
 8   
9 -class System(object):
10 """ 11 Manages the whole system. 12 13 process is the current controlled process. 14 controller is the current controller. 15 16 The whole system is executed in a separate thread. 17 The timer is also realized as separate thread. 18 """ 19
20 - def __init__(self,process=None,controller=None,logger=None):
21 self.process = process #: process to control 22 self.controller = controller #: controller for calulcating control values 23 self.logger = logger #: logging instance 24 self.stepsize = 0.01 #: step size of loop for simulations in seconds 25 self.run = 0 #: main loop in in continous run mode 26 self.run_event = threading.Event() #: controls the main loop's turn (if set make another turn) 27 self.main_thread = threading.Thread(target=self.main_loop) #: the main loop thread 28 self.main_thread.setDaemon(1) 29 self.main_thread.start() 30 self.timer_event = threading.Event() #: periodic trigger for main loop 31 self.timer_thread = threading.Thread(target=self.timer_loop) #: calculation time independent periodic trigger generator 32 self.timer_thread.setDaemon(1) 33 self.timer_thread.start()
34
35 - def main_loop(self):
36 """Realize main control loop as separate thread, so it can be 37 running indepently of the GUI timers""" 38 input = {} 39 output = {'a':0.0} 40 while 1: 41 self.run_event.wait() # wait for start impulse 42 if not self.run: # if only a step reset start impulse 43 self.run_event.clear() 44 try: 45 if self.process: 46 input = self.process.getStateValues(input) 47 if self.controller: 48 self.controller.calculate(input,output) 49 else: 50 output['a']=0.0 51 self.process.doStep(self.stepsize) 52 self.process.setControlValues(output) 53 if self.logger: 54 self.logger.log(input,output) 55 else: 56 self.run = 0 57 self.run_event.clear(); 58 except: 59 self.run = 0 60 self.run_event.clear(); 61 import traceback 62 traceback.print_exc() 63 64 # if run mode and is simulated, wait for next activation 65 if self.run:# and not self.process.no_timer: 66 self.timer_event.wait() 67 self.timer_event.clear()
68
69 - def timer_loop(self):
70 """Realize a timer, using sleep is usually more precise 71 than using the GUI timer""" 72 while 1: 73 self.run_event.wait() # only when running 74 time.sleep(self.stepsize) # wait until next impulse 75 self.timer_event.set() # activate timer impulse
76
77 - def start(self):
78 """Start the main loop.""" 79 self.run = 1 80 self.run_event.set()
81
82 - def stop(self):
83 """Stop the main loop.""" 84 self.run = 0 85 self.run_event.clear()
86
87 - def step(self):
88 """Make a single step of the main loop. ( = stop after one step)""" 89 self.run = 0 90 self.run_event.set()
91