Ejemplo n.º 1
0
    def encode(self, value):
        """Translates the given value into a tango compatible value according to
        the attribute data type.

        Raises `pint.DimensionalityError` if value is a Quantity and it
        cannot be expressed in the units of the attribute set in the DB
        """
        if isinstance(value, Quantity):
            # convert to units of the attr in the DB (or raise an exception)
            magnitude = value.to(self._units).magnitude
        else:
            magnitude = value

        fmt = self.getDataFormat()
        tgtype = self._tango_data_type
        if fmt == DataFormat._0D:
            if tgtype == PyTango.CmdArgType.DevDouble:
                attrvalue = float(magnitude)
            elif tgtype == PyTango.CmdArgType.DevFloat:
                # We encode to float, but rounding to Tango::DevFloat precision
                # see: http://sf.net/p/sardana/tickets/162
                attrvalue = float(numpy.float32(magnitude))
            elif PyTango.is_int_type(tgtype):
                # changed as a partial workaround to a problem in PyTango
                # writing to DevULong64 attributes (see ALBA RT#29793)
                attrvalue = long(magnitude)
            elif tgtype == PyTango.CmdArgType.DevBoolean:
                try:
                    attrvalue = bool(int(magnitude))
                except:
                    attrvalue = str(magnitude).lower() == "true"
            elif tgtype == PyTango.CmdArgType.DevUChar:
                try:
                    # assume value to be a 1-character string repr of a byte
                    attrvalue = ord(magnitude)
                except TypeError:
                    # but also support uint8 values (use ord-chr to make sure)
                    attrvalue = ord(chr(magnitude))
            elif tgtype in (PyTango.CmdArgType.DevState, PyTango.CmdArgType.DevEncoded):
                attrvalue = magnitude
            else:
                attrvalue = str(magnitude)
        elif fmt in (DataFormat._1D, DataFormat._2D):
            if PyTango.is_int_type(tgtype):
                # cast to integer because the magnitude conversion gives floats
                attrvalue = magnitude.astype("int64")
            elif tgtype == PyTango.CmdArgType.DevUChar:
                attrvalue = magnitude.view("uint8")
            else:
                attrvalue = magnitude
        else:
            attrvalue = str(magnitude)
        return attrvalue
Ejemplo n.º 2
0
def standard_display_format_t2q(dtype, fmt):
    if fmt == 'Not specified':
        return '!s'
    
    # %6.2f is the default value that Tango sets when the format is
    # unassigned in tango < 8. This is only good for float types! So for other
    # types I am changing this value.
    if fmt == '%6.2f':
        if Tango.is_float_type(dtype, inc_array=True):
            pass
        elif Tango.is_int_type(dtype, inc_array=True):
            fmt = '%d'
        elif tango_cfg.data_type in __S_TYPES:
            fmt = '%s'
    return fmt
Ejemplo n.º 3
0
def attr_value_t2q(attr_cfg, tango_attr_value):
    if tango_attr_value.has_failed:
        pass
    else:
        if tango_attr_value.is_empty:
            pass

    dtype = tango_attr_value.type
    fmt = attr_cfg.display_format
    numerical = Tango.is_numerical_type(dtype)

    r_value = tango_attr_value.value
    w_value = tango_attr_value.w_value
    units = attr_cfg.unit
    if numerical:
        if r_value is not None:
            r_value = Quantity(r_value, units=units)
            if fmt is not None:
                r_value.default_format = fmt + r_value.default_format
        if w_value is not None:
            w_value = Quantity(w_value, units=units)
            if fmt is not None:
                w_value.default_format = fmt + w_value.default_format
        
    quality = quality_t2q(tango_attr_value.quality)
    value = AttributeValue(r_value=r_value, r_quality=quality,
                           r_timestamp=tango_attr_value.time.todatetime(),
                           w_value=w_value, config=attr_cfg)
    return value
Ejemplo n.º 4
0
    def _decodeAttrInfoEx(self, pytango_attrinfoex=None):
        if pytango_attrinfoex is None:
            self._pytango_attrinfoex = PyTango.AttributeInfoEx()
        else:
            self._pytango_attrinfoex = i = pytango_attrinfoex

            self.writable = i.writable != PyTango.AttrWriteType.READ
            self._label = i.label
            self.data_format = data_format_from_tango(i.data_format)
            desc = description_from_tango(i.description)
            if desc != "":
                self._description = desc
            self.type = data_type_from_tango(i.data_type)
            ###############################################################
            # changed in taurus4: range, alarm and warning now return
            # quantities if appropriate
            units = unit_from_tango(i.unit)
            if PyTango.is_numerical_type(i.data_type, inc_array=True):
                Q_ = partial(quantity_from_tango_str, units=units, dtype=i.data_type)
                ninf, inf = float("-inf"), float("inf")
                min_value = Q_(i.min_value) or Quantity(ninf, units)
                max_value = Q_(i.max_value) or Quantity(inf, units)
                min_alarm = Q_(i.alarms.min_alarm) or Quantity(ninf, units)
                max_alarm = Q_(i.alarms.max_alarm) or Quantity(inf, units)
                min_warning = Q_(i.alarms.min_warning) or Quantity(ninf, units)
                max_warning = Q_(i.alarms.max_warning) or Quantity(inf, units)
                self._range = [min_value, max_value]
                self._warning = [min_warning, max_warning]
                self._alarm = [min_alarm, max_alarm]

            ###############################################################
            # The following members will be accessed via __getattr__
            # self.standard_unit
            # self.display_unit
            # self.disp_level
            ###############################################################
            # Tango-specific extension of TaurusConfigValue
            self.display_level = display_level_from_tango(i.disp_level)
            self.tango_writable = i.writable
            self.max_dim = i.max_dim_x, i.max_dim_y
            ###############################################################
            self.format = standard_display_format_from_tango(i.data_type, i.format)
            # self._units and self._display_format is to be used by
            # TangoAttrValue for performance reasons. Do not rely on it in other
            # code
            self._units = units
