Package simulation :: Module System
[hide private]
[frames] | no frames]

Source Code for Module simulation.System

 1  # -*- coding: utf-8 -*- 
 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,stepsize=0.01,process=None,controller=None,logger=None):
21 self.process = process #: process to control 22 self.controller = controller #: controller for calculating control values 23 self.logger = logger #: logging instance 24 self.stepsize = stepsize #: step size of loop for simulations in seconds 25 self.run = 0 #: main loop in in continuous 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 independently of the GUI timers""" 38 while 1: 39 self.run_event.wait() # wait for start impulse 40 if not self.run: # if only a step reset start impulse 41 self.run_event.clear() 42 try: 43 if self.process: 44 input = self.process.getStateValues({}) 45 output = self.process.getDefaultControlValues() 46 if self.controller: 47 self.controller.calculate(input,output) 48 self.process.doStep(self.stepsize) 49 self.process.setControlValues(output) 50 if self.logger: 51 self.logger.log(input,output) 52 else: 53 self.run = 0 54 self.run_event.clear() 55 except: 56 self.run = 0 57 self.run_event.clear() 58 import traceback 59 traceback.print_exc() 60 61 # if run mode and is simulated, wait for next activation 62 if self.run:# and not self.process.no_timer: 63 self.timer_event.wait() 64 self.timer_event.clear()
65
66 - def timer_loop(self):
67 """Realize a timer, using sleep is usually more precise 68 than using the GUI timer""" 69 while 1: 70 self.run_event.wait() # only when running 71 time.sleep(self.stepsize) # wait until next impulse 72 self.timer_event.set() # activate timer impulse
73
74 - def start(self):
75 """Start the main loop.""" 76 self.run = 1 77 self.run_event.set()
78
79 - def stop(self):
80 """Stop the main loop.""" 81 self.run = 0 82 self.run_event.clear()
83
84 - def step(self):
85 """Make a single step of the main loop. ( = stop after one step)""" 86 self.run = 0 87 self.run_event.set()
88