예제 #1
0
    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)
예제 #2
0
    def run(self, motor):

        show_ctrlaxis = self.getViewOption(ViewOption.ShowCtrlAxis)
        pos_format = self.getViewOption(ViewOption.PosFormat)

        name = motor.getName()
        motor_device = PyTango.DeviceProxy(name)
        try:
            high = motor_device.UnitLimitMax
            low = motor_device.UnitLimitMin
            pos = motor_device.Position
            self.output("")
            if show_ctrlaxis:
                axis_nb = getattr(motor, "axis")
                ctrl_name = self.getController(motor.controller).name
                ca_name = " (" + ctrl_name + "." + str(axis_nb) + ")"
                name = name + ca_name
            self.output("    %s     " % name)
            self.output("")
            if pos_format != -1:
                fmt = '%c.%df' % ('%', pos_format)
                lowstr = fmt % low
                self.output("UnitLimitMin: %s " % lowstr)
                posstr = fmt % pos
                self.output("Current     : %s " % posstr)
                highstr = fmt % high
                self.output("UnitLimitMax: %s " % highstr)
            else:
                self.output("UnitLimitMin: %f " % low)
                self.output("Current     : %f " % pos)
                self.output("UnitLimitMax: %f " % high)

        except PyTango.DevFailed as e:
            Except.print_exception(e)
            self.warning("Not able to read motor position or limits")
예제 #3
0
 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)
예제 #4
0
 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)
예제 #5
0
 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)
예제 #6
0
    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)
예제 #7
0
 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)
예제 #8
0
    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)
예제 #9
0
    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)
예제 #10
0
파일: excepts.py 프로젝트: ska-sa/fandango
    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
예제 #11
0
    def __init__(self, poolName, mntgrpName, flagClear):
        self.db = Database()
        #
        # the pool for the Mg
        #
        try:
            self.poolMg = DeviceProxy(poolName)
        except Exception as e:
            Except.print_exception(e)
            print("failed to get proxy to ", poolName)
            sys.exit(255)
        #
        # find the MG
        #
        try:
            self.mg = DeviceProxy(mntgrpName)
        except Exception:
            lst = [mntgrpName, 'exp_t01', 'exp_c01', 'exp_c02']
            self.poolMg.command_inout('CreateMeasurementGroup', lst)
            self.mg = DeviceProxy(mntgrpName)

        if not flagClear:
            self.hsh = json.loads(self.mg.Configuration)
            self.masterTimer = self.findMasterTimer()
            self.index = len(self.mg.ElementList)
        else:
            self.hsh = {}
            self.hsh[u'controllers'] = {}
            self.hsh[u'description'] = "Measurement Group"
            self.hsh[u'label'] = mntgrpName
            self.index = 0
예제 #12
0
 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')
예제 #13
0
 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")
예제 #14
0
 def read_Value(self, attr):
     twod = self.twod
     # TODO: decide if we force the controller developers to store the
     # last acquired value in the controllers or we always will use
     # cache. This is due to the fact that the clients (MS) read the value
     # after the acquisition had finished.
     use_cache = twod.is_in_operation() and not self.Force_HW_Read
     # For the moment we just check if we recently receive ValueBuffer.
     # event. In this case, we use cache and clean the flag
     # so the cached value will be returned only at the first readout
     # after the acquisition. This is a workaround for the count executed
     # by the MacroServer e.g. step scans or ct which read the value after
     # the acquisition.
     if not use_cache and self._first_read_cache:
         use_cache = True
         self._first_read_cache = False
     value = twod.get_value(cache=use_cache, propagate=0)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     state = twod.get_state(cache=use_cache, propagate=0)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr,
                        value=value.value,
                        quality=quality,
                        timestamp=value.timestamp,
                        priority=0)
예제 #15
0
파일: excepts.py 프로젝트: ska-sa/fandango
    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)
예제 #16
0
    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)
