def action_setmaintenancemode(self, model, tango_dev=None, data_input=None): """This command triggers the Dish to transition to the MAINTENANCE Dish Element Mode, and returns to the caller. To go into a state that is safe to approach the Dish by a maintainer, and to enable the Engineering interface to allow direct access to low level control and monitoring by engineers and maintainers. This mode will also enable engineers and maintainers to upgrade SW and FW. Dish also enters this mode when an emergency stop button is pressed. data_input: None """ _allowed_modes = ('STANDBY-LP', 'STANDBY-FP') dish_mode_quant = model.sim_quantities['dishMode'] current_mode_enum_val = dish_mode_quant.last_val current_mode_str_val = ( dish_mode_quant.meta['enum_labels'][int(current_mode_enum_val)]) if current_mode_str_val in _allowed_modes: set_mode = dish_mode_quant.meta['enum_labels'].index('MAINTENANCE') model.sim_quantities['dishMode'].set_val(set_mode, model.time_func()) MODULE_LOGGER.info( "Dish transition to the OPERATE Dish Element mode.") else: Except.throw_exception( "DISH Command Failed", "DISH is not in {} mode.".format(_allowed_modes), "SetMaintenanceMode()", ErrSeverity.WARN)
def read_Data(self, attr): desc = "Data attribute is not foreseen for reading. It is used only "\ "as the communication channel for the continuous acquisitions." Except.throw_exception("UnsupportedFeature", desc, "PoolExpChannelDevice.read_Data", ErrSeverity.WARN)
def pre_update(self, sim_model, sim_time, dt): MODULE_LOGGER.info("***Pre-updating from the override class***") pointing_state_quant = sim_model.sim_quantities['pointingState'] current_pnt_state_enum_val = pointing_state_quant.last_val current_pnt_state_str_val = (pointing_state_quant.meta['enum_labels'][ int(current_pnt_state_enum_val)]) if current_pnt_state_str_val == 'READY': MODULE_LOGGER.info("Skipping quantity updates. Dish quantity state" " already in READY mode.") return azim_slew_rate = self.AZIM_DRIVE_MAX_RATE elev_slew_rate = self.ELEV_DRIVE_MAX_RATE azim_max_slew = azim_slew_rate * dt elev_max_slew = elev_slew_rate * dt try: achieved_azim = sim_model.sim_quantities[ 'achievedAzimuth'].last_val achieved_elev = sim_model.sim_quantities[ 'achievedElevation'].last_val desired_azim = sim_model.sim_quantities['desiredAzimuth'].last_val desired_elev = sim_model.sim_quantities[ 'desiredElevation'].last_val except KeyError: Except.throw_exception( "Dish pre-update method failed", "One of these quantities (achievedAzimuth, achievedElevation" ", desiredAzimuth, desiredElevation) is not in the Dish model.", "update()", ErrSeverity.WARN) current_delta_azim = abs(achieved_azim - desired_azim) current_delta_elev = abs(achieved_elev - desired_elev) move_delta_azim = min(azim_max_slew, current_delta_azim) move_delta_elev = min(elev_max_slew, current_delta_elev) new_position_azim = ( achieved_azim + cmp(desired_azim, achieved_azim) * move_delta_azim) sim_model.sim_quantities['achievedAzimuth'].set_val( new_position_azim, sim_time) new_position_elev = ( achieved_elev + cmp(desired_elev, achieved_elev) * move_delta_elev) sim_model.sim_quantities['achievedElevation'].set_val( new_position_elev, sim_time) sim_model.sim_quantities['achievedPointing'].set_val([ sim_model.sim_quantities['achievedAzimuth'].last_val, sim_model.sim_quantities['achievedElevation'].last_val ], sim_time) if (self._almost_equal( sim_model.sim_quantities['achievedAzimuth'].last_val, sim_model.sim_quantities['desiredAzimuth'].last_val) and self._almost_equal( sim_model.sim_quantities['achievedElevation'].last_val, sim_model.sim_quantities['desiredElevation'].last_val)): pointing_state_quant.set_val( pointing_state_quant.meta['enum_labels'].index("READY"), sim_time)
def ReloadMacro(self, macro_names): """ReloadMacro(list<string> macro_names):""" try: for macro_name in macro_names: self.macro_server.reload_macro(macro_name) except MacroServerException, mse: Except.throw_exception(mse.type, mse.msg, 'ReloadMacro')
def __exit__(self,etype,e,tb): #Type of exception, exception instance, traceback if not e and not etype: pass else: stack = traceback.format_tb(tb) exstring = '\n'.join(stack) if self.verbose: print '-'*80 self.logger.warning('%s Exception Catched, Tracebacks (most recent call last): %s;\n%s'%(etype.__name__,str(e),exstring)) sys.stdout.flush(); sys.stderr.flush() print '-'*80 if self.postmethod: self.postmethod(exstring) if etype is DevFailed: #for k,v in e[0].items():print k,':',v if True: #not self.rethrow: #re_throw doesn't work! #The exception is throw just as it was err = e[0] Except.throw_exception(err.reason,err.desc,err.origin) #Except.throw_exception(e.args[0]['reason'],e.args[0]['desc'],e.args[0]['origin']) else: #It doesn't work!!! #ex=DevFailed(e[0]['reason'],e[0]['desc'],e[0]['origin']) #Except.re_throw_exception(ex, '','','') pass else: #elif etype is Exception: exstring = self.origin or len(exstring)<125 and exstring or stack[-1] Except.throw_exception(etype.__name__,str(e),exstring)
def action_setstandbylpmode(self, model, tango_dev=None, data_input=None): """This command triggers the Dish to transition to the STANDBY-LP Dish Element Mode, and returns to the caller. Standby_LP is the default mode when the Dish is configured for low power consumption, and is the mode wherein Dish ends after a start up procedure. data_input: None """ _allowed_modes = ('OFF', 'STARTUP', 'SHUTDOWN', 'STANDBY-LP', 'STANDBY-FP', 'MAINTENANCE', 'STOW', 'CONFIG', 'OPERATE') dish_mode_quant = model.sim_quantities['dishMode'] current_mode_enum_val = dish_mode_quant.last_val current_mode_str_val = ( dish_mode_quant.meta['enum_labels'][int(current_mode_enum_val)]) if current_mode_str_val in _allowed_modes: set_mode = dish_mode_quant.meta['enum_labels'].index('STANDBY-LP') model.sim_quantities['dishMode'].set_val(set_mode, model.time_func()) MODULE_LOGGER.info( "Dish transition to the STANDBY-LP Dish Element Mode.") else: Except.throw_exception( "DISH Command Failed", "DISH is not in {} mode.".format(_allowed_modes), "SetStandbyLPMode()", ErrSeverity.WARN)
def wrapper(*args,**kwargs): try: #logger.debug('Trying %s'%fun.__name__) result = fun(*args,**kwargs) #sys.stdout.write('fun DONE!!!\n') return result except DevFailed, e: exstring=getPreviousExceptions() if verbose: print '-'*80 #exstring = traceback.format_exc() logger.warning('DevFailed Exception Catched: \n%s'%exstring) try: if showArgs: logger.info('%s(*args=%s, **kwargs=%s)'%(fun.__name__,args,kwargs)) except:pass sys.stdout.flush(); sys.stderr.flush() print '-'*80 if postmethod: postmethod(exstring) err = e.args[0] if rethrow: #Except.re_throw_exception(e,'','',"%s(...)"%fun.__name__) Except.throw_exception(err.reason, exstring, "%s(...)"%fun.__name__) else: #Except.throw_exception(err.reason,err.desc,err.origin) logger.warning(str((err.reason,err.desc,err.origin))) return default
def _configureband(self, model, timestamp, band_number): _allowed_modes = ('STANDBY-FP', 'OPERATE') dish_mode_quant = model.sim_quantities['dishMode'] current_mode_enum_val = dish_mode_quant.last_val current_mode_str_val = ( dish_mode_quant.meta['enum_labels'][int(current_mode_enum_val)]) if current_mode_str_val in _allowed_modes: set_mode = dish_mode_quant.meta['enum_labels'].index('CONFIG') model.sim_quantities['dishMode'].set_val(set_mode, float(timestamp)) MODULE_LOGGER.info( "Configuring DISH to operate in frequency band {}.".format( band_number)) MODULE_LOGGER.info( "Done configuring DISH to operate in frequency band {}.". format(band_number)) MODULE_LOGGER.info("Dish reverting back to '{}' mode.".format( current_mode_str_val)) model.sim_quantities['dishMode'].set_val(current_mode_enum_val, model.time_func()) else: Except.throw_exception( "DISH Command Failed", "DISH is not in {} mode.".format(_allowed_modes), "ConfigureBand{}()".format(band_number), ErrSeverity.WARN)
def action_lowpower(self, model, tango_dev=None, data_input=None): """This command triggers the Dish to transition to the LOW power state. All subsystems go into a low power state to power only the essential equipment. Specifically the Helium compressor will be set to a low power consumption, and the drives will be disabled. When issued a STOW command while in LOW power, the DS controller should be able to turn the drives on, stow the dish and turn the drives off again. The purpose of this mode is to enable the observatory to perform power management (load curtailment), and also to conserve energy for non-operating dishes. data_input: None """ _allowed_modes = ('STOW', 'MAINTENANCE') dish_mode_quant = model.sim_quantities['dishMode'] current_mode_enum_val = dish_mode_quant.last_val current_mode_str_val = ( dish_mode_quant.meta['enum_labels'][int(current_mode_enum_val)]) if current_mode_str_val in _allowed_modes: power_state_quant = model.sim_quantities['powerState'] set_mode = power_state_quant.meta['enum_labels'].index('LOW') power_state_quant.set_val(set_mode, model.time_func()) MODULE_LOGGER.info("Dish transitioning to LOW power state.") else: Except.throw_exception( "DISH Command Failed", "DISH is not in {} mode.".format(_allowed_modes), "LowPower()", ErrSeverity.WARN)
def read_ValueRefBuffer(self, _): desc = ("ValueRefBuffer attribute is not foreseen for reading. " "It is used only as the communication channel for the " "continuous acquisitions.") Except.throw_exception("UnsupportedFeature", desc, "PoolExpChannelDevice.read_ValueRefBuffer", ErrSeverity.WARN)
def ReloadMacro(self, macro_names): """ReloadMacro(list<string> macro_names):""" try: for macro_name in macro_names: self.macro_server.reload_macro(macro_name) except MacroServerException, mse: Except.throw_exception(mse.type, mse.msg, "ReloadMacro")
def ReloadMacroLib(self, lib_names): """ReloadMacroLib(sequence<string> lib_names): """ try: for lib_name in lib_names: self.macro_server.reload_macro_lib(lib_name) except MacroServerException, mse: Except.throw_exception(mse.type, mse.msg, "ReloadMacroLib")
def ReloadMacroLib(self, lib_names): """ReloadMacroLib(sequence<string> lib_names): """ try: for lib_name in lib_names: self.macro_server.reload_macro_lib(lib_name) except MacroServerException, mse: Except.throw_exception(mse.type, mse.msg, 'ReloadMacroLib')
def ExceptionWrapper(fun,logger=exLogger,postmethod=None, showArgs=False,verbose=False,rethrow=False,default=None): ''' Implementation of the popular Catched() decorator: * it will execute your method within a a try/except * it will print the traceback * if :rethrow: is False it will return :default: in case of exception Example: @ExceptionWrapper def funny(): print 'what?' end funny() ''' def wrapper(*args,**kwargs): try: #logger.debug('Trying %s'%fun.__name__) result = fun(*args,**kwargs) #sys.stdout.write('fun DONE!!!\n') return result except DevFailed, e: exstring=getPreviousExceptions() if verbose: print '-'*80 #exstring = traceback.format_exc() logger.warning('DevFailed Exception Catched: \n%s'%exstring) try: if showArgs: logger.info('%s(*args=%s, **kwargs=%s)'%(fun.__name__,args,kwargs)) except:pass sys.stdout.flush(); sys.stderr.flush() print '-'*80 if postmethod: postmethod(exstring) err = e.args[0] if rethrow: #Except.re_throw_exception(e,'','',"%s(...)"%fun.__name__) Except.throw_exception(err.reason, exstring, "%s(...)"%fun.__name__) else: #Except.throw_exception(err.reason,err.desc,err.origin) logger.warning(str((err.reason,err.desc,err.origin))) return default except Exception,e: #exstring = traceback.format_exc() exstring=getPreviousExceptions() if verbose: print '-'*80 logger.error('Python Exception catched: \n%s'%exstring) try: if showArgs: logger.info('%s(*args=%s, **kwargs=%s)'%(fun.__name__,args,kwargs)) except:pass print '-'*80 if postmethod: postmethod(exstring) if rethrow: Except.throw_exception('Exception',exstring,"%s(...)"%fun.__name__) else: return default
def writeHook(self, value): self.__reviewMonitorDependencies() formula = self._write modified = self._replaceAttrs4Values(formula, self._writeAttrs) solution = self._solve(value, modified) self.debug("write with VALUE=%s, %r means %s" % (value, formula, solution)) if self.write_not_allowed is not None: if value != solution: PyTangoExcept.throw_exception("Write %s not allowed" % value, self.write_not_allowed, self.owner.name, ErrSeverity.WARN) self._lastWrite = solution return solution
def throw_sardana_exception(exc): """Throws an exception as a tango exception""" if isinstance(exc, SardanaException): if exc.exc_info and not None in exc.exc_info: Except.throw_python_exception(*exc.exc_info) else: tb = "<Unknown>" if exc.traceback is not None: tb = str(exc.traceback) Except.throw_exception(exc.type, exc.msg, tb) elif hasattr(exc, 'exc_info'): Except.throw_python_exception(*exc.exc_info) else: raise exc
def wrapper(*args, **kwargs): try: #logger.trace('Trying %s'%fun.__name__) result = fun(*args, **kwargs) #logger.trace('%s Succeed!\n'%fun) return result except Exception, e: etype = type(e).__name__ exstring = getPreviousExceptions() elog, eargs = exstring, ('Exception', exstring, "%s(...)" % fun.__name__) if isinstance(e, DevFailed): try: err = e.args[0] eargs = (err.reason, exstring, "%s(...)" % fun.__name__) elog = str((err.reason, err.desc, err.origin)) except: pass if verbose: logger.warning('<' * 80) logger.error('%s Exception catched: \n%s' % (etype, elog)) try: if showArgs: logger.info('%s(*args=%s, **kwargs=%s)' % (fun.__name__, args, kwargs)) except: pass if postmethod: ExceptionWrapper(postmethod)(exstring) if rethrow: #Except.re_throw_exception(e,'','',"%s(...)"%fun.__name__) logger.warning('%s Rethrow!' % etype) Except.throw_exception(*eargs) else: if isinstance( e, DevFailed) and elog and not verbose and not postmethod: logger.warning(elog) return default
def _validate_input_sizes(self, command_name, argin): """Check the validity of the input parameters passed on to the command specified by the command_name parameter. Parameters ---------- command_name: str The name of the command which is to be executed. argin: PyTango.DevVarLongStringArray A tuple of two lists representing [number of instances][capability types] Raises ------ PyTango.DevFailed: If the two lists are not equal in length. """ capabilities_instances, capability_types = argin if len(capabilities_instances) != len(capability_types): Except.throw_exception("Command failed!", "Argin value lists size mismatch.", command_name, ErrSeverity.ERR)
def _validate_capability_types(self, command_name, capability_types): """Check the validity of the input parameter passed on to the command specified by the command_name parameter. Parameters ---------- command_name: str The name of the command which is to be executed. capability_types: list A list strings representing capability types. Raises ------ PyTango.DevFailed: If any of the capabilities requested are not valid. """ invalid_capabilities = list( set(capability_types) - set(self._configured_capabilities)) if invalid_capabilities: Except.throw_exception( "Command failed!", "Invalid capability types requested {}".format( invalid_capabilities), command_name, ErrSeverity.ERR)
def action_setoperatemode(self, model, tango_dev=None, data_input=None): """This command triggers the Dish to transition to the OPERATE Dish Element Mode, and returns to the caller. This mode fulfils the main purpose of the Dish, which is to point to designated directions while capturing data and transmitting it to CSP. data_input: None """ _allowed_modes = ('STANDBY-FP') dish_mode_quant = model.sim_quantities['dishMode'] current_mode_enum_val = dish_mode_quant.last_val current_mode_str_val = ( dish_mode_quant.meta['enum_labels'][int(current_mode_enum_val)]) if current_mode_str_val in _allowed_modes: set_mode = dish_mode_quant.meta['enum_labels'].index('OPERATE') model.sim_quantities['dishMode'].set_val(set_mode, model.time_func()) MODULE_LOGGER.info( "Dish transition to the OPERATE Dish Element Mode.") else: Except.throw_exception( "DISH Command Failed", "DISH is not in {} mode.".format(_allowed_modes), "SetOperateMode()", ErrSeverity.WARN)
def action_setstandbyfpmode(self, model, tango_dev=None, data_input=None): """This command triggers the Dish to transition to the STANDBY-FP Dish Element Mode, and returns to the caller. To prepare all subsystems for active observation, once a command is received by TM to go to the FULL_POWER mode. data_input: None """ _allowed_modes = ('STANDBY-LP', 'STOW', 'OPERATE', 'MAINTENANCE') dish_mode_quant = model.sim_quantities['dishMode'] current_mode_enum_val = dish_mode_quant.last_val current_mode_str_val = ( dish_mode_quant.meta['enum_labels'][int(current_mode_enum_val)]) if current_mode_str_val in _allowed_modes: set_mode = dish_mode_quant.meta['enum_labels'].index('STANDBY-FP') model.sim_quantities['dishMode'].set_val(set_mode, model.time_func()) MODULE_LOGGER.info( "Dish transition to the STANDBY-FP Dish Element Mode.") else: Except.throw_exception( "DISH Command Failed", "DISH is not in {} mode.".format(_allowed_modes), "SetStandbyFPMode()", ErrSeverity.WARN)
def action_slew(self, model, tango_dev=None, data_input=None): """The Dish is tracking the commanded pointing positions within the specified TRACK pointing accuracy. data_input: list [Timestamp] [azimuth] [elevation] """ _allowed_modes = ('OPERATE') dish_mode_quant = model.sim_quantities['dishMode'] current_mode_enum_val = dish_mode_quant.last_val current_mode_str_val = ( dish_mode_quant.meta['enum_labels'][int(current_mode_enum_val)]) if current_mode_str_val not in _allowed_modes: Except.throw_exception( "DISH Command Failed", "DISH is not in {} mode.".format(_allowed_modes), "Slew()", ErrSeverity.WARN) try: pointing_state_quant = model.sim_quantities['pointingState'] except KeyError: Except.throw_exception( "DISH Command Failed", "The quantity 'pointingState' is not in the Dish model.", "Slew()", ErrSeverity.WARN) model_time = model.time_func() pointing_state_enum_val = pointing_state_quant.last_val pointing_state_str_val = (pointing_state_quant.meta['enum_labels'][int( pointing_state_enum_val)]) if pointing_state_str_val != 'SLEW': set_mode = pointing_state_quant.meta['enum_labels'].index('SLEW') pointing_state_quant.set_val(set_mode, model_time) else: Except.throw_exception( "DISH Command Failed", "Dish pointing state already in SLEW mode.", "Slew()", ErrSeverity.WARN) model.sim_quantities['desiredAzimuth'].set_val(data_input[1], model_time) model.sim_quantities['desiredElevation'].set_val( data_input[2], model_time) model.sim_quantities['desiredPointing'].set_val( [data_input[1], data_input[2]], model_time)
def action_setstowmode(self, model, tango_dev=None, data_input=None): """This command triggers the Dish to transition to the STOW Dish Element Mode, and returns to the caller. To point the dish in a direction that minimises the wind loads on the structure, for survival in strong wind conditions. The Dish is able to observe in the stow position, for the purpose of transient detection. data_input: None """ _allowed_modes = ('OFF', 'STARTUP', 'SHUTDOWN', 'STANDBY-LP', 'STANDBY-FP', 'MAINTENANCE', 'STOW', 'CONFIG', 'OPERATE') dish_mode_quant = model.sim_quantities['dishMode'] current_mode_enum_val = dish_mode_quant.last_val current_mode_str_val = ( dish_mode_quant.meta['enum_labels'][int(current_mode_enum_val)]) if current_mode_str_val not in _allowed_modes: Except.throw_exception( "DISH Command Failed", "DISH is not in {} mode.".format(_allowed_modes), "SetStowMode()", ErrSeverity.WARN) try: pointing_state_quant = model.sim_quantities['pointingState'] except KeyError: Except.throw_exception( "DISH Command Failed", "The quantity 'pointingState' is not in the Dish model.", "Slew()", ErrSeverity.WARN) model_time = model.time_func() pointing_state_enum_val = pointing_state_quant.last_val pointing_state_str_val = (pointing_state_quant.meta['enum_labels'][int( pointing_state_enum_val)]) if pointing_state_str_val != 'STOW': set_mode = pointing_state_quant.meta['enum_labels'].index('STOW') pointing_state_quant.set_val(set_mode, model_time) else: Except.throw_exception( "DISH Command Failed", "Dish pointing state already in STOW mode.", "SetStowMode()", ErrSeverity.WARN) model.sim_quantities['desiredElevation'].set_val(90, model_time) set_mode = dish_mode_quant.meta['enum_labels'].index('STOW') model.sim_quantities['dishMode'].set_val(set_mode, model_time) MODULE_LOGGER.info("Dish transition to the STOW Dish Element Mode.")
def _is_command_allowed(self, command_name): """Determine whether the command specified by the command_name parameter should be allowed to execute or not. Parameters ---------- command_name: str The name of the command which is to be executed. Returns ------- True or False: boolean A True is returned when the device is in the allowed states and modes to execute the command. Returns False if the command name is not in the list of commands with rules specified for them. Raises ------ PyTango.DevFailed: If the device is not in the allowed states and/modes to execute the command. """ dp = DeviceProxy(self.get_name()) obstate_labels = list(dp.attribute_query('obsState').enum_labels) obs_idle = obstate_labels.index('IDLE') obs_ready = obstate_labels.index('READY') admin_labels = list(dp.attribute_query('adminMode').enum_labels) admin_online = admin_labels.index('ON-LINE') admin_maintenance = admin_labels.index('MAINTENANCE') admin_offline = admin_labels.index('OFF-LINE') admin_not_fitted = admin_labels.index('NOT-FITTED') current_admin_mode = self.read_adminMode() if command_name in ["ReleaseResources", "AssignResources"]: if current_admin_mode in [admin_offline, admin_not_fitted]: Except.throw_exception("Command failed!", "Subarray adminMode is" " 'OFF-LINE' or 'NOT-FITTED'.", command_name, ErrSeverity.ERR) if self.read_obsState() == obs_idle: if current_admin_mode in [admin_online, admin_maintenance]: return True else: Except.throw_exception("Command failed!", "Subarray adminMode not" "'ON-LINE' or not in 'MAINTENANCE'.", command_name, ErrSeverity.ERR) else: Except.throw_exception("Command failed!", "Subarray obsState not 'IDLE'.", command_name, ErrSeverity.ERR) elif command_name in ['ConfigureCapability', 'DeconfigureCapability', 'DeconfigureAllCapabilities']: if self.get_state() == DevState.ON and self.read_adminMode() == admin_online: if self.read_obsState() in [obs_idle, obs_ready]: return True else: Except.throw_exception( "Command failed!", "Subarray obsState not 'IDLE' or 'READY'.", command_name, ErrSeverity.ERR) else: Except.throw_exception( "Command failed!", "Subarray State not 'ON' and/or adminMode not" " 'ON-LINE'.", command_name, ErrSeverity.ERR) return False