Ejemplo n.º 5
0
def attr_config_t2q(tango_cfg):
    if tango_cfg is None:
        return None
    result = AttributeConfig()

    dtype = tango_cfg.data_type
    disp_fmt = display_format_t2q(dtype, tango_cfg.format)

    result.name = tango_cfg.name
    result.label = tango_cfg.label
    result.description = description_t2q(tango_cfg.description)
    result.ndim = int(tango_cfg.data_format)
    result.display_level = display_level_t2q(tango_cfg.disp_level)
    result.format = standard_display_format_t2q(dtype, tango_cfg.format)
    result.access = access_t2q(tango_cfg.writable)
    result.display_format = disp_fmt

    numerical = Tango.is_numerical_type(dtype)         

    result.unit = units = unit_t2q(tango_cfg.unit, to_quantity=numerical)
    result.display_unit = display_unit_t2q(tango_cfg.display_unit, to_quantity=numerical)
    result.standard_unit = standard_unit_t2q(tango_cfg.standard_unit, to_quantity=numerical)

    if numerical:
        Q_ = partial(quantity_str2t_no_error, units=units, dtype=dtype, fmt=disp_fmt)
    else:
        Q_ = partial(str_2_obj, tg_type=dtype)
    result.min_value = Q_(tango_cfg.min_value)
    result.max_value = Q_(tango_cfg.max_value)
    result.min_alarm = Q_(tango_cfg.min_alarm)
    result.max_alarm = Q_(tango_cfg.max_alarm)
    result.min_warning = Q_(tango_cfg.alarms.min_warning)
    result.max_warning = Q_(tango_cfg.alarms.max_warning)
        
    result.value_range = [result.min_value, result.max_value]
    result.alarm_range = [result.min_alarm, result.max_alarm]
    result.warning_range = [result.min_warning, result.max_warning]

    # add dev_name, dev_alias, attr_name, attr_full_name
#    dev, attr = attr_cfg._getDev(), attr_cfg._getAttr()
#    result.dev_name = dev.getNormalName()
#    result.dev_alias = dev.getSimpleName()
#    result.attr_name = attr.getSimpleName()
#    result.attr_fullname = attr.getNormalName()
    return result
Ejemplo n.º 6
0
def mon(self, parameter_s=''):
    """Monitor a given attribute.
    
    %mon -a <attribute name>           - activates monitoring of given attribute
    %mon -d <attribute name>           - deactivates monitoring of given attribute
    %mon -r                            - deactivates monitoring of all attributes
    %mon -i <id>                       - displays detailed information for the event with given id
    %mon -l <dev filter> <attr filter> - shows event table filtered with the regular expression for attribute name
    %mon                               - shows event table (= %mon -i .* .*)"""

    db = __get_db()
    if db is None:
        print("You are not connected to any Tango Database.")
        return

    # make sure parameter_s is a str and not a unicode
    parameter_s = str(parameter_s)
    opts, args = self.parse_options(parameter_s, 'adril', mode='list')
    if len(args) > 3:
        raise UsageError("%mon: too many arguments")
    if 'd' in opts:
        try:
            todel = args[0]
        except IndexError:
            raise UsageError("%mon -d: must provide an attribute to unmonitor")
        else:
            try:
                dev, _, attr = todel.rpartition("/")
                subscriptions = __get_device_subscriptions(dev)
                attr_id = subscriptions[attr.lower()]
                del subscriptions[attr.lower()]
                d = __get_device_proxy(dev)
                d.unsubscribe_event(attr_id)
                print("Stopped monitoring '%s'" % todel)
            except KeyError:
                raise UsageError("%%mon -d: Not monitoring '%s'" % todel)

    elif 'a' in opts:
        try:
            toadd = args[0]
        except IndexError:
            raise UsageError("%mon -a: must provide an attribute to monitor")
        dev, _, attr = toadd.rpartition("/")
        subscriptions = __get_device_subscriptions(dev)
        attr_id = subscriptions.get(attr.lower())
        if attr_id is not None:
            raise UsageError("%%mon -a: Already monitoring '%s'" % toadd)
        d = __get_device_proxy(dev)
        w = __get_event_log()
        model = w.model()
        attr_id = d.subscribe_event(attr, PyTango.EventType.CHANGE_EVENT,
                                    model, [])
        subscriptions[attr.lower()] = attr_id
        print("'%s' is now being monitored. Type 'mon' to see all events" %
              toadd)
    elif 'r' in opts:
        for d, v in db._db_cache.devices.items():
            d, subs = v[3], v[4]
            for _id in subs.values():
                d.unsubscribe_event(_id)
            v[4] = {}
    elif 'i' in opts:
        try:
            evtid = int(args[0])
        except IndexError:
            raise UsageError("%mon -i: must provide an event ID")
        except ValueError:
            raise UsageError("%mon -i: must provide a valid event ID")
        try:
            w = __get_event_log()
            e = w.getEvents()[evtid]
            if e.err:
                print(str(PyTango.DevFailed(*e.errors)))
            else:
                print(str(e))
        except IndexError:
            raise UsageError("%mon -i: must provide a valid event ID")
    elif 'l' in opts:
        try:
            dexpr = args[0]
            aexpr = args[1]
        except IndexError:
            raise UsageError("%mon -l: must provide valid device and " \
                             "attribute filters")
        w = __get_event_log()
        w.show(dexpr, aexpr)
    else:
        w = __get_event_log()
        w.show()
Ejemplo n.º 7
0
 def isInteger(self, inc_array=False):
     tgtype = self._tango_data_type
     return PyTango.is_int_type(tgtype, inc_array=inc_array)