예제 #17
0
 def read_Value(self, attr):
     oned = self.oned
     # TODO: decide if we force the controller developers to store the
     # last acquired value in the controllers or we always will use
     # cache. This is due to the fact that the clients (MS) read the value
     # after the acquisition had finished.
     use_cache = oned.is_in_operation() and not self.Force_HW_Read
     # For the moment we just check if we recently receive ValueBuffer.
     # event. In this case, we use cache and clean the flag
     # so the cached value will be returned only at the first readout
     # after the acquisition. This is a workaround for the count executed
     # by the MacroServer e.g. step scans or ct which read the value after
     # the acquisition.
     if not use_cache and self._first_read_cache:
         use_cache = True
         self._first_read_cache = False
     value = oned.get_value(cache=use_cache, propagate=0)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     state = oned.get_state(cache=use_cache, propagate=0)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr, value=value.value, quality=quality,
                        timestamp=value.timestamp, priority=0)
예제 #18
0
 def _to_motor_write_positions(self, pos):
     w_positions = []
     for elem in self.motor_group.get_user_elements():
         position = pos[elem]
         if position.in_error():
             Except.throw_python_exception(*position.exc_info)
         w_positions.append(position.w_value)
     return w_positions
예제 #19
0
 def _to_motor_write_positions(self, pos):
     w_positions = []
     for elem in self.motor_group.get_user_elements():
         position = pos[elem]
         if position.in_error():
             Except.throw_python_exception(*position.exc_info)
         w_positions.append(position.w_value)
     return w_positions
예제 #20
0
 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')
예제 #21
0
 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")
예제 #22
0
파일: excepts.py 프로젝트: ska-sa/fandango
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
예제 #23
0
    def _on_pseudo_counter_changed(self, event_source, event_type,
                                   event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name.lower()
        attr_name = name

        try:
            attr = self.get_attribute_by_name(attr_name)
        except DevFailed:
            return

        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        value, w_value, error = None, None, None

        if name == "state":
            value = self.calculate_tango_state(event_value)
        elif name == "status":
            value = self.calculate_tango_status(event_value)
        elif name == "valuebuffer":
            value = self._encode_value_chunk(event_value)
            self._first_read_cache = True
        elif name == "value":
            if isinstance(event_value, SardanaAttribute):
                # first obtain the value - during this process it may
                # enter into the error state, either when updating the elements
                # values or when calculating the pseudo value
                value = event_value.value
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                timestamp = event_value.timestamp
            else:
                value = event_value

            state = self.pseudo_counter.get_state(propagate=0)
            if state == State.Moving:
                quality = AttrQuality.ATTR_CHANGING
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                else:
                    value = event_value.value
                timestamp = event_value.timestamp

        self.set_attribute(attr,
                           value=value,
                           w_value=w_value,
                           timestamp=timestamp,
                           quality=quality,
                           priority=priority,
                           error=error,
                           synch=False)
예제 #24
0
    def _on_pseudo_counter_changed(self, event_source, event_type,
                                   event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name.lower()
        attr_name = name
        # TODO: remove this condition when Data attribute will be substituted
        # by ValueBuffer
        if name == "valuebuffer":
            attr_name = "data"

        try:
            attr = self.get_attribute_by_name(attr_name)
        except DevFailed:
            return

        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        value, w_value, error = None, None, None

        if name == "state":
            value = self.calculate_tango_state(event_value)
        elif name == "status":
            value = self.calculate_tango_status(event_value)
        elif name == "valuebuffer":
            value = self._encode_value_chunk(event_value)
            self._first_read_cache = True
        elif name == "value":
            if isinstance(event_value, SardanaAttribute):
                # first obtain the value - during this process it may
                # enter into the error state, either when updating the elements
                # values or when calculating the pseudo value
                value = event_value.value
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                timestamp = event_value.timestamp
            else:
                value = event_value

            state = self.pseudo_counter.get_state(propagate=0)
            if state == State.Moving:
                quality = AttrQuality.ATTR_CHANGING
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                else:
                    value = event_value.value
                timestamp = event_value.timestamp

        self.set_attribute(attr, value=value, w_value=w_value,
                           timestamp=timestamp, quality=quality,
                           priority=priority, error=error, synch=False)
예제 #25
0
 def read_Value(self, attr):
     value = self.ior.get_value(cache=False)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     self.set_attribute(attr,
                        value=value.value,
                        w_value=value.w_value,
                        priority=0,
                        timestamp=value.timestamp)
예제 #26
0
 def read_Value(self, attr):
     pseudo_counter = self.pseudo_counter
     use_cache = pseudo_counter.is_in_operation() and not self.Force_HW_Read
     value = pseudo_counter.get_value(cache=use_cache, propagate=0)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     quality = None
     state = pseudo_counter.get_state(cache=use_cache, propagate=0)
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr, value=value.value, quality=quality,
                        priority=0, timestamp=value.timestamp)
예제 #27
0
 def read_Value(self, attr):
     twod = self.twod
     use_cache = twod.is_in_operation() and not self.Force_HW_Read
     value = twod.get_value(cache=use_cache, propagate=0)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     state = twod.get_state(cache=use_cache, propagate=0)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr, value=value.value, quality=quality,
                        timestamp=value.timestamp, priority=0)
