def __init__(self, name, lamps=None, parent=None): Logging.logEvent("Debug", "Status Update", { "message": "Creating ZoneControlStub: {}".format(name), "level": 3 }) self.zoneProfile = ProfileInstance.getInstance().zoneProfiles.getZone( name) self.lamps = lamps self.name = name self.parent = parent self.temp_temperature = None self.pid = PID() if lamps: # These are the PID settings for the lamps proportional_gain = .2 integral_gain = 0 derivative_gain = 0 else: # These are the PID settings for the heaters in the platen proportional_gain = .4 integral_gain = 0 derivative_gain = 0 self.pid.setKp(proportional_gain) self.pid.setKi(integral_gain) self.pid.setKd(derivative_gain)
def __init__(self): if ProfileInstance.__instance != None: raise Exception("This class is a singleton!") else: Logging.logEvent("Debug", "Status Update", { "message": "Creating ProfileInstance", "level": 2 }) self.zoneProfiles = ZoneCollection(self) # System Wide stats self.activeProfile = False self.vacuumWanted = False # TODO: When Profile aborted is vacuumWanted cleared? self.currentSetpoint = None self.recordData = False self.inRamp = False self.inHold = False self.inPause = False self.getStatusFromDB() self.systemStatusQueue = [] ProfileInstance.__instance = self
def saveProfile(self, json): try: name = json["name"] sql = "SELECT * FROM tvac.Thermal_Zone_Profile WHERE profile_name=\"{}\";".format( name) mysql = MySQlConnect() mysql.cur.execute(sql) mysql.conn.commit() results = mysql.cur.fetchall() if results: return "{'result':'Error, profile already exists'}" for zoneProfile in json['profiles']: result = self.saveZone(name, zoneProfile) if result != True: return str(result) Logging.logEvent( "Event", "Profile", { "message": "New Profile loaded: ({})".format(name), "ProfileInstance": self.parent.getInstance() }) return "{'result':'success'}" except Exception as e: Logging.debugPrint(3, "sql: {}".format(sql)) Logging.debugPrint( 1, "Error in loadProfile, zoneCollection: {}".format(str(e))) return str({'result': str(e)})
def __init__(self): if HardwareStatusInstance.__instance != None: raise Exception("This class is a singleton!") else: Logging.logEvent("Debug", "Status Update", { "message": "Creating HardwareStatusInstance", "level": 2 }) self.Thermocouples = ThermocoupleCollection() self.PfeifferGuages = PfeifferGaugeCollection() self.ShiCryopump = ShiCryopumpCollection() self.Shi_MCC_Cmds = [] # ['cmd', arg, arg,... arg] self.Shi_Compressor_Cmds = [] # 'cmd' self.TdkLambda_PS = TdkLambdaCollection() self.TdkLambda_Cmds = [] # ['cmd', arg, arg,... arg] self.PC_104 = PC_104_Instance.getInstance() # System Wide Stats if os.name == "posix": userName = os.environ['LOGNAME'] else: userName = "******" if "root" in userName: self.OperationalVacuum = False # self.OperationalVacuum = True else: self.OperationalVacuum = True self.VacuumState = None # self.VacuumState = "Operational Vacuum" HardwareStatusInstance.__instance = self
def __init__(self): Logging.logEvent("Debug", "Status Update", { "message": "Creating PfeifferGaugeCollection", "level": 2 }) self.pfGuageList = self.buildCollection() self.time = datetime.now()
def __init__(self): Logging.logEvent( "Debug", "Status Update", { "message": "Creating TDK Lambda DC Power Supplies Collection ", "level": 2 }) self.TdkLambda_ps = self.buildCollection() self.time = datetime.now()
def __init__(self): if ThreadCollectionInstance.__instance != None: raise Exception("This class is a singleton!") else: Logging.logEvent("Debug", "Status Update", { "message": "Creating ThreadCollectionInstance", "level": 2 }) self.threadCollection = ThreadCollection() ThreadCollectionInstance.__instance = self
def __init__(self, parent=None): Logging.logEvent("Debug", "Status Update", { "message": "Creating DutyCycleControlStub", "level": 2 }) self.zoneProfiles = ProfileInstance.getInstance().zoneProfiles self.parent = parent Thread.__init__(self) self.updatePeriod = ProfileInstance.getInstance( ).zoneProfiles.updatePeriod self.d_out = HardwareStatusInstance.getInstance().PC_104.digital_out self.zones = { "zone1": ZoneControlStub(name='zone1', lamps=['IR Lamp 1', 'IR Lamp 2'], parent=self), "zone2": ZoneControlStub(name='zone2', lamps=['IR Lamp 3', 'IR Lamp 4'], parent=self), "zone3": ZoneControlStub(name='zone3', lamps=['IR Lamp 6', 'IR Lamp 5'], parent=self), "zone4": ZoneControlStub(name='zone4', lamps=['IR Lamp 7', 'IR Lamp 8'], parent=self), "zone5": ZoneControlStub(name='zone5', lamps=['IR Lamp 9', 'IR Lamp 10'], parent=self), "zone6": ZoneControlStub(name='zone6', lamps=['IR Lamp 12', 'IR Lamp 11'], parent=self), "zone7": ZoneControlStub(name='zone7', lamps=['IR Lamp 13', 'IR Lamp 14'], parent=self), "zone8": ZoneControlStub(name='zone8', lamps=['IR Lamp 15', 'IR Lamp 16'], parent=self), # zone9 is the platen "zone9": ZoneControlStub(name='zone9', parent=self) } self.currentSetpoint = 1 self.ramp = False self.soak = False
def __init__(self, num=120): Logging.logEvent("Debug", "Status Update", { "message": "Creating ThermocoupleCollection", "level": 2 }) self.tcList = self.buildCollection(num) self.time = datetime.now() self.ValidTCs = [] self.InvalidTCs = [] for tc in self.tcList: self.updateValidTCs(tc)
def __init__(self, ThreadCollection): if LN2ControlStub.__instance != None: # correct to carry over from TCU.py? raise Exception("This class is a singleton!") else: Logging.logEvent("Debug","Status Update", {"message": "LN2: Creating LN2ControlStub", "level":2}) LN2ControlStub.__instance = self self.ThreadCollection = ThreadCollection self.hardwareStatus = HardwareStatusInstance self.SLEEP_TIME = 5 # will be 30 seconds super(LN2ControlStub, self).__init__()
def __init__(self): if PC_104_Instance.__instance != None: raise Exception("This class is a singleton!") else: Logging.logEvent("Debug", "Status Update", { "message": "Creating PC_104_Instance", "level": 2 }) self.digital_in = DigitalInContract() self.digital_out = DigitalOutContract() self.analog_in = AnalogInContract() self.analog_out = AnalogOutContract() PC_104_Instance.__instance = self
def run_set_cmd(self, fun, cmd): if len(cmd) <= 1: val = fun() elif len(cmd) == 2: val = fun(cmd[1]) elif len(cmd) == 3: val = fun(cmd[1], cmd[2]) else: raise Exception('run_cmd has to many arguments') if val['Error']: Logging.logEvent( "Debug", "Status Update", { "message": 'Shi MCC Set_"%s" Error Response: %s' % (cmd[0], val), "level": 3 })
def run_get_cmd(self, fun, key): val = fun() if val['Error']: Logging.logEvent( "Debug", "Status Update", { "message": 'Shi MCC Get_"%s" Error Response: %s' % (key, val), "level": 3 }) else: if 'Data' in val: self.hw.ShiCryopump.update({'MCC Params': {key: val['Data']}}) else: self.hw.ShiCryopump.update( {'MCC Params': { key: val['Response'] }})
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): Logging.logEvent("Debug", "Status Update", { "message": "Creating VacuumControlStub:", "level": 3 }) Thread.__init__(self, group=group, target=target, name=name) self.args = args self.kwargs = kwargs self.zoneProfiles = ProfileInstance.getInstance().zoneProfiles self.profile = ProfileInstance.getInstance() self.hw = HardwareStatusInstance.getInstance() self.state = None self.pres_opVac = 9e-5 self.pres_atm = 100 self.pres_cryoP_Prime = 40e-3 self.pres_chamber_crossover = 25e-3 self.pres_chamber_max_crossover = 40e-3 self.pres_min_roughing = 9e-4 self.pres_ruffon = 70 self.cryoPumpPressure = None self.chamberPressure = None self.roughPumpPressure = None self.updatePeriod = 1 # # FOR TESTING ################################ # self.state = "Operational Vacuum" # self.hw.OperationalVacuum = True # # FOR TESTING ################################ if os.name == "posix": userName = os.environ['LOGNAME'] else: userName = "******"
def runProfile(self, firstStart=True): ''' This assumes a profile is already loaded in RAM, it will start the profile Also making an entry in the DB ''' # Check to make sure there is an active profile in memory if not self.zoneProfiles.profileName: return "{'Error':'No Profile loaded in memory'}" if firstStart: result = self.addProfileInstancetoBD() # If there is an error connecting to the DB, return it if result != True: return result # starts all the HWcontrol threads try: for thread in self.zoneThreadDict: if self.zoneThreadDict[thread].zoneProfile.zone > 0: self.zoneThreadDict[thread].running = True self.zoneThreadDict[thread].daemon = True self.zoneThreadDict[thread].start() Logging.logEvent( "Debug", "Status Update", { "message": "Zone {} is handled, about the start".format( self.zoneThreadDict[thread].zoneProfile.zone), "level": 1 }) except Exception as e: pass ProfileInstance.getInstance().activeProfile = True Logging.debugPrint(2, "Setting Active Profile to True") return "{'result':'success'}"
def checkHold(self): ''' This is a helper function that keeps the loop held in same temp. It recreates the expected values with updated times at the end TODO: NOTE: if a hold is held less than updateTime it might not recalculate or even get in here ''' try: if ProfileInstance.getInstance().inHold: startHoldTime = int(time.time()) Logging.logEvent( "Event", "Hold Start", { "message": "In hold for first time", "ProfileInstance": ProfileInstance.getInstance() }) while ProfileInstance.getInstance().inHold: for zone in self.zones: if self.zones[zone].zoneProfile.activeZoneProfile: zone = self.zones[zone] # self.temp_temperature = zone.updateDutyCycle() time.sleep(.5) endHoldTime = int(time.time()) holdTime = endHoldTime - startHoldTime self.startTime = self.startTime + holdTime Logging.logEvent( "Event", "HoldEnd", { "message": "Just Left hold", "ProfileInstance": ProfileInstance.getInstance() }) Logging.logEvent( "Debug", "Status Update", { "message": "Leaving hold after {} seconds in hold, new startTime {}" .format(holdTime, self.startTime), "ProfileInstance": ProfileInstance.getInstance(), "level": 2 }) # regenerate expected time, moving things forward to account for hold for zone in self.zones: if self.zones[zone].zoneProfile.activeZoneProfile: self.zones[ zone].expected_temp_values, self.expected_time_values = self.zones[ zone].createExpectedValues( self.zones[zone].zoneProfile. thermalProfiles, startTime=self.startTime) except Exception as e: Logging.debugPrint( 1, "DCCS: Error in check Hold, Duty Cycle: {}".format(str(e))) if Logging.debug: raise e
def __init__(self, parent): if SafetyCheck.__instance != None: raise Exception("This class is a singleton!") else: Logging.logEvent("Debug", "Status Update", { "message": "Creating SafetyCheck", "level": 2 }) self.errorList = [] self.errorDict = { "System Alarm: High Temperature": False, "Product Saver Alarm: High Temperature": False, "Product Saver Alarm: Low Temperature": False, "Human Touch Alarm: High Temperature": False, "Human Touch Alarm: Low Temperature": False, "Raised Pressure While Testing": False, } self.MAX_UUT_TEMP = {} self.MIN_UUT_TEMP = {} SafetyCheck.__instance = self self.parent = parent super(SafetyCheck, self).__init__()
def checkPause(self): ''' This is a helper function that pauses the loop ''' try: if ProfileInstance.getInstance().inPause: startPauseTime = int(time.time()) Logging.logEvent("Event", "Pause Start", { "message": "In Pause for first time", "level": 3 }) while ProfileInstance.getInstance().inPause: for zone in self.zones: if self.zones[zone].zoneProfile.activeZoneProfile: zone = self.zones[zone] self.d_out.update({zone.lamps[1] + " PWM DC": 0}) self.d_out.update({zone.lamps[0] + " PWM DC": 0}) zone.pid.error_value = 0 zone.dutyCycle = 0 time.sleep(.5) endPauseTime = int(time.time()) pauseTime = endPauseTime - startPauseTime self.startTime = self.startTime + pauseTime Logging.logEvent("Event", "pauseEnd", { "message": "Just Left pause", "level": 3 }) Logging.logEvent( "Debug", "Status Update", { "message": "Leaving pause after {} seconds in pause, new startTime {}" .format(pauseTime, self.startTime), "level": 3 }) # regenerate expected time, moving things forward to account for pause for zone in self.zones: if self.zones[zone].zoneProfile.activeZoneProfile: self.zones[ zone].expected_temp_values, self.expected_time_values = self.zones[ zone].createExpectedValues( self.zones[zone].zoneProfile. thermalProfiles, startTime=self.startTime) except Exception as e: Logging.debugPrint( 1, "Error in check Pause, Duty Cycle Control Stub: {}".format( str(e))) if Logging.debug: raise e
"level": 2 }) if Logging.debug: raise e self.compressor.close_port() time.sleep(4) if __name__ == '__main__': # adding debug info if (len(sys.argv) > 1): for arg in sys.argv: if arg.startswith("-v"): Logging.verbos = arg.count("v") Logging.logEvent("Debug", "Status Update", { "message": "Debug on: Level {}".format(Logging.verbos), "level": 1 }) hw_status = HardwareStatusInstance.getInstance() hw_status.PC_104.digital_out.update({'CryoP Pwr Relay 1': True}) thread = ShiCompressorUpdater() thread.daemon = True thread.start() while True: time.sleep(5) print(hw_status.ShiCryopump.getJson())
def run(self): if os.name == "posix": userName = os.environ['LOGNAME'] else: userName = "******" # While true to restart the thread if it errors out while True: # Catch anything that goes wrong # This has no check because it should always be running try: # Thread "Start up" stuff goes here Logging.logEvent("Debug", "Status Update", { "message": "Starting Shi Mcc Control Stub Thread", "level": 2 }) if "root" in userName: # Live systems go here Logging.logEvent("Debug", "Status Update", { "message": "Power on the Shi Mcc", "level": 3 }) self.mcc.open_port() while self.hw.PC_104.digital_out.getVal( 'CryoP Pwr Relay 1') is None: time.sleep(1) Currently_powered = self.hw.PC_104.digital_out.getVal( 'MCC2 Power') self.hw.PC_104.digital_out.update({'MCC2 Power': True}) if not Currently_powered: time.sleep(5) self.mcc.flush_port() # Now send some initialization commands # The maximum second stage temperature the cryopump may start to restart after a power failure. val = self.mcc.Get_RegenParam_6() if val['Error']: Logging.logEvent( "Debug", "Status Update", { "message": 'Shi MCC GetRegenParam_6" Error Response: %s' % (val), "level": 4 }) raise Exception( "Shi MCC Error with Get_RegenParam_6: %s" % val['Response']) else: if val['Data'] != 65: self.run_set_cmd(self.mcc.Set_RegenParam, [' ', '6', 65]) # 2: Power failure recovery enabled only when T2 is less than the limit set point. val = self.mcc.Get_PowerFailureRecovery() if val['Error']: Logging.logEvent( "Debug", "Shi MCC Error", { "message": "Set_RegenParam: %s" % val['Response'], "level": 3 }) raise Exception( "Shi MCC Error with Set_RegenParam: %s" % val['Response']) else: if val['Data'] != 2: self.run_set_cmd(self.mcc.Set_RegenParam, [' ', 2]) next_param_read_time = time.time() # setup is done, this loop is the normal thread loop while True: next_mcc_read_time = time.time() + self.mcc_read_period if "root" in userName: try: Logging.logEvent( "Debug", "Status Update", { "message": "Reading and writing with ShiMccUpdater.", "level": 4 }) val = self.mcc.get_Status() if val['Error']: Logging.logEvent( "Debug", "Status Update", { "message": "Shi MCC Error Response: %s" % val['Response'], "level": 4 }) else: self.hw.ShiCryopump.update( {'MCC Status': val['Response']}) Logging.logEvent( "Debug", "Status Update", { "message": "Cryopump Stage 1: {:.1f}K; Stage 2: {:.1f}K" "".format( self.hw.ShiCryopump.get_mcc_status( 'Stage 1 Temp'), self.hw.ShiCryopump.get_mcc_status( 'Stage 2 Temp')), "level": 4 }) if time.time() > next_param_read_time: val = self.mcc.get_ParamValues() if val['Error']: Logging.logEvent( "Debug", "Status Update", { "message": "Shi MCC Error Response: %s" % val['Response'], "level": 4 }) else: self.hw.ShiCryopump.update( {'MCC Params': val['Response']}) next_param_read_time = time.time( ) + self.param_period while len(self.hw.Shi_MCC_Cmds): cmd = self.hw.Shi_MCC_Cmds.pop() if 'FirstStageTempCTL' == cmd[ 0]: # 2.9 • First Stage Temperature Control pg:10 self.run_set_cmd( self.mcc.Set_FirstStageTempCTL, cmd) self.run_get_cmd( self.mcc.Get_FirstStageTempCTL, "First Stage Temp CTL") elif 'PowerFailureRecovery' == cmd[ 0]: # 2.12 • Power Failure Recovery pg:11 self.run_set_cmd( self.mcc.Set_PowerFailureRecovery, cmd) self.run_get_cmd( self.mcc.Get_PowerFailureRecovery, "Power Failure Recovery") elif 'Turn_CryoPumpOn' == cmd[ 0]: # 2.14 • Pump On/Off/Query pg:13 self.run_set_cmd(self.mcc.Turn_CryoPumpOn, cmd) elif 'Turn_CryoPumpOff' == cmd[ 0]: # 2.14 • Pump On/Off/Query pg:13 self.run_set_cmd(self.mcc.Turn_CryoPumpOff, cmd) elif 'Close_PurgeValve' == cmd[ 0]: # 2.15 • Purge On/Off/Query pg:14 self.run_set_cmd(self.mcc.Close_PurgeValve, cmd) elif 'Open_PurgeValve' == cmd[ 0]: # 2.15 • Purge On/Off/Query pg:14 if self.hw.PC_104.digital_in.getVal( 'CryoP_GV_Closed'): self.run_set_cmd( self.mcc.Open_PurgeValve, cmd) else: Logging.logEvent( "Debug", "Status Update", { "message": 'Cryopump Gate Valve not closed. Purge valve not opened.', "level": 2 }) elif 'Start_Regen' == cmd[ 0]: # 2.16 • Regeneration pg:14 self.run_set_cmd(self.mcc.Start_Regen, cmd) Logging.logEvent( "Event", "Cryopump Regeneration", { "message": "Cryopump regeneration starting", "ProfileInstance": ProfileInstance.getInstance() }) elif 'Set_RegenParam' == cmd[ 0]: # 2.19 • Regeneration Parameters pg:16 self.run_set_cmd(self.mcc.Set_RegenParam, cmd) val = self.mcc.Get_RegenParam(cmd[1]) if val['Error']: Logging.logEvent( "Debug", "Status Update", { "message": 'Shi MCC GetRegenParam_%s" Error Response: %s' % (cmd[1], val), "level": 4 }) else: self.hw.ShiCryopump.update({ 'MCC Params': { "Regen Param_%s" % cmd[1]: val['Data'] } }) elif 'RegenStartDelay' == cmd[ 0]: # 2.21 • Regeneration Start Delay pg.18 self.run_set_cmd( self.mcc.Set_RegenStartDelay, cmd) self.run_get_cmd( self.mcc.Get_RegenStartDelay, "Regen Start Delay") elif 'Open_RoughingValve' == cmd[ 0]: # 2.24 • Rough On/Off/Query pg:19 self.run_set_cmd( self.mcc.Open_RoughingValve, cmd) elif 'Close_RoughingValve' == cmd[ 0]: # 2.24 • Rough On/Off/Query pg:19 self.run_set_cmd( self.mcc.Close_RoughingValve, cmd) elif 'Clear_RoughingInterlock' == cmd[ 0]: # 2.25 • Rough Valve Interlock pg:20 self.run_set_cmd( self.mcc.Clear_RoughingInterlock, cmd) elif 'SecondStageTempCTL' == cmd[ 0]: # 2.27 • Second Stage Temperature Control pg:21 self.run_set_cmd( self.mcc.Set_SecondStageTempCTL, cmd) self.run_get_cmd( self.mcc.Get_SecondStageTempCTL, "Second Stage Temp CTL") elif 'Turn_TcPressureOn' == cmd[ 0]: # 2.29 • TC On/Off/Query pg:22 self.run_set_cmd( self.mcc.Turn_TcPressureOn, cmd) elif 'Turn_TcPressureOff' == cmd[ 0]: # 2.29 • TC On/Off/Query pg:22 self.run_set_cmd( self.mcc.Turn_TcPressureOff, cmd) else: Logging.logEvent( "Error", 'Unknown Shi_MCC_Cmd: "%s"' % cmd[0], { "type": 'Unknown Shi_MCC_Cmd', "filename": 'ThreadControls/ShiMccUpdater.py', "line": 0, "thread": "ShiMccUpdater" }) except ValueError as err: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split( exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent( "Error", 'Error in ShiMccUpdater reading values: "%s"' % err, { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "ShiMccUpdater" }) if Logging.debug: raise err else: Logging.logEvent("Debug", "Status Update", { "message": "Test run of Shi MCC loop", "level": 4 }) if time.time() < next_mcc_read_time: time.sleep(next_mcc_read_time - time.time()) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent( "Error", "Shi MCC Interface Thread", { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "ShiMccUpdater" }) Logging.logEvent( "Debug", "Status Update", { "message": "There was a {} error in ShiMccUpdater. File: {}:{}\n{}" .format(exc_type, fname, exc_tb.tb_lineno, e), "level": 1 }) if Logging.debug: raise e self.mcc.close_port() time.sleep(4)
def run(self): while True: # While true to restart the thread if it errors out try: # Thread "Start up" stuff goes here Logging.logEvent( "Debug", "Status Update", { "message": "Starting TS Registers Control Stub Thread", "level": 2, }) self.ir_lamp_pwm_start() if os.name == "posix": userName = os.environ['LOGNAME'] else: userName = "******" if "root" in userName: # Root is only in live, might need to change in busy box self.ts_reg.open_Registers() self.da_io.digital_out.update( self.ts_reg.dio_read4(1, False)) self.da_io.digital_out.update( self.ts_reg.dio_read4(2, False)) self.da_io.digital_in.update(self.ts_reg.dio_read4(1)) self.da_io.digital_in.update(self.ts_reg.dio_read4(2)) time.sleep(1) self.time_test = time.time() # self.ts_reg.start_adc(1, 7, int(32e6 * self.adc_period)) self.ts_reg.start_adc(1, 7, 4000000) while True: for i in range(len(self.ir_lamp_pwm)): self.ir_lamp_pwm[i].update_waveform_state( self.da_io.digital_out.get_IR_Lamps_pwm_dc(i + 1)) if "root" in userName: Logging.logEvent( "Debug", "Status Update", { "message": "Reading and writing with PC 104", "level": 4 }) self.interlocks() self.ts_reg.do_write4([ self.da_io.digital_out.get_c1_b0(), self.da_io.digital_out.get_c1_b1(), self.da_io.digital_out.get_c1_b2(), self.da_io.digital_out.get_c1_b3() ], 1) self.ts_reg.do_write4([ self.da_io.digital_out.get_c2_b0(), self.da_io.digital_out.get_c2_b1(), self.da_io.digital_out.get_c2_b2(), self.da_io.digital_out.get_c2_b3() ], 2) if self.da_io.digital_out.getVal('RoughP Start'): self.da_io.digital_out.update( {'RoughP Start': False}) self.da_io.digital_in.update(self.ts_reg.dio_read4(1)) self.da_io.digital_in.update(self.ts_reg.dio_read4(2)) self.ts_reg.dac_write( self.da_io.analog_out.get_dac_counts(2), 2) self.ts_reg.dac_write( self.da_io.analog_out.get_dac_counts(3), 3) # self.read_analog_in() # loop period is adc_period * 2 seconds self.wait_for_next_Multipule(self.adc_period * 8) else: Logging.logEvent("Debug", "Status Update", { "message": "Test run of PC 104 loop", "level": 5 }) time.sleep(5) except Exception as e: # FileCreation.pushFile("Error",self.zoneUUID,'{"errorMessage":"%s"}'%(e)) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent( "Error", "Hardware Interface Thread", { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "TsRegistersUpdater" }) Logging.logEvent( "Debug", "Status Update", { "message": "There was a {} error in TsRegistersUpdater. File: {}:{}\n{}" .format(exc_type, fname, exc_tb.tb_lineno, e), "level": 2 }) if Logging.debug: raise e # nicely close things, to open them back up again... if os.name == "posix": userName = os.environ['LOGNAME'] else: userName = "******" if "root" in userName: self.ts_reg.close() time.sleep(4)
def do_POST(self): """Respond to a POST request.""" try: Logging.logEvent("Debug", "Status Update", { "message": "Received Post Request", "level": 1 }) body = self.getBody() path = self.path Logging.logEvent("Debug", "Status Update", { "message": "POST Request Path: {}".format(path), "level": 2 }) # You might need to decode the results if type(body) == type(b'a'): body = body.decode("utf-8") contractObj = json.loads(body) # Based on the path we are given, do different functions control = PostControl() result = { '/saveProfile': control.saveProfile, '/loadProfile': control.loadProfile, '/runSingleProfile': control.runSingleProfile, '/pauseZone': control.pauseSingleThread, '/pauseRemoveZone': control.removePauseSingleThread, '/holdZone': control.holdSingleThread, '/releaseHoldZone': control.releaseHoldSingleThread, '/abortZone': control.abortSingleThread, '/calculateRamp': control.calculateRamp, '/SendHwCmd': control.SendHwCmd, '/setPC104Digital': control.setPC104_Digital, '/setPC104Analog': control.setPC104_Analog, '/heatUpPlaten': control.heatUpPlaten, '/heatUpShroud': control.heatUpShroud, }[path](contractObj) Logging.logEvent("Debug", "Status Update", { "message": "Sending POST Results", "level": 1 }) Logging.logEvent( "Debug", "Status Update", { "message": "POST Results: {}".format( str(result).replace("\"", "'").encode()), "level": 2 }) self.setHeader() self.wfile.write(str(result).encode()) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent( "Error", "POST Handler", { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "Verb Handler" }) Logging.logEvent( "Debug", "Status Update", { "message": "There was a {} error in Server (POST Handler). File: {}:{}" .format(exc_type, fname, exc_tb.tb_lineno), "level": 1 }) self.setHeader() output = '{"Error":"%s"}\n' % (e) self.wfile.write(output.encode()) raise (e)
def run(self): # While true to restart the thread if it errors out while True: # Check to make sure there is an active profile # and that we are sitting in an operational vacuum # and that all drivers and updaters are running if ProfileInstance.getInstance().activeProfile and \ HardwareStatusInstance.getInstance().OperationalVacuum and \ ProfileInstance.getInstance().zoneProfiles.getActiveProfileStatus(): try: Logging.logEvent("Debug", "Status Update", { "message": "DCCS: Starting Duty Cycle thread", "level": 2 }) Logging.logEvent( "Event", "Start Profile", { 'time': datetime.time(), "message": ProfileInstance.getInstance(). zoneProfiles.profileName, "ProfileInstance": ProfileInstance.getInstance() }) ProfileInstance.getInstance( ).zoneProfiles.updateThermalStartTime(time.time()) # local temp variables for checking state #TODO: Start time should gotten somewhere else, not made here if self.zoneProfiles.thermalStartTime: self.startTime = self.zoneProfiles.thermalStartTime else: self.startTime = int(time.time()) currentSetpointTemporary = 1 rampTemporary = False soakTemporary = True Logging.logEvent("Debug", "Status Update", { "message": "DCCS: Setting up Platen", "level": 2 }) HardwareStatusInstance.getInstance().TdkLambda_Cmds.append( ['Setup Platen', '']) for zone in self.zones: if self.zones[zone].zoneProfile.activeZoneProfile: self.zones[zone].maxTempRisePerMin = self.zones[ zone].zoneProfile.maxHeatPerMin self.zones[zone].maxTempRisePerUpdate = ( self.zones[zone].maxTempRisePerMin / 60) * self.updatePeriod self.zones[ zone].expected_temp_values, self.expected_time_values = self.zones[ zone].createExpectedValues( self.zones[zone].zoneProfile. thermalProfiles, startTime=self.zoneProfiles. thermalStartTime) # Program loop is here while ProfileInstance.getInstance().activeProfile: Logging.logEvent( "Debug", "Status Update", { "message": "DCCS: Running Duty Cycle Thread", "level": 3 }) # You might need to stay is pause # get current time currentTime = time.time() # if there is no more expected time values, break out of while True loop if len(self.expected_time_values) <= 0: break # this will find the time value matching the current time # and give us the temp value it should be at that time. # print("currentTime: {}".format(currentTime)) # print("expected_time_values: {}".format(self.expected_time_values)) while currentTime > self.expected_time_values[0]: for zone in self.zones: if self.zones[ zone].zoneProfile.activeZoneProfile: self.zones[ zone].temp_temperature = self.zones[ zone].expected_temp_values[0] self.zones[ zone].expected_temp_values = self.zones[ zone].expected_temp_values[1:] self.expected_time_values = self.expected_time_values[ 1:] if len(self.setpoint_start_time) > 0: if currentTime > self.setpoint_start_time[0][0]: rampTemporary = True soakTemporary = False if currentTime > self.setpoint_start_time[ 0][1]: rampTemporary = False soakTemporary = True self.setpoint_start_time = self.setpoint_start_time[ 1:] currentSetpointTemporary += 1 if len(self.setpoint_start_time) <= 0: break if len(self.expected_time_values) <= 0: break self.checkPause() self.checkHold() # compare the temps just made with the values in self. # if they are different, or important log it if rampTemporary == True and self.ramp == False: ProfileInstance.getInstance( ).currentSetpoint = currentSetpointTemporary Logging.logEvent( "Event", "Profile", { "message": "Profile {} has entered setpoint {} Ramp". format( ProfileInstance.getInstance( ).zoneProfiles.profileName, currentSetpointTemporary), "ProfileInstance": ProfileInstance.getInstance() }) if soakTemporary == True and self.soak == False: if currentSetpointTemporary > 1: Logging.logEvent( "Event", "Profile", { "message": "Profile {} has entered setpoint {} Soak" .format( ProfileInstance.getInstance( ).zoneProfiles.profileName, currentSetpointTemporary - 1), "ProfileInstance": ProfileInstance.getInstance() }) ProfileInstance.getInstance.inRamp = False self.ramp = rampTemporary self.soak = soakTemporary # With the temp goal tempurture picked, make the duty cycle for zone in self.zones: if self.zones[zone].zoneProfile.activeZoneProfile: # This checks to see if a current temp has been made... if self.zones[zone].temp_temperature: self.zones[zone].updateDutyCycle() else: print("Waiting...") if len(self.expected_time_values) <= 0: break # sleep until the next time around time.sleep(self.updatePeriod) # end of inner while True # end of test # turning off lamps at the end of test for zone in self.zones: if self.zones[zone].zoneProfile.activeZoneProfile: zone = self.zones[zone] if zone.lamps: self.d_out.update( {zone.lamps[1] + " PWM DC": 0}) self.d_out.update( {zone.lamps[0] + " PWM DC": 0}) else: HardwareStatusInstance.getInstance( ).TdkLambda_Cmds.append( ['Platen Duty Cycle', 0]) #TODO: Turn off the heaters here Logging.logEvent( "Event", "End Profile", { 'time': datetime.time(), "message": ProfileInstance.getInstance(). zoneProfiles.profileName, "ProfileInstance": ProfileInstance.getInstance() }) HardwareStatusInstance.getInstance().TdkLambda_Cmds.append( ['Disable Platen Output', '']) self.updateDBwithEndTime() self.running = False tcList = HardwareStatusInstance.getInstance( ).Thermocouples.tcList for tc in tcList: tc.update({"zone": 0, "userDefined": False}) # self.zoneProfile.activeZoneProfile = False # This assumes all zones have the same end time ProfileInstance.getInstance().activeProfile = False ProfileInstance.getInstance().vacuumWanted = False except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split( exc_tb.tb_frame.f_code.co_filename)[1] print("Error: {} in file {}:{}".format( exc_type, fname, exc_tb.tb_lineno)) self.running = False ProfileInstance.getInstance( ).zoneProfiles.activeProfile = False Logging.debugPrint( 1, "DCCS: Error in run, Duty Cycle: {}".format(str(e))) Logging.logEvent( "Error", "Duty Cycle Control Stub Thread", { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "DutyCycleControlStub", "ThreadCollection": self.parent, "item": "Duty Cycle Control Stub", "itemID": -1, "details": "There is a software error ({})".format(e) }) if Logging.debug: raise e # end of try, catch else: Logging.debugPrint( 4, "DCCS: activeProfile: {}".format( ProfileInstance.getInstance().activeProfile)) Logging.debugPrint( 4, "DCCS: OperationalVacuum: {}".format( HardwareStatusInstance.getInstance().OperationalVacuum) ) Logging.debugPrint( 4, "DCCS: getActiveProfileStatus: {}".format( ProfileInstance.getInstance( ).zoneProfiles.getActiveProfileStatus())) # Sleeping so it doesn't busy wait time.sleep(1)
def run(self): # While true to restart the thread if it errors out while True: # Catch anything that goes wrong # This has no check because it should always be running try: # Thread "Start up" stuff goes here # Logging.logEvent("Event", "Thread Start", # {"thread": "Shi Compressor Updater", # "ProfileInstance": ProfileInstance.getInstance()}) Logging.logEvent("Debug", "Status Update", { "message": "Starting Shi Compressor Updater", "level": 2 }) if os.name == "posix": userName = os.environ['LOGNAME'] else: userName = "******" if "root" in userName: # Live systems go here Logging.logEvent("Debug", "Status Update", { "message": "Power on the Shi Compressor", "level": 3 }) self.compressor.open_port() while self.hw.PC_104.digital_out.getVal( 'CryoP Pwr Relay 1') is None: time.sleep(1) Currently_powered = self.hw.PC_104.digital_out.getVal( 'CryoP Pwr Relay 1') self.hw.PC_104.digital_out.update( {'CryoP Pwr Relay 1': True}) if not Currently_powered: time.sleep(5) self.compressor.flush_port() next_op_hours_read_time = time.time() # setup is done, this loop is the normal thread loop while True: next_compressor_read_time = time.time( ) + self.compressor_read_period if "root" in userName: try: Logging.logEvent( "Debug", "Status Update", { "message": "Reading and writing with ShiCompressorUpdater.", "level": 4 }) val = {} val.update(self.compressor.get_temperatures()) val.update(self.compressor.get_pressure()) val.update(self.compressor.get_status_bits()) if time.time() > next_op_hours_read_time: val.update(self.compressor.get_id()) next_op_hours_read_time += self.op_hours_read_period self.hw.ShiCryopump.update({'Compressor': val}) while len(self.hw.Shi_Compressor_Cmds): cmd = self.hw.Shi_Compressor_Cmds.pop() if 'on' == cmd: self.compressor.set_compressor_on() elif 'off' == cmd: self.compressor.set_compressor_off() elif 'reset' == cmd: self.compressor.set_reset() else: Logging.logEvent( "Error", 'Unknown Shi_Compressor_Cmds: "%s"' % cmd, { "type": 'Unknown Shi_Compressor_Cmds', "filename": 'ThreadControls/ShiCompressorUpdater.py', "line": 0, "thread": "ShiCompressorUpdater" }) except ValueError as err: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split( exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent( "Error", 'Error in ShiCompressorUpdater reading values: "%s"' % err, { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "ShiCompressorUpdater" }) raise err else: Logging.logEvent( "Debug", "Status Update", { "message": "Test run of Shi Compressor loop", "level": 4 }) if time.time() < next_compressor_read_time: time.sleep(next_compressor_read_time - time.time()) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent( "Error", "Shi Compressor Interface Thread", { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "ShiCompressorUpdater" }) Logging.logEvent( "Debug", "Status Update", { "message": "There was a {} error in ShiCompressorUpdater. File: {}:{}\n{}" .format(exc_type, fname, exc_tb.tb_lineno, e), "level": 2 }) if Logging.debug: raise e self.compressor.close_port() time.sleep(4)
def run(self): ''' ''' # used for testing first = True while True: # While true to restart the thread if it errors out try: # Thread "Start up" stuff goes here Logging.logEvent( "Debug", "Status Update", { "message": "Starting Pfeiffer Guage Updater Thread", "level": 2 }) if os.name == "posix": userName = os.environ['LOGNAME'] else: userName = "******" # userName = '******' if "root" in userName: self.read_all_params() next_pressure_read_time = time.time() next_param_read_time = time.time() while True: next_pressure_read_time += self.pressure_read_peroid if "root" in userName: try: self.gauges.update([{ 'addr': 1, 'Pressure': self.Pgauge.GetPressure(1) }, { 'addr': 2, 'Pressure': self.Pgauge.GetPressure(2) }, { 'addr': 3, 'Pressure': self.Pgauge.GetPressure(3) }]) Logging.logEvent( "Debug", "Status Update", { "message": "Reading and writing with PfeifferGaugeUpdater.\n" "Cryopump: {:f}; Chamber: {:f}; RoughPump: {:f}\n" "".format( self.gauges.get_cryopump_pressure(), self.gauges.get_chamber_pressure(), self.gauges.get_roughpump_pressure()), "level": 4 }) if time.time() > next_param_read_time: self.gauges.update([{ 'addr': 1, 'error': self.Pgauge.GetError(1), 'cc on': self.Pgauge.GetCCstate(1) }, { 'addr': 2, 'error': self.Pgauge.GetError(2), 'cc on': self.Pgauge.GetCCstate(2) }, { 'addr': 3, 'error': self.Pgauge.GetError(3) }]) if __name__ != '__main__': if ProfileInstance.getInstance( ).recordData: self.logPressureData() next_param_read_time += self.param_period except ValueError as err: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split( exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent( "Error", 'Error in PfeifferGaugeUpdater reading values: "%s"' % err, { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "PfeifferGaugeUpdater" }) else: Logging.logEvent( "Debug", "Status Update", { "message": "Test run of Pfeiffer Guages loop", "level": 4 }) if first: # TODO: Test the system at differnt starting pressures, it could restart at any point # What happens when pressure in roughing is more than cryo? self.gauges.update([{ 'addr': 1, 'Pressure': 1000 }, { 'addr': 2, 'Pressure': 0.001 }, { 'addr': 3, 'Pressure': 999 }]) first = False goingUp = False else: if True or self.gauges.get_chamber_pressure( ) > 0.0000001 and not goingUp: self.gauges.update([{ 'addr': 1, 'Pressure': self.gauges.get_cryopump_pressure() / 2.5 }, { 'addr': 2, 'Pressure': self.gauges.get_chamber_pressure() / 5 }, { 'addr': 3, 'Pressure': self.gauges.get_roughpump_pressure() / 3 }]) else: goingUp = True self.gauges.update([{ 'addr': 1, 'Pressure': self.gauges.get_cryopump_pressure() * 2.5 }, { 'addr': 2, 'Pressure': self.gauges.get_chamber_pressure() * 5 }, { 'addr': 3, 'Pressure': self.gauges.get_roughpump_pressure() * 3 }]) # Just to see the screen for longer time.sleep(5) Logging.logEvent( "Debug", "Status Update", { "message": "Current Pressure in Chamber is {}".format( self.gauges.get_chamber_pressure()), "level": 4 }) currentTime = time.time() if currentTime < next_pressure_read_time: time.sleep(next_pressure_read_time - currentTime) except Exception as e: # FileCreation.pushFile("Error",self.zoneUUID,'{"errorMessage":"%s"}'%(e)) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent( "Error", "Pfeiffer Interface Thread", { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "PfeifferGaugeUpdater" }) Logging.logEvent( "Debug", "Status Update", { "message": "There was a {} error in PfeifferGaugeUpdater. File: {}:{}\n{}" .format(exc_type, fname, exc_tb.tb_lineno, e), "level": 1 }) if Logging.debug: raise e time.sleep(4)
def Process_Commands(self, cmd): Logging.debugPrint(2,"Tdk command: {}".format(cmd)) if 'Set Platen Left' == cmd[0]: if cmd[2] == 'V': self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_left_addr(), self.pwr_supply.set_pv, cmd[1]) if cmd[2] == 'C': self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_left_addr(), self.pwr_supply.set_pc, cmd[1]) elif 'Set Platen Right' == cmd[0]: if cmd[2] == 'V': self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_right_addr(), self.pwr_supply.set_pv, cmd[1]) if cmd[2] == 'C': self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_right_addr(), self.pwr_supply.set_pc, cmd[1]) elif 'Set Shroud Left' == cmd[0]: if cmd[2] == 'V': self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_left_addr(), self.pwr_supply.set_pv, cmd[1]) if cmd[2] == 'C': self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_left_addr(), self.pwr_supply.set_pc, cmd[1]) elif 'Set Shroud Right' == cmd[0]: if cmd[2] == 'V': self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_right_addr(), self.pwr_supply.set_pv, cmd[1]) if cmd[2] == 'C': self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_right_addr(), self.pwr_supply.set_pc, cmd[1]) elif 'Enable All Output' == cmd[0]: # Duty cycle is a value from 0-1 if self.hw.OperationalVacuum: self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_left_addr(), self.pwr_supply.set_out, True) self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_right_addr(), self.pwr_supply.set_out, True) self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_left_addr(), self.pwr_supply.set_out, True) self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_right_addr(), self.pwr_supply.set_out, True) else: Logging.logEvent("Debug", "Status Update", { "message": 'TDK Lambda Powers Supply Cant be turned on when not in Operational vacuum', "level": 3}) elif 'Enable Platen Output' == cmd[0]: # Duty cycle is a value from 0-1 if self.hw.OperationalVacuum: self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_left_addr(), self.pwr_supply.set_out, True) self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_right_addr(), self.pwr_supply.set_out, True) else: Logging.logEvent("Debug", "Status Update", { "message": 'TDK Lambda Powers Supply Cant be turned on when not in Operational vacuum', "level": 3}) elif 'Enable Shroud Output' == cmd[0]: # Duty cycle is a value from 0-1 if self.hw.OperationalVacuum: self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_left_addr(), self.pwr_supply.set_out, True) self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_right_addr(), self.pwr_supply.set_out, True) else: Logging.logEvent("Debug", "Status Update", { "message": 'TDK Lambda Powers Supply Cant be turned on when not in Operational vacuum', "level": 3}) elif 'Setup Platen' == cmd[0]: # Duty cycle is a value from 0-1 Logging.logEvent("Debug", "Status Update", { "message": 'Setting up Platen Heaters', "level": 2}) if self.hw.OperationalVacuum: for addr in [self.hw.TdkLambda_PS.get_platen_left_addr(), self.hw.TdkLambda_PS.get_platen_right_addr()]: self.pwr_supply.set_addr(addr) self.pwr_supply.set_pc(0.0) self.pwr_supply.set_pv(0.0) self.pwr_supply.set_out_on() else: Logging.logEvent("Debug", "Status Update", { "message": 'TDK Lambda Powers Supply Cant be turned on when not in Operational vacuum', "level": 3}) elif 'Setup Shroud' == cmd[0]: # Duty cycle is a value from 0-1 Logging.logEvent("Debug", "Status Update", { "message": 'Setting up Shroud Heaters', "level": 2}) if self.hw.OperationalVacuum: for addr in [self.hw.TdkLambda_PS.get_shroud_left_addr(), self.hw.TdkLambda_PS.get_shroud_right_addr()]: self.pwr_supply.set_addr(addr) self.pwr_supply.set_pc(0.0) self.pwr_supply.set_pv(0.0) self.pwr_supply.set_out_on() else: Logging.logEvent("Debug", "Status Update", { "message": 'TDK Lambda Powers Supply Cant be turned on when not in Operational vacuum', "level": 3}) elif 'Disable All Output' == cmd[0]: # Duty cycle is a value from 0-1 self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_left_addr(), self.pwr_supply.set_out, False) self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_right_addr(), self.pwr_supply.set_out, False) self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_left_addr(), self.pwr_supply.set_out, False) self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_right_addr(), self.pwr_supply.set_out, False) elif 'Disable Platen Output' == cmd[0]: # Duty cycle is a value from 0-1 self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_left_addr(), self.pwr_supply.set_out, False) self.run_set_cmd(self.hw.TdkLambda_PS.get_platen_right_addr(), self.pwr_supply.set_out, False) elif 'Disable Shroud Output' == cmd[0]: # Duty cycle is a value from 0-1 self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_left_addr(), self.pwr_supply.set_out, False) self.run_set_cmd(self.hw.TdkLambda_PS.get_shroud_right_addr(), self.pwr_supply.set_out, False) elif 'Platen Duty Cycle' == cmd[0]: # Duty cycle is a value from 0-1 if self.hw.OperationalVacuum: if cmd[1] > 1: dutycycle = 1.0 elif cmd[1] < 0: dutycycle = 0.0 else: dutycycle = float(cmd[1]) current = 5.5 * dutycycle voltage = current * 80.0 for addr in [self.hw.TdkLambda_PS.get_platen_left_addr(), self.hw.TdkLambda_PS.get_platen_right_addr()]: self.pwr_supply.set_addr(addr) self.pwr_supply.set_pc(current) self.pwr_supply.set_pv(voltage) else: Logging.logEvent("Debug", "Status Update", { "message": 'TDK Lambda Powers Supply Cant be turned on when not in Operational vacuum', "level": 3}) elif 'Shroud Duty Cycle' == cmd[0]: # Duty cycle is a value from 0-1 if self.hw.OperationalVacuum: if cmd[1] > 1: dutycycle = 1.0 elif cmd[1] < 0: dutycycle = 0.0 else: dutycycle = float(cmd[1]) current = 3 * dutycycle voltage = current * 80.0 for addr in [self.hw.TdkLambda_PS.get_shroud_left_addr(), self.hw.TdkLambda_PS.get_shroud_right_addr()]: self.pwr_supply.set_addr(addr) self.pwr_supply.set_pc(current) self.pwr_supply.set_pv(voltage) else: Logging.logEvent("Debug", "Status Update", { "message": 'TDK Lambda Powers Supply Cant be turned on when not in Operational vacuum', "level": 3}) else: Logging.logEvent("Error", 'Unknown TDK Lambda command: "%s"' % cmd[0], {"type": 'Unknown TdkLambda_Cmd', "filename": 'ThreadControls/TdkLambdaUpdater.py', "line": 93, "thread": "TdkLambdaUpdater" })
class ReuseAddrTCPServer(socketserver.TCPServer): allow_reuse_address = True if __name__ == '__main__': # adding debug info if(len(sys.argv)>1): for arg in sys.argv: if arg.startswith("-v"): Logging.verbos = arg.count("v") if(len(sys.argv)>2): for arg in sys.argv: if "--debug" in arg: Logging.debug = True Logging.logEvent("Debug","Status Update", {"message": "Verbos on: Level {}".format(Logging.verbos), "level":1}) PORT = 8000 Logging.logEvent("Debug","Status Update", {"message": "Starting initializing threads and drivers", "level":1}) hardwareStatusInstance = HardwareStatusInstance.getInstance() profileInstance = ProfileInstance.getInstance() threadInstance = ThreadCollectionInstance.getInstance() Logging.logEvent("Event","System", {"message": "Server is fully booted", "ProfileInstance": profileInstance.getInstance()}) Logging.logEvent("Debug","Status Update",
def run(self): ''' ''' if os.name == 'posix': userName = os.environ['LOGNAME'] else: userName = "******" while True: # While true to restart the thread if it errors out try: # Thread "Start up" stuff goes here Logging.logEvent("Debug", "Status Update", {"message": "TDK Lambda Genesys Control Stub Thread", "level": 2}) if "root" in userName: self.pwr_supply.open_port() update_power_supplies = [{'addr': self.hw.TdkLambda_PS.get_platen_left_addr()}, {'addr': self.hw.TdkLambda_PS.get_platen_right_addr()}, {'addr': self.hw.TdkLambda_PS.get_shroud_left_addr()}, {'addr': self.hw.TdkLambda_PS.get_shroud_right_addr()}] for ps in update_power_supplies: self.pwr_supply.set_addr(ps['addr']) ps.update(self.pwr_supply.get_out()) if not self.hw.OperationalVacuum: self.pwr_supply.set_out_off() ps.update(self.pwr_supply.get_idn()) ps.update(self.pwr_supply.get_rev()) ps.update(self.pwr_supply.get_sn()) ps.update(self.pwr_supply.get_date()) ps.update(self.pwr_supply.get_ast()) ps.update(self.pwr_supply.get_out()) ps.update(self.pwr_supply.get_mode()) self.hw.TdkLambda_PS.update(update_power_supplies) next_status_read_time = time.time() while True: next_status_read_time += self.ps_read_peroid if "root" in userName: try: # TODO: Not sure on the location of flush port self.pwr_supply.flush_port() update_power_supplies = [{'addr': self.hw.TdkLambda_PS.get_platen_left_addr()}, {'addr': self.hw.TdkLambda_PS.get_platen_right_addr()}, {'addr': self.hw.TdkLambda_PS.get_shroud_left_addr()}, {'addr': self.hw.TdkLambda_PS.get_shroud_right_addr()}] for ps in update_power_supplies: self.pwr_supply.set_addr(ps['addr']) if not self.hw.OperationalVacuum and self.hw.TdkLambda_PS.get_val(ps['addr'], 'output enable'): debugPrint(2,"TDK, either not in vacuum, or turned off") self.pwr_supply.set_out_off() ps.update(self.pwr_supply.get_status()) ps.update(self.pwr_supply.get_out()) ps.update(self.pwr_supply.get_mode()) self.hw.TdkLambda_PS.update(update_power_supplies) while len(self.hw.TdkLambda_Cmds): self.Process_Commands(self.hw.TdkLambda_Cmds.pop(0)) except ValueError as err: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent("Error", 'Error in TdkLambdaUpdater reading values: "%s"' % err, {"type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "TdkLambdaUpdater" }) if Logging.debug: raise err else: Logging.logEvent("Debug", "Status Update", {"message": "Test run of TDK Lambda Power Supplies loop", "level": 4}) # Just to see the screen for longer time.sleep(5) if time.time() < next_status_read_time: time.sleep(next_status_read_time - time.time()) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent("Error", "TDK Lambda Power Supplies Interface Thread", {"type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "TdkLambdaUpdater", "ThreadCollection":self.parent, "item":"Tdk-Lambda Heater", "itemID":-1, "details":"A TDK-Lambda is probably powered off" }) Logging.logEvent("Debug", "Status Update", {"message": "There was a {} error in TdkLambdaUpdater. File: {}:{}\n{}".format( exc_type, fname, exc_tb.tb_lineno, e), "level": 1}) if Logging.debug: raise e self.pwr_supply.close_port() time.sleep(4)
def createExpectedValues(self, setPoints, startTime=None): ''' This is a helper function that given a list of setpoints containing a GoalTemp, RampTime and SoakTime. It will generate a list time values and matching temputure values ''' Logging.logEvent( "Debug", "Status Update", { "message": "DCCS: Creating Expected temperature values: {}".format( self.name), "level": 2 }) intervalTime = self.parent.updatePeriod # if given a startTime, use that, otherwise, use current Logging.debugPrint( 1, "DCCS: thermalStartTime: {}".format( self.parent.zoneProfiles.thermalStartTime)) if startTime: Logging.debugPrint( 3, "DCCS: Starttime is: {}\t current: {}".format( startTime, time.time())) if "datetime.datetime" in str(type(startTime)): startTime = time.mktime(startTime.timetuple()) currentTime = int(startTime) else: currentTime = int(time.time()) sql = "SELECT zone{}_Temp FROM tvac.Profile_Instance where endTime is null;".format( self.zoneProfile.zone) mysql = MySQlConnect() try: mysql.cur.execute(sql) mysql.conn.commit() except Exception as e: Logging.debugPrint(3, "sql: {}".format(sql)) Logging.debugPrint( 1, "Error in loadThermoProfiles, zoneCollection: {}".format( str(e))) if Logging.debug: raise e result = mysql.cur.fetchone() print("result: {}".format(result)) currentTemp = result["zone{}_Temp".format(self.zoneProfile.zone)] currentTemp = float(currentTemp) print("currentTemp: {}".format(currentTemp)) expected_temp_values = [] expected_time_values = [] self.parent.setpoint_start_time = [] for setPoint in setPoints: # get values out from setpoint goalTemp = setPoint.tempGoal rampTime = setPoint.ramp soakTime = setPoint.soakduration currentTime2 = time.time() # skip ramp section if rampTime == 0 if rampTime: TempDelta = goalTemp - currentTemp numberOfJumps = rampTime / intervalTime intervalTemp = TempDelta / numberOfJumps rampEndTime = currentTime + rampTime # Debug prints debugStatus = { "goal temperature": goalTemp, "Time at Start of Setpoint": currentTime, "Ramp Duration": rampTime, "Delta temp per Update": intervalTemp, "Update Time": self.parent.updatePeriod, "TempDelta Total": TempDelta, } Logging.logEvent( "Debug", "Data Dump", { "message": "DCCS: Setpoint {}: Ramp Status".format( setPoint.thermalsetpoint), "level": 3, "dict": debugStatus }) # setting all values all for ramp notUsed = 0 for i, tempSetPoint in enumerate( range(currentTime, rampEndTime, intervalTime)): if tempSetPoint > currentTime2: x = tempSetPoint y = currentTemp + ((i) * intervalTemp) expected_time_values.append(tempSetPoint) expected_temp_values.append(y) else: notUsed += 1 else: rampEndTime = currentTime self.parent.setpoint_start_time.append([currentTime, 0]) # Debug prints debugStatus = { "Soak Duration": soakTime, "goal temperature": goalTemp, } Logging.logEvent( "Debug", "Data Dump", { "message": "DCCS: Setpoint {}: Soak Status".format( setPoint.thermalsetpoint), "level": 3, "dict": debugStatus }) #Setting all soak values self.parent.setpoint_start_time[-1][1] = rampEndTime for tempSetPoint in range(rampEndTime, rampEndTime + soakTime, intervalTime): if tempSetPoint > currentTime2: x = tempSetPoint y = goalTemp expected_time_values.append(tempSetPoint) expected_temp_values.append(y) currentTime = rampEndTime + soakTime currentTemp = goalTemp # end of for loop, end generating outputs # print("Logging all data") # Logging.logEvent("Event","Expected Temp Update", # {"expected_temp_values": expected_temp_values, # "expected_time_values": expected_time_values, # "zone" : self.args[0], # "profileUUID" : self.zoneProfile.profileUUID, # "ProfileInstance" : ProfileInstance.getInstance() # }) return expected_temp_values, expected_time_values
def do_GET(self): """Respond to a GET request.""" Logging.logEvent("Debug", "Status Update", { "message": "Received GET Request", "level": 1 }) try: path = self.path Logging.logEvent("Debug", "Status Update", { "message": "GET Request Path: {}".format(path), "level": 2 }) # Based on the path we are given, do different functions control = GetControl() result = { '/runProfile': control.runProfile, '/checkZoneStatus': control.checkTreadStatus, '/getAllThermoCoupleData': control.getAllThermoCoupleData, '/getAllZoneData': control.getAllZoneData, '/getShiTemps': control.getShiTemps, '/getCryoPump_Status': control.getCryoPump_Status, '/getCryoPump_Params': control.getCryoPump_Params, '/getCryoPump_plots': control.getCryoPump_plots, '/getPC104_Digital': control.getPC104_Digital, '/getPC104_Switches': control.getPC104_Switches, '/getPC104_Analog': control.getPC104_Analog, '/getPressureGauges': control.getPressureGauges, '/getZoneTemps': control.getZoneTemps, '/getLastErr': control.getLastError, '/putUnderVacuum': control.putUnderVacuum, '/VacuumNotNeeded': control.VacuumNotNeeded, '/StopCryoPumpingChamber': control.StopCryoPumpingChamber, '/StopCryoPump': control.StopCryoPump, '/StopRoughingPump': control.StopRoughingPump, '/getEventList': control.getEventList, '/hardStop': control.hardStop, '/hold': control.holdAllZones, '/pause': control.pauseAllZones, '/resume': control.resumeAllZones, '/unHold': control.unHoldAllZones, '/getVacuumState': control.getVacuumState, '/doRegen': control.doRegen, '/abortRegen': control.abortRegen, '/getTvacStatus': control.getTvacStatus, '/StoprecordData': control.StoprecordData, '/recordData': control.recordData, }[path]() Logging.logEvent("Debug", "Status Update", { "message": "Sending GET Results", "level": 1 }) Logging.logEvent( "Debug", "Status Update", { "message": "GET Results: {}".format(str(result).encode()), "level": 5 }) # Out the results back to the server self.setHeader() self.wfile.write(str(result).encode()) except Exception as e: # print("There has been an error"). # FileCreation.pushFile("Error","Get",'{"errorMessage":"%s"}\n'%(e)) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Logging.logEvent( "Error", "GET Handler", { "type": exc_type, "filename": fname, "line": exc_tb.tb_lineno, "thread": "Verb Handler", "ThreadCollection": ThreadCollectionInstance.getInstance().threadCollection, "item": "Server", "itemID": -1, "details": "PATH: {} is not recognized".format(path) }) Logging.logEvent( "Debug", "Status Update", { "message": "There was a {} error in Server (GET Handler). File: {}:{}" .format(exc_type, fname, exc_tb.tb_lineno), "level": 1 }) self.setHeader() output = '{"Error":"%s"}\n' % (e) self.wfile.write(output.encode()) raise e