Ejemplo n.º 8
0
    def test_start_five(self):
        fun = sys._getframe().f_code.co_name
        print("Run: %s.%s() " % (self.__class__.__name__, fun))
        # idn = self.__rnd.randint(1, 1231233)
        cqueue = Queue.Queue()
        self.assertTrue(cqueue.empty())
        ths = []
        for i in range(5):
            ths.append(CheckerThread(i, cqueue))

        ci0 = CheckerItem("cp0")
        ci0.append(TangoDSItem("ds0", None, None))
        cqueue.put(ci0)

        ci1 = CheckerItem("cp1")
        ci1.append(TangoDSItem("ds1", "wrongsdfgdfg", None))
        cqueue.put(ci1)

        ci2 = CheckerItem("cp2")
        ci2.append(TangoDSItem("ds2", self._simps3.new_device_info_writer.name,
                               None))
        cqueue.put(ci2)

        ci3 = CheckerItem("cp3")
        ci3.append(TangoDSItem("ds3", self._simps3.new_device_info_writer.name,
                               'ScalarDouble'))
        ci3.append(TangoDSItem("ds4", self._simps3.new_device_info_writer.name,
                               'ScalarLong'))
        ci3.append(TangoDSItem("ds5", self._simps3.new_device_info_writer.name,
                               'ScalarShort'))
        ci3.append(TangoDSItem("ds6", self._simps3.new_device_info_writer.name,
                               'ScalarBoolean'))
        cqueue.put(ci3)

        ci4 = CheckerItem("cp4")
        ci4.append(TangoDSItem("ds3", self._simps3.new_device_info_writer.name,
                               'ScalarDouble'))
        ci4.append(TangoDSItem("ds4", self._simps3.new_device_info_writer.name,
                               'ScalarDoubleddd'))
        cqueue.put(ci4)

        ci5 = CheckerItem("cp5")
        dp = PyTango.DeviceProxy(self._simps4.new_device_info_writer.name)
        dp.SetState("ALARM")
        ci5.append(TangoDSItem("ds3", self._simps4.new_device_info_writer.name,
                               'ScalarDouble'))
        ci5.append(TangoDSItem("ds4", self._simps4.new_device_info_writer.name,
                               'ScalarShort'))
        cqueue.put(ci5)

        ci6 = CheckerItem("cp6")
        dp = PyTango.DeviceProxy(self._simps4.new_device_info_writer.name)
        dp.CreateAttribute("Position")
        ci6.append(TangoDSItem("ds3", self._simps4.new_device_info_writer.name,
                               None))
        ci6.append(TangoDSItem("ds4", self._simps4.new_device_info_writer.name,
                               'ScalarShort'))
        cqueue.put(ci6)

        ci7 = CheckerItem("cp6")
        dp = PyTango.DeviceProxy(self._simps.new_device_info_writer.name)
        dp.CreateAttribute("Position")
        ci7.append(TangoDSItem("ds3", self._simps.new_device_info_writer.name,
                               None))
        ci7.append(TangoDSItem("ds4", self._simps.new_device_info_writer.name,
                               'ScalarShort'))
        cqueue.put(ci7)

        ci8 = CheckerItem("cp8")
        dp = PyTango.DeviceProxy(self._simps2.new_device_info_writer.name)
        dp.SetState("FAULT")
        ci8.append(TangoDSItem("ds3", self._simps2.new_device_info_writer.name,
                               'ScalarDouble'))
        ci8.append(TangoDSItem("ds4", self._simps2.new_device_info_writer.name,
                               'ScalarShort'))
        cqueue.put(ci8)

        ci9 = CheckerItem("cp9")
        ci9.append(TangoDSItem(
            "ds3", self._simpsoff.new_device_info_writer.name,
            'ScalarDouble'))
        ci9.append(TangoDSItem(
            "ds4", self._simpsoff.new_device_info_writer.name,
            'ScalarShort'))
        cqueue.put(ci9)

        for el in ths:
            el.start()
        for el in ths:
            el.join()

        self.assertTrue(ci0.message is not None)
        self.assertEqual(ci0.errords, 'ds0')
        self.assertTrue(not ci0.active)
        self.assertTrue(ci1.message is not None)
        self.assertEqual(ci1.errords, 'ds1')
        self.assertTrue(not ci1.active)
        self.assertEqual(ci2.errords, None)
        self.assertEqual(ci2.message, None)
        self.assertTrue(ci2.active)
        self.assertEqual(ci3.errords, None)
        self.assertEqual(ci3.message, None)
        self.assertTrue(ci3.active)
        self.assertEqual(ci4.errords, "ds4")
        self.assertEqual(ci4.message, 'Empty Attribute')
        self.assertTrue(not ci4.active)
        self.assertEqual(ci5.errords, "ds4")
        self.assertEqual(ci5.message, 'ALARM_STATE')
        self.assertTrue(ci5.active)
        self.assertEqual(ci6.errords, "ds4")
        self.assertEqual(ci6.message, 'ALARM_STATE')
        self.assertTrue(ci6.active)
        self.assertEqual(ci7.errords, None)
        self.assertEqual(ci7.message, None)
        self.assertTrue(ci7.active, None)
        self.assertEqual(ci8.errords, "ds3")
        self.assertEqual(ci8.message, 'FAULT STATE')
        self.assertTrue(not ci8.active)
        self.assertEqual(ci9.errords, "ds3")
        self.assertTrue(ci9.message is not None)
        self.assertTrue(not ci9.active)
Ejemplo n.º 9
0
 def add(self):
     db = PyTango.Database()
     db.add_device(self.new_device_info_writer)
     db.add_server(self.new_device_info_writer.server,
                   self.new_device_info_writer)
Ejemplo n.º 10
0
                               description=format_description(info))

parser.add_option("-t", "--timeout", dest="timeout", default=3.0, type="float",
                  help="Adjust the timeout for the command (in seconds)")
parser.add_option("-f", "--forget", dest="forget", default=False,
                  action="store_true",
                  help="Ignore the result, return immediately")
options, args = parser.parse_args()

# Check arguments
if info.in_type == PyTango.ArgType.DevVoid:
    if not len(args) == 0:
        sys.exit("No arguments expected!")
    argument = None
else:
    if PyTango.is_scalar_type(info.in_type) and not len(args) == 1:
        sys.exit("Exactly one argument expected!")
    argument = PyTango.utils.seqStr_2_obj(args, info.in_type)


# run command
proxy.set_timeout_millis(int(options.timeout * 1000))
if options.forget:
    result = proxy.command_inout_asynch("{command}", argument, options.forget)
else:
    result = proxy.command_inout("{command}", argument)

# output
if result is not None and not options.forget:
    if PyTango.is_array_type(info.out_type):
        print "\n".join(result)
 def init(self):
     #self.md2          = PyTango.DeviceProxy('i11-ma-cx1/ex/md2')
     self.beamPosition = PyTango.DeviceProxy('i11-ma-cx1/ex/md2-beamposition')
     MiniDiff.init(self)
Ejemplo n.º 12
0
 def init(self):
     import PyTango
     self.attr_proxy = PyTango.AttributeProxy(self.raw_value)
Ejemplo n.º 13
0
# Every Qt application must have one and only one QApplication object;
# it receives the command line arguments passed to the script, as they
# can be used to customize the application's appearance and behavior
import sys
from PyQt4.QtGui import *
from PyQt4 import QtCore
import PyTango
from PyQt4 import QtGui
import PyTango

power_supply = PyTango.DeviceProxy("test/power_supply/1")

qt_app = QApplication(sys.argv)