예제 #28
0
 def read_DialPosition(self, attr):
     motor = self.motor
     use_cache = motor.is_in_operation() and not self.Force_HW_Read
     state = motor.get_state(cache=use_cache, propagate=0)
     dial_position = motor.get_dial_position(cache=use_cache, propagate=0)
     if dial_position.error:
         Except.throw_python_exception(*dial_position.exc_info)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr, value=dial_position.value, quality=quality,
                        priority=0, timestamp=dial_position.timestamp)
예제 #29
0
파일: Motor.py 프로젝트: cmft/sardana
 def read_DialPosition(self, attr):
     motor = self.motor
     use_cache = motor.is_in_operation() and not self.Force_HW_Read
     state = motor.get_state(cache=use_cache, propagate=0)
     dial_position = motor.get_dial_position(cache=use_cache, propagate=0)
     if dial_position.error:
         Except.throw_python_exception(*dial_position.exc_info)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr, value=dial_position.value, quality=quality,
                        priority=0, timestamp=dial_position.timestamp)
예제 #30
0
 def read_CurrentValue(self, attr):
     zerod = self.zerod
     #use_cache = ct.is_action_running() and not self.Force_HW_Read
     use_cache = self.get_state() == State.Moving and not self.Force_HW_Read
     value = zerod.get_current_value(cache=use_cache, propagate=0)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     quality = None
     state = zerod.get_state(cache=use_cache, propagate=0)
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr, value=value.value, quality=quality,
                        priority=0, timestamp=value.timestamp)
예제 #31
0
 def _getMcaName(self, mcaSardanaDeviceAlias):
     """
     input: sardana device name alias
     output: the MCA Tango server name which is used by the Sardana device
     """
     try:
         proxy = DeviceProxy(mcaSardanaDeviceAlias)
     except DevFailed as e:
         Except.re_throw_exception(
             e, "MgUtils",
             "failed to create proxy to %s " % mcaSardanaDeviceAlias,
             "MgUtils._gHeMcaName")
     return proxy.TangoDevice
예제 #32
0
 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
예제 #33
0
 def read_ValueRef(self, attr):
     twod = self.twod
     value_ref = twod.get_value_ref()
     if value_ref.error:
         Except.throw_python_exception(*value_ref.exc_info)
     use_cache = twod.is_in_operation() and not self.Force_HW_Read
     state = twod.get_state(cache=use_cache, propagate=0)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr,
                        value=value_ref.value,
                        quality=quality,
                        timestamp=value_ref.timestamp,
                        priority=0)
예제 #34
0
 def read_Value(self, attr):
     twod = self.twod
     # TODO: decide if we force the controller developers to store the
     # last acquired value in the controllers or we always will use
     # cache. This is due to the fact that the clients (MS) read the value
     # after the acquisition had finished.
     use_cache = twod.is_in_operation() and not self.Force_HW_Read
     value = twod.get_value(cache=use_cache, propagate=0)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     state = twod.get_state(cache=use_cache, propagate=0)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr, value=value.value, quality=quality,
                        timestamp=value.timestamp, priority=0)