class TangoDevice(QWidget):
    ''' A PyQT4 Gui to read attributes(current, voltage) and write attributes(current) to the  Tango Server of PowerSupply Device'''

    #to write current to device on button 'write' click
    def writevalue(self):
        self.currwrite = self.write.text()
        power_supply.current = float(self.currwrite)

    #to turnon the device
    def turon(self):

        power_supply.TurnOn()
        self.state.setPlaceholderText(str(power_supply.state()))

    #to turnoff the device
    def turnoff(self):
Ejemplo n.º 14
0
 def init_device(self):
     self.debug_stream("In init_device:")
     Device.init_device(self)
     self.phase_val = 0.0
     self.dac_dev = pt.DeviceProxy(self.dac_ds_name)
     self.set_state(pt.DevState.ON)
Ejemplo n.º 15
0
 def __init__(self, url='timing/EventR/rec1'):
     self.dp = PyTango.DeviceProxy(url)
Ejemplo n.º 16
0
 def __init__(self, url='timing/EventR/rec1'):
     if type(url) is PyTango.DeviceProxy:
         self.dp = url
     else:
         self.dp = PyTango.DeviceProxy(url)
Ejemplo n.º 17
0
    def initialize_dynamic_attributes(self):
        self.debug_stream('In initialize_dynamic_attributes()')
        if self.pv is not None:  # already initialized
            return
        # variables initialization
        READ_METHOD = self.read_attr
        WRITE_METHOD = self.write_attr
        if self.Host == []:
            self.Host = ''
        self.pv = {}
        pvs = {}

        try:
            # initialize libca library
            epics.ca.initialize_libca()

            # get pv names and build libca channels
            for pv_entry in self.ProcessVariables:
                pv_attr = pv_entry.split('\t')
                attr_name = None
                if len(pv_attr) == 1:
                    pv_name = pv_attr[0]
                elif len(pv_attr) == 2:
                    pv_name, attr_name = pv_attr
                else:
                    msg = 'Invalid entry in ProcessVariables device property:'\
                        ' %s' % pv_entry
                    self.error_stream(msg)
                    self._set_state(PyTango.DevState.FAULT, msg)
                    return
                # get host name if necessary
                if self.Host != '':
                    pv_full_name = '%s:%s' % (self.Host, pv_name)
                else:
                    pv_full_name = pv_name
                # create epics channel to PV (to increase performance do not
                # wait for a connection)
                ch_id = epics.ca.create_channel(pv_full_name,
                                                connect=False,
                                                auto_cb=False)
                # build default attribute name (if not provided)
                if attr_name is None:
                    attr_name = self.epics2tango_name(pv_name)
                self.pv[attr_name] = [ch_id, pv_full_name]
                pvs[attr_name] = [ch_id]

            # connect PVs and get necessary info
            for name, data in pvs.items():
                connected = epics.ca.connect_channel(data[0])
                if not connected:
                    msg = 'At least one channel unreachable. Is hardware up?'
                    self.error_stream(msg)
                    self._set_state(PyTango.DevState.FAULT,
                                    msg,
                                    force_init=True)
                    return
            epics.ca.poll()  # wait for connections completion
            for name, data in pvs.items():
                data.append(epics.ca.field_type(data[0]))
                data.append(epics.ca.read_access(data[0]))
                data.append(epics.ca.write_access(data[0]))
                data.append(epics.ca.element_count(data[0]))

            # add dynamic attributes
            for attr_name, data in pvs.items():
                # find out tango type
                tango_type = self.epics2tango_type(data[1])
                if tango_type is None:
                    msg = 'Unknown type %s for PV %s' %\
                          (str(data[1]), self.pv[attr_name][1])
                    self.error_stream(msg)
                    self._set_state(PyTango.DevState.ALARM, msg)
                    del self.pv[attr_name]
                    continue
                # find out read/write access
                read_access = bool(data[2])
                write_access = bool(data[3])
                read_method = None
                write_method = None
                if read_access and write_access:
                    read_method = READ_METHOD
                    write_method = WRITE_METHOD
                    access_type = PyTango.AttrWriteType.READ_WRITE
                elif read_access and not write_access:
                    read_method = READ_METHOD
                    access_type = PyTango.AttrWriteType.READ
                elif not read_access and write_access:
                    write_method = WRITE_METHOD
                    access_type = PyTango.AttrWriteType.WRITE
                else:
                    msg = 'PV %s has neither read nor write permissions'\
                          % pv_full_name
                    self.error_stream(msg)
                    self._set_state(PyTango.DevState.FAULT, msg)
                    continue
                # find out dimension and build attribute
                dimension = data[4]
                if dimension > 1:
                    attr = PyTango.SpectrumAttr(attr_name, tango_type,
                                                access_type, dimension)
                else:
                    attr = PyTango.Attr(attr_name, tango_type, access_type)
                properties = PyTango.UserDefaultAttrProp()
                # set description field with PV name
                properties.set_description(self.pv[attr_name][1])
                attr.set_default_properties(properties)
                # add attribute
                self.add_attribute(attr, read_method, write_method)
        except Exception, e:
            msg = 'Unable to create dynamic attributes'
            self.error_stream('%s: %s' % (msg, str(e)))
            self._set_state(PyTango.DevState.FAULT, msg)
Ejemplo n.º 18
0
def createChannelDict(channel, index=None, **kwargs):
    from taurus.core.tango import FROM_TANGO_TO_STR_TYPE
    import PyTango
    import numpy

    if isinstance(channel, str):
        #@fixme: to make things uglier, I lazily assume Tango attribute namin
        dev_name, attr_name = channel.rsplit('/', 1)
        name = attr_name
        try:
            dev = PyTango.DeviceProxy(dev_name)
            db = dev.get_device_db()
            try:
                alias = db.get_alias(dev.name())
            except:
                # no alias...
                alias = dev.name()
            label = alias + "/" + attr_name
        except:
            label = channel
        full_name = channel
        source = channel
    else:
        name = channel['name']
        label = name
        full_name = channel['full_name']
        source = channel['source']

    ret = {
        'name': name,
        'label': label,
        'full_name': full_name,
        # bool. Whether this channel is enabled (if not enabled, it won't be
        # used for output or plot)
        'enabled': True,
        'output': True,  # bool. Whether to show output in the stdout
        'data_type': 'float64',
        'data_units': 'No unit',
        #           'timer': '', #should contain a channel name
        #           'monitor': '', #should contain a channel name
        #           'trigger': '', #should contain a channel name
        # 'value_ref_enabled': False,  # bool
        # 'value_ref_pattern': '',  # str
        'conditioning': '',  # this is a python expresion to be evaluated for conditioning the data. The data for this channel can be referred as 'x' and data from other channels can be referred by channel name
        'normalization': Normalization.No,  # one of the Normalization enumeration members
        # string indicating the location of the data of this channel within
        # the nexus tree
        'nexus_path': '',
    }

    # If the channel is a Tango one, try to guess data_type, shape and
    # data_units
    attrproxy = attrconf = value = None
    dtype = shape = None
    try:
        attrproxy = PyTango.AttributeProxy(source)
        attrconf = attrproxy.get_config()
        # avoid trying to read for scalars. We know that their shape must be ()
        if attrconf.data_format != PyTango.AttrDataFormat.SCALAR:
            value = attrproxy.read().value
    except Exception as e:
        print(str(e))

    if value is not None:
        shape = list(numpy.shape(value))
        dtype = getattr(value, 'dtype', numpy.dtype(type(value))).name
        ret['data_units'] = attrconf.unit
    elif attrconf is not None:
        if attrconf.data_format == PyTango.AttrDataFormat.SCALAR:
            shape = []
        else:
            shape = [n for n in (attrconf.max_dim_x,
                                 attrconf.max_dim_y) if n > 0]
        dtype = FROM_TANGO_TO_STR_TYPE[attrconf.data_type]
        ret['data_units'] = attrconf.unit

    if dtype is not None:
        #        if dtype.startswith('str'):
        #            dtype='char'
        #            shape = list(shape)+[DEFAULT_STRING_LENGTH]
        #        elif dtype == 'bool':
        #            dtype='int8'
        ret['data_type'] = dtype
    if shape is not None:
        ret['shape'] = shape

    # now overwrite using the arguments
    ret.update(kwargs)

    # Calculate the index
    if index is not None:
        # an integer used for ordering the channel in this measurement group
        ret['index'] = index

    # Choose a default plot_type for the channel
    if 'plot_type' not in ret:
        default_plot_type = {0: PlotType.Spectrum,
                             2: PlotType.Image, None: PlotType.No}
        try:
            rank = len(ret['shape'])
        except KeyError:
            rank = None  # if shape is not known, use the default plot_type
        ret['plot_type'] = default_plot_type.get(rank, PlotType.No)

    # And a default value for plot_axes
    if 'plot_axes' not in ret:
        default_axes = {PlotType.No: [], PlotType.Spectrum: [
            '<mov>'], PlotType.Image: ['<idx>', '<idx>']}
        # a string defining a colon-separated list of axis names. An axis can
        # be a channel name or "<idx>". This shares the syntax of the NeXus
        # @axes attribute
        ret['plot_axes'] = default_axes[ret['plot_type']]

    return ret
Ejemplo n.º 19
0
 def __getAttrObj(self,
                  attrName,
                  definition,
                  channel=None,
                  function=None,
                  multiple=None):
     # TODO: image dimensions
     if definition['dim'] == [0]:
         if 'writeCmd' in definition:
             attr = PyTango.Attr(attrName, definition['type'],
                                 PyTango.READ_WRITE)
             readmethod = AttrExc(getattr(self.__device, 'read_attr'))
             writemethod = AttrExc(getattr(self.__device, 'write_attr'))
         else:
             attr = PyTango.Attr(attrName, definition['type'], PyTango.READ)
             readmethod = AttrExc(getattr(self.__device, 'read_attr'))
             writemethod = None
     elif definition['dim'][0] == 1:
         if 'writeCmd' in definition:
             attr = PyTango.SpectrumAttr(attrName, definition['type'],
                                         PyTango.READ_WRITE,
                                         definition['dim'][1])
             readmethod = AttrExc(getattr(self.__device, 'read_attr'))
             writemethod = AttrExc(getattr(self.__device, 'write_attr'))
         else:
             attr = PyTango.SpectrumAttr(attrName, definition['type'],
                                         PyTango.READ, definition['dim'][1])
             readmethod = AttrExc(getattr(self.__device, 'read_attr'))
             writemethod = None
     else:
         raise AttributeError("Not supported multiple dimensions")
     # attribute properties
     aprop = PyTango.UserDefaultAttrProp()
     if 'unit' in definition:
         aprop.set_unit(latin1(definition['unit']))
     if 'min' in definition:
         aprop.set_min_value(str(definition['min']))
     if 'max' in definition:
         aprop.set_max_value(str(definition['max']))
     if 'format' in definition:
         aprop.set_format(latin1(definition['format']))
     if 'description' in definition:
         aprop.set_description(latin1(definition['description']))
     if 'label' in definition:
         aprop.set_label(latin1(definition['label']))
     if 'memorized' in definition:
         attr.set_memorized()
         attr.set_memorized_init(True)
     attr.set_default_properties(aprop)
     self.__device.add_attribute(attr,
                                 r_meth=readmethod,
                                 w_meth=writemethod)
     self._attributeList.append(attrName)
     # prepare internal structure ---
     if channel or function or multiple:
         if channel:
             like = "channel"
         elif function:
             like = "function"
         elif multiple and 'scpiPrefix' in definition['multiple'] and\
                 'attrSuffix' in definition['multiple']:
             like = definition['multiple']['scpiPrefix']
         else:
             raise AttributeError("Wrong definition of multiple attribute")
         number = channel or function or multiple
         self.__prepareChannelLikeAttr(like, number, definition)
     else:
         readCmd = definition['readCmd']
         if 'writeCmd' not in definition:
             # writeCmd = definition['writeCmd']
             definition['writeCmd'] = None
     if 'readFormula' not in definition:
         # readFormula = definition['readFormula']
         definition['readFormula'] = None
     # if 'writeFormula' not in definition:
     #     # writeFormula = definition['writeFormula']
     #     writeFormula = None
     # build internal structure ---
     if definition['writeCmd'] is None:
         self.__buildROObj(attrName, definition)
     else:
         self.__buildRWObj(attrName, definition, readmethod, writemethod)
         if 'writeValues' in definition:
             self.__prepareWriteValues(attrName, definition, aprop, attr)
     return attr
Ejemplo n.º 20
0
import PyTango
import subprocess
import time
import sys

new_device_info_writer = PyTango.DbDevInfo()
new_device_info_writer._class = "SimpleServer"
new_device_info_writer.server = "SimpleServer/S1"
new_device_info_writer.name = "stestp09/testss/s1r228"

db = PyTango.Database()
db.add_device(new_device_info_writer)
db.add_server(new_device_info_writer.server, new_device_info_writer)

# time.sleep(1)