예제 #35
0
파일: Door.py 프로젝트: rhomspuron/sardana
    def on_door_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()

        name = event_type.name.lower()

        multi_attr = self.get_device_attr()
        try:
            attr = multi_attr.get_attr_by_name(name)
        except DevFailed:
            return

        if name == "state":
            event_value = self.calculate_tango_state(event_value)
        elif name == "status":
            event_value = self.calculate_tango_status(event_value)
        elif name == "recorddata":
            format, value = event_value
            codec = CodecFactory().getCodec(format)
            event_value = codec.encode(('', value))
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                timestamp = event_value.timestamp
                event_value = event_value.value

            if attr.get_data_type() == ArgType.DevEncoded:
                codec = CodecFactory().getCodec('json')
                event_value = codec.encode(('', event_value))
        self.set_attribute(attr, value=event_value, timestamp=timestamp)
예제 #36
0
    def on_zerod_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name
        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        error = None
        attr = self.get_device_attr().get_attr_by_name(name)

        if name == "state":
            event_value = self.calculate_tango_state(event_value)
        elif name == "status":
            event_value = self.calculate_tango_status(event_value)
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                timestamp = event_value.timestamp
                event_value = event_value.value

            if name == "value":
                state = self.zerod.get_state()
                if state == State.Moving:
                    quality = AttrQuality.ATTR_CHANGING
        self.set_attribute(attr, value=event_value, timestamp=timestamp,
                           quality=quality, priority=priority, error=error,
                           synch=False)
예제 #37
0
    def _on_measurement_group_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name
        name = name.replace('_', '')
        multi_attr = self.get_device_attr()
        attr = multi_attr.get_attr_by_name(name)
        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        error = None

        if name == "state":
            event_value = self.calculate_tango_state(event_value)
        elif name == "status":
            event_value = self.calculate_tango_status(event_value)
        elif name == "acquisitionmode":
            event_value = AcqMode.whatis(event_value)
        elif name == "configuration":
            cfg = self.measurement_group.get_user_configuration()
            codec = CodecFactory().getCodec('json')
            _, event_value = codec.encode(('', cfg))
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                timestamp = event_value.timestamp
                event_value = event_value.value

        self.set_attribute(attr, value=event_value, timestamp=timestamp,
                           quality=quality, priority=priority, error=error,
                           synch=False)
예제 #38
0
 def read_Value(self, attr):
     twod = self.twod
     # TODO: decide if we force the controller developers to store the
     # last acquired value in the controllers or we always will use
     # cache. This is due to the fact that the clients (MS) read the value
     # after the acquisition had finished.
     use_cache = twod.is_in_operation() and not self.Force_HW_Read
     value = twod.get_value(cache=use_cache, propagate=0)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     state = twod.get_state(cache=use_cache, propagate=0)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr, value=value.value, quality=quality,
                        timestamp=value.timestamp, priority=0)
예제 #39
0
    def on_door_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()

        name = event_type.name.lower()

        multi_attr = self.get_device_attr()
        try:
            attr = multi_attr.get_attr_by_name(name)
        except DevFailed:
            return

        if name == "state":
            event_value = self.calculate_tango_state(event_value)
        elif name == "status":
            event_value = self.calculate_tango_status(event_value)
        elif name == "recorddata":
            format, value = event_value
            codec = CodecFactory().getCodec(format)
            event_value = codec.encode(('', value))
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                timestamp = event_value.timestamp
                event_value = event_value.value

            if attr.get_data_type() == ArgType.DevEncoded:
                codec = CodecFactory().getCodec('json')
                event_value = codec.encode(('', event_value))
        self.set_attribute(attr, value=event_value, timestamp=timestamp)
예제 #40
0
    def on_controller_changed(self, event_src, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return
        timestamp = time.time()
        name = event_type.name.lower()
        multi_attr = self.get_device_attr()
        try:
            attr = multi_attr.get_attr_by_name(name)
        except DevFailed:
            return
        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        error = None

        if name == "state":
            event_value = self.calculate_tango_state(event_value)
        elif name == "status":
            event_value = self.calculate_tango_status(event_value)
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                timestamp = event_value.timestamp
                event_value = event_value.value
        self.set_attribute(attr,
                           value=event_value,
                           timestamp=timestamp,
                           quality=quality,
                           priority=priority,
                           error=error,
                           synch=False)
예제 #41
0
    def on_zerod_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name
        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        error = None
        attr = self.get_device_attr().get_attr_by_name(name)

        if name == "state":
            event_value = self.calculate_tango_state(event_value)
        elif name == "status":
            event_value = self.calculate_tango_status(event_value)
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                timestamp = event_value.timestamp
                event_value = event_value.value

            if name == "value":
                state = self.zerod.get_state()
                if state == State.Moving:
                    quality = AttrQuality.ATTR_CHANGING
        self.set_attribute(attr,
                           value=event_value,
                           timestamp=timestamp,
                           quality=quality,
                           priority=priority,
                           error=error,
                           synch=False)
예제 #42
0
    def _on_twod_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name.lower()
        name = name.replace('_', '')  # for integration_time events

        try:
            attr = self.get_attribute_by_name(name)
        except DevFailed:
            return

        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        value, w_value, error = None, None, None

        if name == "state":
            value = self.calculate_tango_state(event_value)
        elif name == "status":
            value = self.calculate_tango_status(event_value)
        elif name == "valuebuffer":
            value = self._encode_value_chunk(event_value)
            self._first_read_cache = True
        elif name == "valuerefbuffer":
            value = self._encode_value_ref_chunk(event_value)
            self._first_read_ref_cache = True
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                else:
                    value = event_value.value
                timestamp = event_value.timestamp
            else:
                value = event_value

            if (name in ("timer", "valuereftemplate", "valuerefenabled")
                    and value is None):
                value = "None"
            elif name == "datasource" and value is None:
                full_name = self.get_full_name()
                # for Taurus 3/4 compatibility
                if not full_name.startswith("tango://"):
                    full_name = "tango://{0}".format(full_name)
                value = "{0}/value".format(full_name)
            elif name == "value":
                state = self.twod.get_state()
                if state == State.Moving:
                    quality = AttrQuality.ATTR_CHANGING
        self.set_attribute(attr,
                           value=value,
                           w_value=w_value,
                           timestamp=timestamp,
                           quality=quality,
                           priority=priority,
                           error=error,
                           synch=False)
예제 #43
0
 def read_CurrentValue(self, attr):
     zerod = self.zerod
     #use_cache = ct.is_action_running() and not self.Force_HW_Read
     use_cache = self.get_state() == State.Moving and not self.Force_HW_Read
     value = zerod.get_current_value(cache=use_cache, propagate=0)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     quality = None
     state = zerod.get_state(cache=use_cache, propagate=0)
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr,
                        value=value.value,
                        quality=quality,
                        priority=0,
                        timestamp=value.timestamp)
예제 #44
0
 def read_Position(self, attr):
     # if motors are moving their position is already being updated with a
     # high frequency so don't bother overloading and just get the cached
     # values
     motor_group = self.motor_group
     use_cache = motor_group.is_in_operation() and not self.Force_HW_Read
     position = motor_group.get_position(cache=use_cache, propagate=0)
     if position.error:
         Except.throw_python_exception(*position.exc_info)
     state = motor_group.get_state(cache=use_cache, propagate=0)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr, value=position.value, w_value=position.w_value,
                        quality=quality, priority=0,
                        timestamp=position.timestamp)