psub = subprocess.Popen(
    "./ST S1 &", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
# psub = os.system("./ST S1 &")
# time.sleep(0.3)

# time.sleep(10)


try:
    #  dp = PyTango.DeviceProxy(new_device_info_writer.name)

    found = False
    cnt = 0
    while not found and cnt < 100000:
        try:
Ejemplo n.º 21
0
import json
import time
import logging

import PyTango

logger = logging.getLogger()
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(module)s - '
    '%(pathname)s : %(lineno)d - %(message)s',
    level=logging.INFO)

device_name = 'C3/unity/eras1'

td = PyTango.DeviceProxy(device_name)
attr_name = 'skelton'
global sample


def write_json(filename, sample):
    with open(filename + ".json", 'w') as fp:
        json.dump(sample, fp)


# Set up a listener
def printer(event_data):
    try:
        #print event_data # A PyTango.EventData instance
        global sample
        sample = event_data
    except Exception:
Ejemplo n.º 22
0
 async def resolve_info(self, info):
     db = PyTango.Database()
     return db.get_info()
Ejemplo n.º 23
0
            rdabs = float(arg.split("=", 1)[1])
        elif arg.find("-rdrel=") in [0, 1]:
            rdrel = float(arg.split("=", 1)[1])
        elif arg.find("-out=") in [0, 1]:
            out = arg.split("=", 1)[1]
            if os.path.isfile(out):
                outFile = (os.path.abspath(out))
        elif arg.find("-sub=") in [0, 1]:
            out = arg.split("=", 1)[1]
            if os.path.isfile(out):
                subFile = (os.path.abspath(out))

        elif os.path.isfile(arg):
            filenames.append(os.path.abspath(arg))

    edna = PyTango.DeviceProxy(device)

    #    edna.initPlugin(plugin)
    t0 = time.time()
    totaltime = 0.0
    listjobs = []
    listInFiles = []
    if filenames:
        common_base = None
        for fn in filenames:
            base = os.path.basename(os.path.splitext(fn)[0])
            if outFile is None:
                if common_base:
                    common_base = getCommon(base, common_base)
                else:
                    common_base = base
Ejemplo n.º 24
0
    parser.add_argument('device', type=str, help='TANGO device address')
    parser.add_argument('-n',
                        '--number',
                        type=int,
                        default=1000,
                        help='Number of frames to acquire')
    parser.add_argument('-s',
                        '--software-trigger',
                        action='store_true',
                        default=False,
                        help='Use software trigger instead of auto')

    args = parser.parse_args()

    camera = PyTango.DeviceProxy(args.device)
    camera.exposure_time = 0.0001
    camera.trigger_source = 1 if args.software_trigger else 0
    camera.Start()

    start = time.time()
    size = 0
    acquired = 0

    if HAVE_PROGRESSBAR:
        progress = progressbar.ProgressBar(max_value=args.number,
                                           redirect_stdout=True)
    else:
        progress = lambda x: x
        print("Recording {} frames ...".format(args.number))
Ejemplo n.º 25
0
 def initialize(self):
     self.dev = PyTango.DeviceProxy(self.dev_name)
     self.dev.init()
 def setProp(self, rc, name, value):
     db = PyTango.Database()
     name = "" + name[0].upper() + name[1:]
     db.put_device_property(self._sv.new_device_info_writer.name,
                            {name: value})
     rc.Init()
Ejemplo n.º 27
0
 def getObj(self, str_repr):
     import PyTango
     return PyTango.DeviceProxy(str_repr)
Ejemplo n.º 28
0
 def delete(self):
     db = PyTango.Database()
     db.delete_server(self.new_device_info_writer.server)
Ejemplo n.º 29
0
 def getNewOperation(self, value):
     attr_value = PyTango.AttributeValue()
     attr_value.name = self.getSimpleName()
     attr_value.value = self.encode(value)
     op = WriteAttrOperation(self, attr_value)
     return op
Ejemplo n.º 30
0
    def __init__(
        self,
        name,
        attribute_name,
        tangoname=None,
        username=None,
        polling=None,
        timeout=10000,
        **kwargs
    ):
        ChannelObject.__init__(self, name, username, **kwargs)

        self.attributeName = attribute_name
        self.deviceName = tangoname
        self.device = None
        self.value = None
        self.polling = polling
        self.__connections = 0
        self.__value = None
        self.pollingTimer = None
        self.timeout = int(timeout)

        logging.getLogger("HWR").debug(
            "creating Tango attribute %s/%s, polling=%s, timeout=%d",
            self.deviceName,
            self.attributeName,
            polling,
            self.timeout,
        )

        try:
            self.device = PyTango.DeviceProxy(self.deviceName)
        except PyTango.DevFailed as traceback:
            last_error = traceback[-1]
            logging.getLogger("HWR").error(
                "%s: %s", str(self.name()), last_error["desc"]
            )
        else:
            try:
                self.device.ping()
            except PyTango.ConnectionFailed:
                self.device = None
                raise ConnectionError
            else:
                self.device.set_timeout_millis(self.timeout)

                if isinstance(polling, int):
                    self.pollingTimer = qt.QTimer()
                    self.pollingTimer.connect(
                        self.pollingTimer, qt.SIGNAL("timeout()"), self.poll
                    )
                    self.pollingTimer.start(polling)
                else:
                    if polling == "events":
                        # try to register event
                        try:
                            self.device.subscribe_event(
                                self.attributeName, PyTango.EventType.CHANGE, self, []
                            )
                        except PyTango.EventSystemFailed:
                            pass
Ejemplo n.º 31
0
 def isNumeric(self, inc_array=False):
     tgtype = self._tango_data_type
     return PyTango.is_numerical_type(tgtype, inc_array=inc_array)
Ejemplo n.º 32
0
 def isNumeric(self, inc_array=False):
     tgtype = self._tango_data_type
     return PyTango.is_numerical_type(tgtype, inc_array=inc_array)
Ejemplo n.º 33
0
 def isInteger(self, inc_array=False):
     tgtype = self._tango_data_type
     return PyTango.is_int_type(tgtype, inc_array=inc_array)
Ejemplo n.º 34
0
 def isFloat(self, inc_array=False):
     tgtype = self._tango_data_type
     return PyTango.is_float_type(tgtype, inc_array=inc_array)
Ejemplo n.º 35
0
    def test_run_attr(self):
        fun = sys._getframe().f_code.co_name
        print("Run: %s.%s() " % (self.__class__.__name__, fun))
        idn = self.__rnd.randint(1, 1231233)
        cqueue = Queue.Queue()
        self.assertTrue(cqueue.empty())
        el = CheckerThread(idn, cqueue)
        self.assertEqual(el.index, idn)

        matt = list(ATTRIBUTESTOCHECK)
        self.assertEqual(matt, ["Value", "Position", "Counts", "Data",
                                "Voltage", "Energy", "SampleTime"])
        ATTRIBUTESTOCHECK[:] = []
        el.run()
        self.assertTrue(cqueue.empty())

        ci0 = CheckerItem("cp0")
        ci0.append(TangoDSItem("ds0", None, None))
        cqueue.put(ci0)

        ci1 = CheckerItem("cp1")
        ci1.append(TangoDSItem("ds1", "wrongsdfgdfg", None))
        cqueue.put(ci1)

        ci2 = CheckerItem("cp2")
        ci2.append(TangoDSItem(
            "ds2", self._simps3.new_device_info_writer.name, None))
        cqueue.put(ci2)

        ci3 = CheckerItem("cp3")
        ci3.append(TangoDSItem(
            "ds3", self._simps3.new_device_info_writer.name,
            'ScalarDouble'))
        ci3.append(TangoDSItem(
            "ds4", self._simps3.new_device_info_writer.name,
            'ScalarLong'))
        ci3.append(TangoDSItem(
            "ds5", self._simps3.new_device_info_writer.name,
            'ScalarShort'))
        ci3.append(TangoDSItem(
            "ds6", self._simps3.new_device_info_writer.name,
            'ScalarBoolean'))
        cqueue.put(ci3)

        ci4 = CheckerItem("cp4")
        ci4.append(TangoDSItem(
            "ds3", self._simps3.new_device_info_writer.name,
            'ScalarDouble'))
        ci4.append(TangoDSItem(
            "ds4", self._simps3.new_device_info_writer.name,
            'EmptyAttribute'))
        cqueue.put(ci4)

        ci5 = CheckerItem("cp5")
        dp = PyTango.DeviceProxy(
            self._simps4.new_device_info_writer.name)
        dp.SetState("ALARM")
        ci5.append(TangoDSItem(
            "ds3", self._simps4.new_device_info_writer.name,
            'ScalarDouble'))
        ci5.append(TangoDSItem(
            "ds4", self._simps4.new_device_info_writer.name,
            'ScalarShort'))
        cqueue.put(ci5)

        ci6 = CheckerItem("cp6")
        dp = PyTango.DeviceProxy(
            self._simps4.new_device_info_writer.name)
        dp.CreateAttribute("Position")
        ci6.append(TangoDSItem(
            "ds3", self._simps4.new_device_info_writer.name, None))
        ci6.append(TangoDSItem(
            "ds4", self._simps4.new_device_info_writer.name,
            'ScalarShort'))
        cqueue.put(ci6)

        ci7 = CheckerItem("cp6")
        dp = PyTango.DeviceProxy(self._simps.new_device_info_writer.name)
        dp.CreateAttribute("Position")
        ci7.append(TangoDSItem(
            "ds3", self._simps.new_device_info_writer.name, None))
        ci7.append(TangoDSItem(
            "ds4", self._simps.new_device_info_writer.name, 'ScalarShort'))
        cqueue.put(ci7)

        ci8 = CheckerItem("cp8")
        dp = PyTango.DeviceProxy(self._simps2.new_device_info_writer.name)
        dp.SetState("FAULT")
        ci8.append(TangoDSItem("ds3", self._simps2.new_device_info_writer.name,
                               'ScalarDouble'))
        ci8.append(TangoDSItem("ds4", self._simps2.new_device_info_writer.name,
                               'ScalarShort'))
        cqueue.put(ci8)

        ci9 = CheckerItem("cp9")
        ci9.append(TangoDSItem(
            "ds3", self._simpsoff.new_device_info_writer.name,
            'ScalarDouble'))
        ci9.append(TangoDSItem(
            "ds4", self._simpsoff.new_device_info_writer.name,
            'ScalarShort'))
        cqueue.put(ci9)

        el.run()

        self.assertTrue(ci0.message is not None)
        self.assertEqual(ci0.errords, 'ds0')
        self.assertTrue(not ci0.active)
        self.assertTrue(ci1.message is not None)
        self.assertEqual(ci1.errords, 'ds1')
        self.assertTrue(not ci1.active)
        self.assertEqual(ci2.errords, None)
        self.assertEqual(ci2.message, None)
        self.assertTrue(ci2.active)
        self.assertEqual(ci3.errords, None)
        self.assertEqual(ci3.message, None)
        self.assertTrue(ci3.active)
        self.assertEqual(ci4.errords, "ds4")
        self.assertEqual(ci4.message, 'Empty Attribute')
        self.assertTrue(not ci4.active)
        self.assertEqual(ci5.errords, "ds4")
        self.assertEqual(ci5.message, 'ALARM_STATE')
        self.assertTrue(ci5.active)
        self.assertEqual(ci6.errords, "ds4")
        self.assertEqual(ci6.message, 'ALARM_STATE')
        self.assertTrue(ci6.active)
        self.assertEqual(ci7.errords, None)
        self.assertEqual(ci7.message, None)
        self.assertTrue(ci7.active, None)
        self.assertEqual(ci8.errords, "ds3")
        self.assertEqual(ci8.message, 'FAULT STATE')
        self.assertTrue(not ci8.active)
        self.assertEqual(ci9.errords, "ds3")
        self.assertTrue(ci9.message is not None)
        self.assertTrue(not ci9.active)

        ATTRIBUTESTOCHECK[:] = matt