예제 #45
0
    def on_controller_changed(self, event_src, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return
        timestamp = time.time()
        name = event_type.name.lower()
        multi_attr = self.get_device_attr()
        try:
            attr = multi_attr.get_attr_by_name(name)
        except DevFailed:
            return
        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        error = None

        if name == "state":
            event_value = self.calculate_tango_state(event_value)
        elif name == "status":
            event_value = self.calculate_tango_status(event_value)
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                timestamp = event_value.timestamp
                event_value = event_value.value
        self.set_attribute(
            attr, value=event_value, timestamp=timestamp, quality=quality, priority=priority, error=error, synch=False
        )
예제 #46
0
    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
예제 #47
0
    def _on_ct_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name.lower()
        name = name.replace('_', '')  # for integration_time events
        attr_name = name
        # TODO: remove this condition when Data attribute will be substituted
        # by ValueBuffer
        if name == "valuebuffer":
            attr_name = "data"

        try:
            attr = self.get_attribute_by_name(attr_name)
        except DevFailed:
            return

        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        value, w_value, error = None, None, None

        if name == "state":
            value = self.calculate_tango_state(event_value)
        elif name == "status":
            value = self.calculate_tango_status(event_value)
        elif name == "valuebuffer":
            value = self._encode_value_chunk(event_value)
            self._first_read_cache = True
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                else:
                    value = event_value.value
                timestamp = event_value.timestamp
            else:
                value = event_value
            if name == "timer" and value is None:
                value = "None"
            elif name == "value":
                w_value = event_source.get_value_attribute().w_value
                state = self.ct.get_state()
                if state == State.Moving:
                    quality = AttrQuality.ATTR_CHANGING

        self.set_attribute(attr,
                           value=value,
                           w_value=w_value,
                           timestamp=timestamp,
                           quality=quality,
                           priority=priority,
                           error=error,
                           synch=False)
예제 #48
0
    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)
예제 #49
0
 def read_Position(self, attr):
     # if motors are moving their position is already being updated with a
     # high frequency so don't bother overloading and just get the cached
     # values
     motor_group = self.motor_group
     use_cache = motor_group.is_in_operation() and not self.Force_HW_Read
     position = motor_group.get_position(cache=use_cache, propagate=0)
     if position.error:
         Except.throw_python_exception(*position.exc_info)
     state = motor_group.get_state(cache=use_cache, propagate=0)
     quality = None
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     self.set_attribute(attr,
                        value=position.value,
                        w_value=position.w_value,
                        quality=quality,
                        priority=0,
                        timestamp=position.timestamp)
예제 #50
0
 def read_Value(self, attr):
     pseudo_counter = self.pseudo_counter
     use_cache = pseudo_counter.is_in_operation() and not self.Force_HW_Read
     if not use_cache and self._first_read_cache:
         use_cache = True
         self._first_read_cache = False
     value_attr = pseudo_counter.get_value(cache=use_cache, propagate=0)
     # first obtain the value - during this process it may
     # enter into the error state, either when updating the elements
     # values or when calculating the pseudo value
     value = value_attr.value
     if value_attr.error:
         Except.throw_python_exception(*value_attr.exc_info)
     quality = None
     state = pseudo_counter.get_state(cache=use_cache, propagate=0)
     if state == State.Moving:
         quality = AttrQuality.ATTR_CHANGING
     timestamp = value_attr.timestamp
     self.set_attribute(attr, value=value, quality=quality,
                        priority=0, timestamp=timestamp)
예제 #51
0
    def _on_oned_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name.lower()
        name = name.replace('_', '')  # for integration_time events
        attr_name = name
        # TODO: remove this condition when Data attribute will be substituted
        # by ValueBuffer
        if name == "valuebuffer":
            attr_name = "data"

        try:
            attr = self.get_attribute_by_name(attr_name)
        except DevFailed:
            return

        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        value, w_value, error = None, None, None

        if name == "state":
            value = self.calculate_tango_state(event_value)
        elif name == "status":
            value = self.calculate_tango_status(event_value)
        elif name == "valuebuffer":
            value = self._encode_value_chunk(event_value)
            self._first_read_cache = True
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                else:
                    value = event_value.value
                timestamp = event_value.timestamp
            else:
                value = event_value
            if name == "timer" and value is None:
                value = "None"
            elif name == "value":
                w_value = event_source.get_value_attribute().w_value
                state = self.oned.get_state()
                if state == State.Moving:
                    quality = AttrQuality.ATTR_CHANGING

        self.set_attribute(attr, value=value, w_value=w_value,
                           timestamp=timestamp, quality=quality,
                           priority=priority, error=error, synch=False)
예제 #52
0
파일: Motor.py 프로젝트: rhomspuron/sardana
    def _on_motor_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name.lower()

        if name == "w_position" and not self.in_write_position:
            self.debug("Storing dial set point: %s",
                       self.motor.dial_position.w_value)
            self.set_write_dial_position_to_db()
            return

        try:
            attr = self.get_attribute_by_name(name)
        except DevFailed:
            return

        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        value, w_value, error = None, None, None

        if name == "state":
            value = self.calculate_tango_state(event_value)
        elif name == "status":
            value = self.calculate_tango_status(event_value)
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                else:
                    value = event_value.value
                timestamp = event_value.timestamp
            else:
                value = event_value
            state = self.motor.get_state(propagate=0)

            if name == "position":
                w_value = event_source.get_position_attribute().w_value
                if state == State.Moving:
                    quality = AttrQuality.ATTR_CHANGING
            elif name == "dialposition" and state == State.Moving:
                quality = AttrQuality.ATTR_CHANGING

        self.set_attribute(attr, value=value, w_value=w_value,
                           timestamp=timestamp, quality=quality,
                           priority=priority, error=error, synch=False)
예제 #53
0
    def _on_motor_group_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name.lower()

        attr = self.get_attribute_by_name(name)
        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        value, w_value, error = None, None, None

        if name == "state":
            value = self.calculate_tango_state(event_value)
        elif name == "status":
            value = self.calculate_tango_status(event_value)
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                else:
                    value = event_value.value
                timestamp = event_value.timestamp
            else:
                value = event_value

            state = self.motor_group.get_state(propagate=0)

            if name == "position":
                w_value = event_value.w_value
                if state == State.Moving:
                    quality = AttrQuality.ATTR_CHANGING

        self.set_attribute(
            attr,
            value=value,
            w_value=w_value,
            timestamp=timestamp,
            quality=quality,
            priority=priority,
            error=error,
            synch=False,
        )
예제 #54
0
    def on_zerod_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        value = None
        error = None

        name = event_type.name.lower()
        attr_name = name
        # TODO: remove this condition when Data attribute will be substituted
        # by ValueBuffer
        if name == "valuebuffer":
            attr_name = "data"
        attr = self.get_device_attr().get_attr_by_name(attr_name)

        if name == "state":
            value = self.calculate_tango_state(event_value)
        elif name == "status":
            value = self.calculate_tango_status(event_value)
        elif name == "valuebuffer":
            value = self._encode_value_chunk(event_value)
        elif name == "value":
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                else:
                    value = event_value.value
                timestamp = event_value.timestamp
            else:
                value = event_value

            if name == "value":
                state = self.zerod.get_state()
                if state == State.Moving:
                    quality = AttrQuality.ATTR_CHANGING
        self.set_attribute(attr, value=value, timestamp=timestamp,
                           quality=quality, priority=priority, error=error,
                           synch=False)
예제 #55
0
파일: util.py 프로젝트: cmft/sardana
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
예제 #56
0
    def _on_twod_changed(self, event_source, event_type, event_value):
        # during server startup and shutdown avoid processing element
        # creation events
        if SardanaServer.server_state != State.Running:
            return

        timestamp = time.time()
        name = event_type.name.lower()
        name = name.replace('_', '')  # for integration_time events

        try:
            attr = self.get_attribute_by_name(name)
        except DevFailed:
            return

        quality = AttrQuality.ATTR_VALID
        priority = event_type.priority
        value, w_value, error = None, None, None

        if name == "state":
            value = self.calculate_tango_state(event_value)
        elif name == "status":
            value = self.calculate_tango_status(event_value)
        else:
            if isinstance(event_value, SardanaAttribute):
                if event_value.error:
                    error = Except.to_dev_failed(*event_value.exc_info)
                else:
                    value = event_value.value
                timestamp = event_value.timestamp
            else:
                value = event_value

            if name == "timer" and value is None:
                value = "None"
            elif name == "value":
                state = self.twod.get_state()
                if state == State.Moving:
                    quality = AttrQuality.ATTR_CHANGING
        self.set_attribute(attr, value=value, w_value=w_value,
                           timestamp=timestamp, quality=quality,
                           priority=priority, error=error, synch=False)
예제 #57
0
파일: IORegister.py 프로젝트: cmft/sardana
 def read_Value(self, attr):
     value = self.ior.get_value(cache=False)
     if value.error:
         Except.throw_python_exception(*value.exc_info)
     self.set_attribute(attr, value=value.value, w_value=value.w_value,
                        priority=0, timestamp=value.timestamp)