Ejemplo n.º 36
0
    def __init__(self, attr=None, pytango_dev_attr=None, config=None):
        # config parameter is kept for backwards compatibility only
        TaurusAttrValue.__init__(self)
        if config is not None:
            from taurus.core.util.log import deprecated

            deprecated(dep='"config" kwarg', alt='"attr"', rel="4.0")
            attr = config
        if attr is None:
            self._attrRef = None
        else:
            self._attrRef = weakref.proxy(attr)
        self.config = self._attrRef  # bck-compat

        self._pytango_dev_attr = p = pytango_dev_attr
        if p is None:
            self._pytango_dev_attr = p = PyTango.DeviceAttribute()
            return

        if self._attrRef is None:
            return

        numerical = PyTango.is_numerical_type(self._attrRef._tango_data_type, inc_array=True)
        if p.has_failed:
            self.error = PyTango.DevFailed(*p.get_err_stack())
        else:
            if p.is_empty:  # spectra and images can be empty without failing
                dtype = FROM_TANGO_TO_NUMPY_TYPE.get(self._attrRef._tango_data_type)
                if self._attrRef.data_format == DataFormat._1D:
                    shape = (0,)
                elif self._attrRef.data_format == DataFormat._2D:
                    shape = (0, 0)
                p.value = numpy.empty(shape, dtype=dtype)
                if not (numerical or self._attrRef.type == DataType.Boolean):
                    # generate a nested empty list of given shape
                    p.value = []
                    for _ in xrange(len(shape) - 1):
                        p.value = [p.value]

        rvalue = p.value
        wvalue = p.w_value
        if numerical:
            units = self._attrRef._units
            if rvalue is not None:
                rvalue = Quantity(rvalue, units=units)
            if wvalue is not None:
                wvalue = Quantity(wvalue, units=units)
        elif isinstance(rvalue, PyTango._PyTango.DevState):
            rvalue = DevState[str(rvalue)]
        elif p.type == PyTango.CmdArgType.DevUChar:
            if self._attrRef.data_format == DataFormat._0D:
                rvalue = chr(rvalue)
                wvalue = chr(wvalue)
            else:
                rvalue = rvalue.view("S1")
                wvalue = wvalue.view("S1")

        self.rvalue = rvalue
        self.wvalue = wvalue
        self.time = p.time  # TODO: decode this into a TaurusTimeVal
        self.quality = quality_from_tango(p.quality)
Ejemplo n.º 37
0
    def read_RegularFileCounter(self, the_att):
        self.info_stream("read_RegularFileCounter")
        the_att.set_value(self.attr_regular)

    def is_RegularFileCounter_allowed(self, req_type):
        return self.get_state() in (PyTango.DevState.ON,)

    def read_WarningFileCounter(self, the_att):
        self.info_stream("read_WarningFileCounter")
        the_att.set_value(self.attr_warning)

    def is_WarningFileCounter_allowed(self, req_type):
        return self.get_state() in (PyTango.DevState.ON,)

    def read_FailedFileCounter(self, the_att):
        self.info_stream("read_FailedFileCounter")
        the_att.set_value(self.attr_failed)

    def is_FailedFileCounter_allowed(self, req_type):
        return self.get_state() in (PyTango.DevState.ON,)


# 1- blocco di partenza di un device Tango
if __name__ == '__main__':
    util = PyTango.Util(sys.argv)
    util.add_class(txtImporterClass, txtImporter)

    U = PyTango.Util.instance()
    U.server_init()
    U.server_run()
Ejemplo n.º 38
0
 def isFloat(self, inc_array=False):
     tgtype = self._tango_data_type
     return PyTango.is_float_type(tgtype, inc_array=inc_array)
Ejemplo n.º 39
0
 def getAttributeProxy(self):
     """Convenience method that creates and returns a PyTango.AttributeProxy
     object"""
     return PyTango.AttributeProxy(self.getFullName())
Ejemplo n.º 40
0
    def __init__(self, attr=None, pytango_dev_attr=None, config=None):
        # config parameter is kept for backwards compatibility only
        TaurusAttrValue.__init__(self)
        if config is not None:
            from taurus.core.util.log import deprecated
            deprecated(dep='"config" kwarg', alt='"attr"', rel='4.0')
            attr = config
        if attr is None:
            self._attrRef = None
        else:
            self._attrRef = weakref.proxy(attr)
        self.config = self._attrRef  # bck-compat

        self._pytango_dev_attr = p = pytango_dev_attr
        if p is None:
            self._pytango_dev_attr = p = PyTango.DeviceAttribute()
            return

        if self._attrRef is None:
            return

        numerical = PyTango.is_numerical_type(self._attrRef._tango_data_type,
                                              inc_array=True)
        if p.has_failed:
            self.error = PyTango.DevFailed(*p.get_err_stack())
        else:
            if p.is_empty:  # spectra and images can be empty without failing
                dtype = FROM_TANGO_TO_NUMPY_TYPE.get(
                    self._attrRef._tango_data_type)
                if self._attrRef.data_format == DataFormat._1D:
                    shape = (0, )
                elif self._attrRef.data_format == DataFormat._2D:
                    shape = (0, 0)
                p.value = numpy.empty(shape, dtype=dtype)
                if not (numerical or self._attrRef.type == DataType.Boolean):
                    # generate a nested empty list of given shape
                    p.value = []
                    for _ in xrange(len(shape) - 1):
                        p.value = [p.value]

        rvalue = p.value
        wvalue = p.w_value
        if numerical:
            units = self._attrRef._units
            if rvalue is not None:
                rvalue = Quantity(rvalue, units=units)
            if wvalue is not None:
                wvalue = Quantity(wvalue, units=units)
        elif isinstance(rvalue, PyTango._PyTango.DevState):
            rvalue = DevState[str(rvalue)]
        elif p.type == PyTango.CmdArgType.DevUChar:
            if self._attrRef.data_format == DataFormat._0D:
                rvalue = chr(rvalue)
                wvalue = chr(wvalue)
            else:
                rvalue = rvalue.view('S1')
                wvalue = wvalue.view('S1')

        self.rvalue = rvalue
        self.wvalue = wvalue
        self.time = p.time  # TODO: decode this into a TaurusTimeVal
        self.quality = quality_from_tango(p.quality)
Ejemplo n.º 41
0
        if parameters is None:
            parameters = self._parameters
        if command is None:
            command = self._command
        if dev is None:
            dev = self.getModelObj()

        try:
            param_type = dev.command_query(command).in_type
        except Exception, e:
            self.warning(
                'Cannot get parameters info for command %s:%s' % (command, str(e)))
            return parameters
        if param_type == PyTango.CmdArgType.DevVoid:
            return None
        if PyTango.is_int_type(param_type, True):
            cast_type = int
        elif PyTango.is_float_type(param_type, True):
            cast_type = float
        elif param_type == PyTango.CmdArgType.DevVarStringArray or param_type == PyTango.CmdArgType.DevString:
            cast_type = str
        elif param_type == PyTango.CmdArgType.DevVarBooleanArray or param_type == PyTango.CmdArgType.DevBoolean:
            cast_type = bool
        else:
            self.info(
                'Unsupported parameters type (%s). Casting to "str"' % str(param_type))
            cast_type = str
        if PyTango.is_scalar_type(param_type):
            if parameters:
                return cast_type(parameters[0])
            else: