def addControllerComboItems(self):
     db = Database()
     items = [""]
     items.extend(db.get_device_exported("*/elotech*").value_string)
     items.extend(db.get_device_exported("*/bestec*").value_string)
     self.controllerCombo.addItems(
         sorted(i for i in items if not i.startswith("dserver")))
Esempio n. 2
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
 def addPressureComboItems(self):
     db = Database()
     items = [""]
     items.extend(db.get_device_exported("*/vgct*").value_string)
     items.extend(db.get_device_exported("*/mks*").value_string)
     self.pressureCombo.addItems(
         sorted(i for i in items if not i.startswith("dserver")))
Esempio n. 4
0
def getSubDevice(filter):
    exportedDevices = dict()
    db = Database()
    eDevices = db.get_device_exported(filter).value_string
    for eDevice in eDevices:
        sd = db.get_device_property(eDevice, "__SubDevices")["__SubDevices"]
        for s in sd:
            exportedDevices[s] = eDevice
    return exportedDevices
def create_device(ctrl, addr, axis):
    db = Database()
    new_device_info_mcc = DbDevInfo()
    new_device_info_mcc._class = "PhytronMcc2"
    new_device_info_mcc.server = "PhytronMcc2/raspi14"

    new_device = NAME + ctrl + '_' + addr + '_' + axis

    print("Creating device: %s" % new_device)
    new_device_info_mcc.name = new_device
    db.add_device(new_device_info_mcc)
    return (new_device)
Esempio n. 6
0
 def setUpClass(cls):
     cls.db = Database()
     cls.add_devices()
     sleep(2)
     for device_server in cls.REQUIRED_DEVICE_SERVERS:
         cls.start_device_server(device_server)
     sleep(2)
Esempio n. 7
0
 def generate_db_file(self, server, instance, device,
                      tangoclass=None, properties={}):
     """Generate a database file corresponding to the given arguments."""
     if not tangoclass:
         tangoclass = server
     # Open the file
     with open(self.db, 'w') as f:
         f.write("/".join((server, instance, "DEVICE", tangoclass)))
         f.write(': "' + device + '"\n')
     # Create database
     db = Database(self.db)
     # Patched the property dict to avoid a PyTango bug
     patched = dict((key, value if value != '' else ' ')
                    for key, value in properties.items())
     # Write properties
     db.put_device_property(device, patched)
     return db
Esempio n. 8
0
def append_device_to_db_file(server,
                             instance,
                             device,
                             db_file_name,
                             tangoclass=None,
                             properties={}):
    """Generate a database file corresponding to the given arguments."""
    if not tangoclass:
        tangoclass = server
    # Open the file
    with open(db_file_name, 'a') as f:
        f.write("/".join((server, instance, "DEVICE", tangoclass)))
        f.write(': "' + device + '"\n')
    # Create database
    db = Database(db_file_name)
    # Patched the property dict to avoid a PyTango bug
    patched = dict((key, value if value != '' else ' ')
                   for key, value in properties.items())
    # Write properties
    db.put_device_property(device, patched)
    return db
Esempio n. 9
0
    def __init__(self, host=None, port=None, parent=None):
        if host is None or port is None:
            try:
                _hp = TangoAuthority.get_default_tango_host()
                host, port = _hp.rsplit(':', 1)
            except Exception:
                from taurus import warning
                warning("Error getting default Tango host")

        # Set host to fqdn
        host = socket.getfqdn(host)

        self.dbObj = Database(host, port)
        self._dbProxy = None
        self._dbCache = None

        complete_name = "tango://%s:%s" % (host, port)
        self.call__init__(TaurusAuthority, complete_name, parent)

        try:
            self.get_class_for_device(self.dev_name())
        except:
            # Ok, old tango database.
            self.get_class_for_device = self.__get_class_for_device
Esempio n. 10
0
 def __init__(self, *args, **kwargs):
     super(Memorised, self).__init__(*args, **kwargs)
     self._tangodb = Database()
     self._storeValue = {}
     self._recoverValue = {}
Esempio n. 11
0
class Memorised(_LinacFeature):

    _storeValue = None
    _recoverValue = None

    def __init__(self, *args, **kwargs):
        super(Memorised, self).__init__(*args, **kwargs)
        self._tangodb = Database()
        self._storeValue = {}
        self._recoverValue = {}

    def __str__(self):
        if self.owner.alias:
            name = "%s (Memorised)" % self.owner.alias
        else:
            name = "%s (Memorised)" % self.owner.name
        return name

    def __repr__(self):
        content = ""
        if len(self._recoverValue) > 0:
            content = "%s\n\tRecover:" % (content)
            for key in self._recoverValue:
                content = "%s %s:%s" % (content, key, self._recoverValue[key])
        if len(self._storeValue) > 0:
            content = "%s \n\tStore:" % (content)
            for key in self._storeValue:
                content = "%s %s:%s" % (content, key, self._storeValue[key])
        return "%s%s" % (self.__str__(), content)

    def store(self, value, suffix=None):
        if self._owner is None or self._owner.device is None:
            self.warning("Cannot memorise values %soutside a "
                         "tango device server"
                         % ("for %s " % self._owner.alias
                            if self._owner.alias is not None else ""))
            return False
        devName = self._owner.device.get_name()
        attrName = self._owner.alias or self._owner.name
        fieldName = suffix or defaultFieldName
        memorisedName = devName+"/"+attrName
        self.info("Memorising attribute %s%s with value %s"
                  % (attrName, "_%s" % suffix if suffix else "", value))
        try:
            self._tangodb.put_device_attribute_property(memorisedName,
                                                        {attrName:
                                                         {fieldName:
                                                          str(value)}})
            self.info("put_device_attribute_property(%s,{%s:{%s:%s}})"
                      % (memorisedName, attrName, fieldName, str(value)))
        except Exception as e:
            self.warning("Property %s_%s cannot be stored due to: %s"
                         % (attrName, "_%s" % suffix if suffix else "", e))
            return False
        self._storeValue[fieldName] = value
        return True

    def recover(self, suffix=None):
        """
            Recover the value from the tangoDB
        """
        if self._owner is None or self._owner.device is None:
            self.warning("Cannot recover memorised values %soutside a "
                         "tango device server"
                         % ("for %s " % self._owner.alias
                            if self._owner.alias is not None else ""))
            return False
        devName = self._owner.device.get_name()
        attrName = self._owner.alias or self._owner.name
        fieldName = suffix or defaultFieldName
        memorisedName = devName+"/"+attrName
        try:
            property = self._tangodb.\
                get_device_attribute_property(memorisedName, [attrName])
            if attrName in property and fieldName in property[attrName]:
                try:
                    value = literal_eval(property[attrName][fieldName][0])
                except:
                    value = property[attrName][fieldName][0]
                self.info("Recovered %r as %s" % (value, type(value)))
            else:
                self.info("Nothing to recover from %s%s"
                          % (attrName, "_%s" % suffix if suffix else ""))
                return False
        except Exception as e:
            self.warning("Property %s%s couldn't be recovered due to: %s"
                         % (attrName, "_%s" % suffix if suffix else "", e))
        else:
            self.info("Recovering memorised value %r for %s%s"
                      % (value, attrName, "_%s" % suffix if suffix else ""))
            if hasattr(self, fieldName):
                self._applyValue(attrName, value, fieldName)
            else:
                self._applyValue(attrName, value)
        self._recoverValue[fieldName] = value
        return True

    def _applyValue(self, attrName, value, field=None, check=True,
                    silent=False):
        if field is None:
            for fieldCandidate in ['wvalue', 'rvalue']:
                if self._applyValue(attrName, value, field=fieldCandidate,
                                    check=check, silent=True):
                    self.info("Applied %s to %s[%s]" % (str(value), attrName,
                                                        fieldCandidate))
                    return True
            self.error("Unknown field candidate to apply %s to %s"
                       % (str(value), attrName))
        try:
            dct = self._owner.__class__.__dict__
            if dct[field] is not None:
                dct[field].fset(self._owner, value)
                if check:
                    readback = dct[field].fget(self._owner)
                    if value != readback:
                        if not silent:
                            self.warning("readback %s doesn't corresponds "
                                         "with set %s" % (value, readback))
                return True
        except Exception as e:
            if not silent:
                self.error("Exception applying %s[%s]: %s -> %s(%s)"
                           % (attrName, field, value, type(e).__name__, e))
        return False

    def getStoreValue(self, suffix=None):
        if not suffix:
            if defaultFieldName in self._storeValue:
                return self._storeValue[defaultFieldName]
        else:
            if suffix in self._storeValue:
                return self._storeValue[suffix]
        # other case return None

    def getRecoverValue(self, suffix=None):
        if not suffix:
            if defaultFieldName in self._recoverValue:
                return self._recoverValue[defaultFieldName]
        else:
            if suffix in self._recoverValue:
                return self._recoverValue[suffix]
from PyTango import Database, DbDevInfo

#  A reference on the DataBase
db = Database()

# The devices name we want to create
new_device_name = "PIStageTango/ktof/pi_stage/test/c413test"

# Define the Tango Class served by this  DServer
new_device_info_stage = DbDevInfo()
new_device_info_stage._class = "linear Stage"
new_device_info_stage.server = "TangoTest"

# add the device
print("Creating device: %s" % new_device_name)
new_device_info_stage.name = new_device_name
db.add_device(new_device_info_stage)
Esempio n. 13
0
from PyTango import Database, DbDevInfo

#  A reference on the DataBase
db = Database()

new_device_name1 = "C3/unity/eras1"

# Define the Tango Class served by this  DServer
new_device_info_mouse = DbDevInfo()
new_device_info_mouse._class = "PyTracker"
new_device_info_mouse.server = "tango_pygame/eras1"  #servername/instance

# add the first device
print("Creating device: %s" % new_device_name1)
new_device_info_mouse.name = new_device_name1
db.add_device(new_device_info_mouse)
Esempio n. 14
0
from PyTango import Database, DbDevInfo

# A reference on the Database
db = Database()

# Define device name
new_device_name = "test/tpm_board/1"

# Define the Tango Class served by this DServer
dev_info = DbDevInfo()
dev_info._class = "TPM_DS"
dev_info.server = "TPM_DS/test"

# add the device
dev_info.name = new_device_name
print("Creating device: %s" % new_device_name)
db.add_device(dev_info)



# SECOND DEVICE
# Define device name
new_device_name = "test/tpm_board/2"

# Define the Tango Class served by this DServer
dev_info = DbDevInfo()
dev_info._class = "TPM_DS"
dev_info.server = "TPM_DS/test"

# add the device
dev_info.name = new_device_name
Esempio n. 15
0
def prepare_logstash(args):
    """Prepare logstash handler based on the configuration stored in the Tango
    database.

    :param args: process execution arguments
    :type args: list<str>

    .. note::
        The prepare_logstash function has been included in Sardana
        on a provisional basis. Backwards incompatible changes
        (up to and including its removal) may occur if
        deemed necessary by the core developers.
    """
    log_messages = []

    try:
        from logstash_async.handler import AsynchronousLogstashHandler
    except ImportError:
        msg = ("Unable to import logstash_async. Skipping logstash " +
               "configuration...", )
        log_messages.append(msg, )
        return log_messages

    def get_logstash_conf(dev_name):
        try:
            props = db.get_device_property(dev_name, "LogstashHost")
            host = props["LogstashHost"][0]
        except IndexError:
            host = None
        try:
            props = db.get_device_property(dev_name, "LogstashPort")
            port = int(props["LogstashPort"][0])
        except IndexError:
            port = None
        try:
            props = db.get_device_property(dev_name, "LogstashCacheDbPath")
            cache_db_path = props["LogstashCacheDbPath"][0]
        except IndexError:
            cache_db_path = None
        return host, port, cache_db_path

    db = Database()

    bin_name = args[0]
    try:
        instance_name = args[1]
    except IndexError:
        msg = ("Unknown %s instance name. " % bin_name +
               "Skipping logstash configuration...")
        log_messages.append(msg, )
        return log_messages
    server_name = bin_name + "/" + instance_name
    if bin_name in ["Pool", "MacroServer"]:
        class_name = bin_name
        dev_name = get_dev_from_class_server(db, class_name, server_name)[0]
        host, port, cache = get_logstash_conf(dev_name)
    else:
        dev_name = get_dev_from_class_server(db, "Pool", server_name)[0]
        host, port, cache = get_logstash_conf(dev_name)
        if host is None:
            dev_name = get_dev_from_class_server(db, "MacroServer",
                                                 server_name)[0]
            host, port, cache = get_logstash_conf(dev_name)

    if host is not None:
        root = Logger.getRootLog()
        handler = AsynchronousLogstashHandler(host, port, database_path=cache)
        # don't use full path for program_name
        handler._create_formatter_if_necessary()
        _, handler.formatter._program_name = os.path.split(
            handler.formatter._program_name)
        root.addHandler(handler)
        msg = ("Log is being sent to logstash listening on %s:%d", host, port)
        log_messages.append(msg)

    return log_messages
Esempio n. 16
0
from PyTango import Database, DbDevInfo
import os, signal

# A reference on the Database
db = Database()

# Kill running servers
# Get device info of Tile
try:
    dev_info = db.get_device_info('test/tile/1')
    if dev_info.pid != 0:
       os.kill(dev_info.pid, signal.SIGTERM)  #o r signal.SIGKILL
    print "Killed PID: %s" % dev_info.pid
except Exception as ex:
    print "No process to kill for test/tile/1"

#get device info of ObsConf
try:
    dev_info = db.get_device_info('test/obsconf/1')
    if dev_info.pid != 0:
       os.kill(dev_info.pid, signal.SIGTERM)  #o r signal.SIGKILL
    print "Killed PID: %s" % dev_info.pid
except Exception as ex:
    print "No process to kill for test/obsconf/1"

#get device info of TPM
try:
    dev_info = db.get_device_info('test/tpm_board/1')
    if dev_info.pid != 0:
       os.kill(dev_info.pid, signal.SIGTERM)
    print "Killed PID: %s" % dev_info.pid
Esempio n. 17
0
class MgConf:
    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

    def findMasterTimer(self):
        if not HasyUtils.versionSardanaNewMg():
            self.findMasterTimerD8()
        else:
            self.findMasterTimerD9()

    def findMasterTimerD8(self):
        for ctrl in self.hsh[u'controllers']:
            Channels = self.hsh[u'controllers'][ctrl][u'units'][u'0'][
                u'channels']
            for chan in Channels:
                if chan.find('dgg2') > 0:
                    temp = chan
                    if temp.find('0000') >= 0:
                        lst = temp.split("/")
                        temp = "/".join(lst[1:])
                    masterTimer = self.db.get_alias(str(temp))
                    return masterTimer
        raise ('MgUtils.findMasterTimer', "No timer found")

    def findMasterTimerD9(self):

        temp = self.hsh[u'timer']
        if temp.find('0000') >= 0:
            lst = temp.split("/")
            #
            # tango://haso113u.desy.de:10000/expchan/dgg2_d1_01/1
            #
            if lst[0].lower() == 'tango:':
                temp = "/".join(lst[3:])
            else:
                temp = "/".join(lst[1:])
            #
            # expchan/dgg2_d1_01/1
            #
            masterTimer = self.db.get_alias(str(temp))
        return masterTimer

    def findDeviceController(self, device):
        """
        returns the controller that belongs to a device
        """

        lst = []
        if self.poolMg.ExpChannelList is not None:
            lst = self.poolMg.ExpChannelList
        ctrl = None
        for elm in lst:
            chan = json.loads(elm)
            # chan:
            # {
            # u'axis': 17,
            # u'controller':
            # u'haso107klx:10000/controller/sis3820ctrl/sis3820_exp',
            # u'full_name': u'haso107klx:10000/expchan/sis3820_exp/17',
            # u'id': 146,
            # u'instrument': u'',
            # u'interfaces': [u'Object', u'PoolObject', u'Element',
            # u'ExpChannel', u'PoolElement', u'CTExpChannel', u'Acquirable'],
            # u'manager': u'exp_pool01',
            # u'name': u'exp_c17',
            # u'parent': u'sis3820_exp',
            # u'pool': u'exp_pool01',
            # u'source': u'haso107klx:10000/expchan/sis3820_exp/17/value',
            # u'type': u'CTExpChannel',
            # u'unit': u'0',
            # }
            if device == chan['name']:
                ctrl = chan['controller']
                break
        if ctrl is None and device.find("adc") >= 0:
            ctrl = os.getenv("TANGO_HOST") + "/" + \
                "controller/hasylabadcctrl/hasyadcctrl"
        elif ctrl is None and device.find("vfc") >= 0:
            ctrl = os.getenv("TANGO_HOST") + "/" + \
                "controller/vfcadccontroller/hasyvfcadcctrl"
        return ctrl

    def findFullDeviceName(self, device):
        """
          input: exp_c01
          returns: expchan/hasylabvirtualcounterctrl/1
        """

        lst = self.poolMg.AcqChannelList
        argout = None
        for elm in lst:
            chan = json.loads(elm)
            if device == chan['name']:
                #
                # from: expchan/hasysis3820ctrl/1/value
                # to:   expchan/hasysis3820ctrl/1
                #
                arr = chan['full_name'].split("/")
                argout = "/".join(arr[0:-1])
        if argout is None:
            print("Error with device")
            print(device)
            raise Exception('MgUtils.findFullDeviceName, %s' % device,
                            "failed to find  %s" % device)
        return argout

    def updateConfiguration(self):
        """
        json-dump the dictionary self.hsh to the Mg configuration
        """
        self.mg.Configuration = json.dumps(self.hsh)

    def addTimer(self, device):
        if not HasyUtils.versionSardanaNewMg():
            self.addTimerD8(device)
        else:
            self.addTimerD9(device)

    def addTimerD8(self, device):
        """
        add a timer to the Mg
        device: exp_t01
        """
        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            self.masterTimer = device
            self.hsh[u'monitor'] = self.findFullDeviceName(device)
            self.hsh[u'timer'] = self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'units'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'monitor'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'timer'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'units'][u'0'][
            u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            print("adding index", self.index, device)
            dct = {}
            dct[u'_controller_name'] = str(ctrl)
            dct[u'_unit_id'] = u'0'
            dct[u'conditioning'] = u''
            dct[u'data_type'] = u'float64'
            dct[u'data_units'] = u'No unit'
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'instrument'] = None
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 0
            dct[u'nexus_path'] = u''
            dct[u'normalization'] = 0
            dct[u'output'] = True
            dct[u'plot_axes'] = []
            dct[u'plot_type'] = 0
            dct[u'shape'] = []
            dct[u'source'] = dct['full_name'] + "/value"
            ctrlChannels[fullDeviceName] = dct

    def addTimerD9(self, device):
        """
        add a timer to the Mg
        device: exp_t01
        """
        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            self.masterTimer = device
            self.hsh[u'monitor'] = self.findFullDeviceName(device)
            self.hsh[u'timer'] = self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'synchronizer'] = "software"
            self.hsh[u'controllers'][ctrl][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'monitor'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'timer'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            print("adding index", self.index, device)
            dct = {}
            dct[u'conditioning'] = u''
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 0
            dct[u'normalization'] = 0
            dct[u'output'] = True
            dct[u'plot_axes'] = []
            dct[u'plot_type'] = 0
            dct[u'source'] = dct['full_name'] + "/value"
            ctrlChannels[fullDeviceName] = dct

    def addExtraTimer(self, device):
        if not HasyUtils.versionSardanaNewMg():
            self.addExtraTimerD8(device)
        else:
            self.addExtraTimerD9(device)

    #
    # add an extra timer to the measurement group
    #
    def addExtraTimerD8(self, device):
        """ device: exp_t01"""
        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'units'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'monitor'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'timer'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'units'][u'0'][
            u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            dct = {}
            dct[u'_controller_name'] = str(ctrl)
            dct[u'_unit_id'] = u'0'
            dct[u'conditioning'] = u''
            dct[u'data_type'] = u'float64'
            dct[u'data_units'] = u'No unit'
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'instrument'] = None
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 0
            dct[u'nexus_path'] = u''
            dct[u'normalization'] = 0
            dct[u'output'] = True
            dct[u'plot_axes'] = []
            dct[u'plot_type'] = 0
            dct[u'shape'] = []
            dct[u'source'] = dct['full_name'] + "/value"
            ctrlChannels[fullDeviceName] = dct

    #
    # add an extra timer to the measurement group
    #
    def addExtraTimerD9(self, device):
        """ device: exp_t01"""
        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'synchronizer'] = "software"
            self.hsh[u'controllers'][ctrl][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'monitor'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'timer'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            dct = {}
            dct[u'conditioning'] = u''
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 0
            dct[u'normalization'] = 0
            dct[u'output'] = True
            dct[u'plot_axes'] = []
            dct[u'plot_type'] = 0
            dct[u'source'] = dct['full_name'] + "/value"
            ctrlChannels[fullDeviceName] = dct

    def addCounter(self, device, flagDisplay, flagOutput):
        if not HasyUtils.versionSardanaNewMg():
            self.addCounterD8(device, flagDisplay, flagOutput)
        else:
            self.addCounterD9(device, flagDisplay, flagOutput)

    #
    # add a counter to the measurement group
    #
    def addCounterD8(self, device, flagDisplay, flagOutput):

        if device.find('sca_') == 0:
            return self.addSCA(device, flagDisplay, flagOutput)

        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            print("MgUtils.addCounter adding controller ", ctrl)
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'units'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'monitor'] = \
                self.findFullDeviceName(self.masterTimer)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'timer'] = \
                self.findFullDeviceName(self.masterTimer)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'units'][u'0'][
            u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            print("adding index", self.index, device)
            dct = {}
            dct[u'_controller_name'] = str(ctrl)
            dct[u'_unit_id'] = u'0'
            dct[u'conditioning'] = u''
            dct[u'data_type'] = u'float64'
            dct[u'data_units'] = u'No unit'
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'instrument'] = u''
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 0
            dct[u'nexus_path'] = u''
            dct[u'normalization'] = 0
            if flagOutput:
                dct[u'output'] = True
            else:
                dct[u'output'] = False
            dct[u'plot_axes'] = [u'<mov>']
            if flagDisplay:
                dct[u'plot_type'] = 1
            else:
                dct[u'plot_type'] = 0
            dct[u'shape'] = []
            dct[u'source'] = dct['full_name'] + "/value"
            ctrlChannels[fullDeviceName] = dct

    #
    # add a counter to the measurement group
    #
    def addCounterD9(self, device, flagDisplay, flagOutput):

        if device.find('sca_') == 0:
            return self.addSCA(device, flagDisplay, flagOutput)

        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            print("MgUtils.addCounter adding controller ", ctrl)
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'synchronizer'] = "software"
            self.hsh[u'controllers'][ctrl][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'monitor'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'timer'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            print("adding index", self.index, device)
            dct = {}
            dct[u'conditioning'] = u''
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 0
            dct[u'normalization'] = 0
            if flagOutput:
                dct[u'output'] = True
            else:
                dct[u'output'] = False
            dct[u'plot_axes'] = [u'<mov>']
            if flagDisplay:
                dct[u'plot_type'] = 1
            else:
                dct[u'plot_type'] = 0
            dct[u'source'] = dct['full_name'] + "/value"
            ctrlChannels[fullDeviceName] = dct

    def addMCA(self, device):
        if not HasyUtils.versionSardanaNewMg():
            self.addMCAD8(device)
        else:
            self.addMCAD9(device)

    #
    # add a MCA to the measurement group
    #
    def addMCAD8(self, device):
        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            print("MgUtils.addMCA adding controller ", ctrl)
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'units'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'monitor'] = \
                self.findFullDeviceName(self.masterTimer)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'timer'] = \
                self.findFullDeviceName(self.masterTimer)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'units'][u'0'][
            u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            print("adding index", self.index, device)
            proxy = DeviceProxy(str(fullDeviceName))
            dct = {}
            dct[u'_controller_name'] = str(ctrl)
            dct[u'_unit_id'] = u'0'
            dct[u'conditioning'] = u''
            dct[u'data_type'] = u'float64'
            dct[u'data_units'] = u'No unit'
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'instrument'] = None
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 1
            dct[u'nexus_path'] = u''
            dct[u'normalization'] = 0
            dct[u'output'] = True
            dct[u'plot_axes'] = []
            dct[u'plot_type'] = 0
            dct[u'shape'] = [proxy.DataLength]
            dct[u'source'] = fullDeviceName + "/Value"
            ctrlChannels[fullDeviceName] = dct

    #
    # add a MCA to the measurement group
    #
    def addMCAD9(self, device):
        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            print("MgUtils.addMCA adding controller ", ctrl)
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'synchronizer'] = "software"
            self.hsh[u'controllers'][ctrl][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'monitor'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'timer'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            print("adding index", self.index, device)
            # proxy =
            DeviceProxy(str(fullDeviceName))
            dct = {}
            dct[u'conditioning'] = u''
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 1
            dct[u'normalization'] = 0
            dct[u'output'] = True
            dct[u'plot_axes'] = [u'<mov>']
            dct[u'plot_type'] = 0
            dct[u'source'] = fullDeviceName + "/Value"
            ctrlChannels[fullDeviceName] = dct

    def addPilatus(self, device):
        if not HasyUtils.versionSardanaNewMg():
            self.addPilatusD8(device)
        else:
            self.addPilatusD9(device)

    #
    # add a MCA to the measurement group
    #
    def addPilatusD8(self, device):
        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            print("MgUtils.addPilatus adding controller ", ctrl)
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'units'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'monitor'] = \
                self.findFullDeviceName(self.masterTimer)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'timer'] = \
                self.findFullDeviceName(self.masterTimer)
            self.hsh[u'controllers'][ctrl][u'units'][u'0'][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'units'][u'0'][
            u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            print("adding index", self.index, device)
            # proxy =
            DeviceProxy(str(fullDeviceName))
            dct = {}
            dct[u'_controller_name'] = str(ctrl)
            dct[u'_unit_id'] = u'0'
            dct[u'conditioning'] = u''
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'instrument'] = u''
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 2
            dct[u'nexus_path'] = u''
            dct[u'normalization'] = 0
            dct[u'output'] = True
            dct[u'plot_axes'] = []
            dct[u'plot_type'] = 0
            dct[u'source'] = fullDeviceName + "/Value"
            ctrlChannels[fullDeviceName] = dct

    #
    # add a Pilatus to the measurement group
    #
    def addPilatusD9(self, device):
        ctrl = self.findDeviceController(device)
        if ctrl not in self.hsh[u'controllers'].keys():
            print("MgUtils.addPilatus adding controller ", ctrl)
            self.hsh[u'controllers'][ctrl] = {}
            self.hsh[u'controllers'][ctrl][u'synchronizer'] = "software"
            self.hsh[u'controllers'][ctrl][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'monitor'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'timer'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][ctrl][u'channels']
        fullDeviceName = self.findFullDeviceName(device)
        if fullDeviceName not in ctrlChannels.keys():
            print("adding index", self.index, device)
            # proxy =
            DeviceProxy(str(fullDeviceName))
            dct = {}
            dct[u'conditioning'] = u''
            dct[u'enabled'] = True
            dct[u'full_name'] = fullDeviceName
            dct[u'index'] = self.index
            self.index += 1
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 2
            dct[u'normalization'] = 0
            dct[u'output'] = True
            dct[u'plot_axes'] = [u'<mov>']
            dct[u'plot_type'] = 0
            dct[u'source'] = fullDeviceName + "/Value"
            ctrlChannels[fullDeviceName] = dct

    def parseSCA(self, name):
        """
        name: sca_exp_mca01_100_200, returns ['exp_mca01', '100', '200']
        """
        lst = name.split('_')
        return [lst[1] + '_' + lst[2], lst[3], lst[4]]

    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

    def _addSca(self, device):
        """
        Input: device: sca_exp_mca01_100_200
        Returns full controller name, e.g.:
        haso107klx:10000/controller/hasscactrl/sca_exp_mca01_100_200
        Creates a HasySca controller and creates a device for this controller,
        There is only one device per controller
        """
        mca, roiMin, roiMax = self.parseSCA(device)
        #
        # find the tango device name which is used my the sardana device
        #
        tgMca = self._getMcaName(mca)
        #
        # sca_exp_mca01_100_200_ctrl
        #
        ctrlAlias = device + "_ctrl"
        #
        # see whether the controller exists already
        #

        lst = self.poolMg.ControllerList
        ctrlFullName = None
        for elm in lst:
            chan = json.loads(elm)
            if ctrlAlias == chan['name']:
                ctrlFullName = chan['full_name']
                break
        #
        # if the controller does not exist, create it
        #
        proxy = DeviceProxy(tgMca)
        dataLength = proxy.DataLength
        if int(roiMax) >= dataLength:
            raise Exception(
                "MgUtils._addSca %s " % device,
                "roiMax %d  >= datalength %d " %
                (int(roiMax), int(dataLength)))
        if int(roiMin) >= dataLength:
            raise Exception(
                "MgUtils._addSca %s " % device,
                "roiMin %d  >= datalength %d " % (int(roiMin), dataLength))

        if ctrlFullName is None:
            lst = [
                'CTExpChannel', 'HasyScaCtrl.py', 'HasyScaCtrl', ctrlAlias,
                "mca", tgMca, "roi1", roiMin, "roi2", roiMax
            ]
            print("MgUtils._addSca", lst)
            try:
                self.poolMg.CreateController(lst)
            except DevFailed as e:
                Except.print_exception(e)
                # print "failed to get proxy to ", poolName
                sys.exit(255)

            lst = self.poolMg.ControllerList
            for elm in lst:
                chan = json.loads(elm)
                if ctrlAlias == chan['name']:
                    ctrlFullName = chan['full_name']
                    break
        if ctrlFullName is None:
            raise Exception('MgUtils._addSca',
                            "failed to make controller for %s" % device)

        #
        # see whether the SCA device exists
        #
        lst = self.poolMg.ExpChannelList
        flag = False
        for elm in lst:
            chan = json.loads(elm)
            if device == chan['name']:
                flag = True
                break

        if not flag:
            #
            # "CTExpChannel","HasyScaCtrl","1","sca_exp_mca01_100_200"
            #
            lst = ["CTExpChannel", ctrlAlias, "1", device]
            self.poolMg.CreateElement(lst)

        return ctrlFullName

    def makeScaControllerForPseudoCounter(self, device):
        """
        Input: device: sca_exp_mca01_100_200
        Returns full controller name, e.g.:
        haso107klx:10000/controller/mca2scactrl/sca_exp_mca01_100_200_ctrl
        """
        mca, roiMin, roiMax = self.parseSCA(device)

        ctrlAlias = device + "_ctrl"
        #
        # see whether the controller exists already
        #
        lst = self.poolMg.ControllerList
        for elm in lst:
            chan = json.loads(elm)
            if ctrlAlias == chan['name']:
                return chan['full_name']
        lst = [
            'PseudoCounter', 'MCA2SCACtrl.py', 'MCA2SCACtrl', device + "_ctrl",
            'mca=' + self.findFullDeviceName(mca), 'sca=' + device
        ]

        # print "MgUutils.makeSardanaController", lst
        self.poolMg.CreateController(lst)
        #
        # now it has been created.
        # go through the list again an return the full controller name
        #
        lst = self.poolMg.ControllerList
        for elm in lst:
            chan = json.loads(elm)
            if ctrlAlias == chan['name']:
                #
                # set the ROIs
                #
                proxy = DeviceProxy(device)
                proxy.Roi1 = int(roiMin)
                proxy.Roi2 = int(roiMax)
                return chan['full_name']
        raise Exception('MgUtils.makeController',
                        "failed to make controller for %s" % device)

    def addSCA(self, device, flagDisplay, flagOutput):
        if not HasyUtils.versionSardanaNewMg():
            self.addSCAD8(device, flagDisplay, flagOutput)
        else:
            self.addSCAD9(device, flagDisplay, flagOutput)

    def addSCAD8(self, device, flagDisplay, flagOutput):
        """
        add a SCA to the measurement group
          input: device, e.g. sca_exp_mca01_100_200
        """
        if device.find('sca_') != 0:
            print("MgUtils.addSCA: '%s' does not begin with 'sca_'," % device)
            return False

        #
        # there is one element per controller
        #
        fullCtrlName = self._addSca(device)
        if fullCtrlName not in self.hsh[u'controllers'].keys():
            print("MgUtils.addSca adding controller ", fullCtrlName)
            self.hsh[u'controllers'][fullCtrlName] = {}
            self.hsh[u'controllers'][fullCtrlName][u'units'] = {}
            self.hsh[u'controllers'][fullCtrlName][u'units'][u'0'] = {}
            self.hsh[u'controllers'][fullCtrlName][u'units'][u'0'][
                u'channels'] = {}
            self.hsh[u'controllers'][fullCtrlName][u'units'][u'0'][u'id'] = 0
            self.hsh[u'controllers'][fullCtrlName][u'units'][u'0'][
                u'monitor'] = self.findFullDeviceName(self.masterTimer)
            self.hsh[u'controllers'][fullCtrlName][u'units'][u'0'][
                u'timer'] = self.findFullDeviceName(self.masterTimer)
            self.hsh[u'controllers'][fullCtrlName][u'units'][u'0'][
                u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][fullCtrlName][u'units'][u'0'][
            u'channels']
        if not self.findFullDeviceName(device) in ctrlChannels.keys():
            print("adding index", self.index, device)
            dct = {}
            dct[u'_controller_name'] = str(fullCtrlName)
            dct[u'_unit_id'] = u'0'
            dct[u'conditioning'] = u''
            dct[u'enabled'] = True
            dct[u'full_name'] = self.findFullDeviceName(device)
            dct[u'index'] = self.index
            self.index += 1
            dct[u'instrument'] = None
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 0
            dct[u'normalization'] = 0
            if flagOutput:
                dct[u'output'] = True
            else:
                dct[u'output'] = False
            dct[u'plot_axes'] = [u'<mov>']
            if flagDisplay:
                dct[u'plot_type'] = 1
            else:
                dct[u'plot_type'] = 0
            dct[u'source'] = dct['full_name'] + "/value"
            ctrlChannels[self.findFullDeviceName(device)] = dct
        return True

    def addSCAD9(self, device, flagDisplay, flagOutput):
        """
        add a SCA to the measurement group
          input: device, e.g. sca_exp_mca01_100_200
        """
        if device.find('sca_') != 0:
            print("MgUtils.addSCA: '%s' does not begin with 'sca_'," % device)
            return False

        #
        # there is one element per controller
        #
        fullCtrlName = self._addSca(device)
        if fullCtrlName not in self.hsh[u'controllers'].keys():
            print("MgUtils.addSca adding controller ", fullCtrlName)
            self.hsh[u'controllers'][fullCtrlName] = {}
            ctrl = fullCtrlName
            self.hsh[u'controllers'][ctrl][u'synchronizer'] = "software"
            self.hsh[u'controllers'][ctrl][u'channels'] = {}
            self.hsh[u'controllers'][ctrl][u'id'] = 0
            self.hsh[u'controllers'][ctrl][u'monitor'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'timer'] = \
                self.findFullDeviceName(device)
            self.hsh[u'controllers'][ctrl][u'trigger_type'] = 0

        ctrlChannels = self.hsh[u'controllers'][fullCtrlName][u'channels']
        if not self.findFullDeviceName(device) in ctrlChannels.keys():
            print("adding index", self.index, device)
            dct = {}
            dct[u'conditioning'] = u''
            dct[u'enabled'] = True
            dct[u'full_name'] = self.findFullDeviceName(device)
            dct[u'index'] = self.index
            self.index += 1
            dct[u'label'] = str(device)
            dct[u'name'] = str(device)
            dct[u'ndim'] = 0
            dct[u'normalization'] = 0
            if flagOutput:
                dct[u'output'] = True
            else:
                dct[u'output'] = False
            dct[u'plot_axes'] = [u'<mov>']
            if flagDisplay:
                dct[u'plot_type'] = 1
            else:
                dct[u'plot_type'] = 0
            dct[u'source'] = dct['full_name'] + "/value"
            ctrlChannels[self.findFullDeviceName(device)] = dct
        return True
                    default=1,
                    metavar='no_channels')
args = vars(parser.parse_args())

for dev in ['lima', 'xspress3']:
    d = None
    try:
        d = DeviceProxy(args[dev])
    except DevFailed:
        pass

    if d:
        print 'Device aleady exist, skipping'
        exit()

db = Database()

print 'Creating LimaCCDs device'
lima = DbDevInfo()
lima._class = 'LimaCCDs'
lima.server = 'LimaCCDs/{instance}'.format(instance=args['name'])
lima.name = args['lima']
db.add_device(lima)

print 'Creating Xspress3 device'
x3 = DbDevInfo()
x3._class = 'Xspress3'
x3.server = 'LimaCCDs/{instance}'.format(instance=args['name'])
x3.name = args['xspress3']
db.add_device(x3)
Esempio n. 19
0
def prepare_logstash(args):
    """Prepare logstash handler based on the configuration stored in the Tango
    database.

    :param args: process execution arguments
    :type args: list<str>

    .. note::
        The prepare_logstash function has been included in Sardana
        on a provisional basis. Backwards incompatible changes
        (up to and including its removal) may occur if
        deemed necessary by the core developers.
    """
    log_messages = []

    try:
        import logstash
    except ImportError:
        msg = ("Unable to import logstash. Skipping logstash " +
               "configuration...", )
        log_messages.append(msg, )
        return log_messages

    def get_logstash_conf(dev_name):
        try:
            props = db.get_device_property(dev_name, "LogstashHost")
            host = props["LogstashHost"][0]
        except IndexError:
            host = None
        try:
            props = db.get_device_property(dev_name, "LogstashPort")
            port = int(props["LogstashPort"][0])
        except IndexError:
            port = 12345
        return host, port

    db = Database()

    bin_name = args[0]
    instance_name = args[1]
    server_name = bin_name + "/" + instance_name
    if bin_name in ["Pool", "MacroServer"]:
        class_name = bin_name
        dev_name = get_dev_from_class_server(db, class_name, server_name)[0]
        host, port = get_logstash_conf(dev_name)
    else:
        dev_name = get_dev_from_class_server(db, "Pool", server_name)[0]
        host, port = get_logstash_conf(dev_name)
        if host is None:
            dev_name = get_dev_from_class_server(db, "MacroServer",
                                                 server_name)[0]
            host, port = get_logstash_conf(dev_name)

    if host is not None:
        root = Logger.getRootLog()
        handler = logstash.TCPLogstashHandler(host, port, version=1)
        root.addHandler(handler)
        msg = ("Log is being sent to logstash listening on %s:%d", host, port)
        log_messages.append(msg)

    return log_messages
Esempio n. 20
0
 def __init__(self, connector=None, uri=None):
     Camera.__init__(self)
     self.uri = uri
     attributes = [ \
             {"attr": "ExposureAuto", "name": "exposure_time_auto"},
             {"attr": "ExposureAutoMin", "name": "exposure_time_min"},
             {"attr": "ExposureAutoMax", "name": "exposure_time_max"},
             {"attr": "ExposureTimeAbs", "name": "exposure_time"},
             {"attr": "GainAuto", "name": "gain_auto"},
             {"attr": "GainAutoMin", "name": "gain_min"},
             {"attr": "GainAutoMax", "name": "gain_max"},
             {"attr": "Gain", "name": "gain"},
             {"attr": "TriggerSource", "name": "trigger_source"},
             {"attr": "AcquisitionFrameRateAbs", "name": "frame_rate"},
             {"attr": "Width"},
             {"attr": "Height"},
             {"attr": "OffsetX", "name": "offset_x"},
             {"attr": "OffsetY", "name": "offset_y"},
             {"attr": "WidthMax", "name": "width_max"},
             {"attr": "HeightMax", "name": "height_max"},
             {"attr": "Image8", "name": "image_8"},
     ]
     if connector == "simulation":
         attributes.append({"attr": "Image8", "name": "image_8"})
         self.connector = VimbaCameraSimulationConnector(uri, attributes)
         self.connector.write("width", 640)
         self.connector.write("height", 480)
         self.connector.write("width_max", 640)
         self.connector.write("height_max", 480)
         self.connector.image_changed.connect(self.on_image_changed)
     elif connector == "tango":
         #determine gain attribute name
         if -1 < uri.find(":") < uri.find("/"):
             host, port = uri.partition("/")[0].split(":")
             db = Database(host, port)
             gain_prop = db.get_device_property(
                     uri.partition("/")[2], "GainFeatureName")
         else:
             db = Database()
             gain_prop = db.get_device_property(uri, "GainFeatureName")
         if len(gain_prop["GainFeatureName"]) > 0:
             gain_attr = gain_prop["GainFeatureName"][0]
             for attr in attributes:
                 if "name" in attr and attr["name"] == "gain":
                     attr["attr"] = gain_attr
         #setup connector
         self.connector = TangoConnector(uri, attributes)
         #start acquisition in right viewing mode and connect changed signal
         try:
             self.connector.proxy.write_attribute("ViewingMode", 1)
             if self.state(refresh=True) != State.RUNNING:
                 self.connector.proxy.command_inout("StartAcquisition")
             sleep(0.2)
             self.connector.proxy.subscribe_event("image_8", \
                     EventType.DATA_READY_EVENT, \
                     self.on_image_changed, [], False)
         except:
             self.janus.utils["logger"].error(
                     "VimbaCamera(" + self.uri + ").__init__() " +
                     "failed to set viewing mode")
             self.janus.utils["logger"].debug("", exc_info=True)
     self.connector.write("trigger_source", "FixedRate")
     self.connector.write("frame_rate", 10.)
     self.connector.value_changed.connect(self.value_changed.emit)
     self.buffer = None
"""Created Receiving device server class"""
class Receiving(Device):
    __metaclass__ = DeviceMeta

    def init_device(self):
        Device.init_device(self)
        self.set_state(DevState.STANDBY)
        self.debug_stream("Init Receiving Device.")

    @command(dtype_in='DevVarStringArray', dtype_out=None)
    def log(self, details):
        message = details[3]
#        print(message)
        self.debug_stream(message)

"""This part is needed to start device server from command line"""
if '--register' in sys.argv:
    reg_ind = sys.argv.index('--register')
    sys.argv.pop(reg_ind)
    name = sys.argv.pop(reg_ind)
    db = Database()
    dev_info = DbDevInfo()
    dev_info._class = 'Receiving'
    dev_info.server = 'ReceivingDS/logdev'
    dev_info.name = name
    db.add_device(dev_info)
    print("In registration")
else:
    print("Running DS")
    run([Receiving])
Esempio n. 22
0
        }
    },
    'loggers': {
        'aavs.ctl': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
        'aavs.none': {
            'handlers': [],
            'level': 'DEBUG',
        }
    }
}
logging.config.dictConfig(LOGGING)

db = Database()


def setup_tango_config(loaded_config):
    """ Set up tango configuration """
    devices = loaded_config["devices"]
    domain = loaded_config["domain"]
    default_logging_target = loaded_config["default_logging_target"]
    default_logging_level = loaded_config["default_logging_level"]

    for group_name, instances in devices.iteritems():
        for device_id, config in instances.iteritems():

            device_class = config["class"]
            full_device_name = "/".join([domain, group_name, device_id])
            device_server_name = config.get("server", None)
Esempio n. 23
0
def prepare_server(args, tango_args):
    """Register a proper server if the user gave an unknown server"""
    log_messages = []
    _, bin_name = os.path.split(args[0])
    server_name, _ = os.path.splitext(bin_name)

    if "-?" in tango_args:
        return log_messages

    nodb = "-nodb" in tango_args
    if nodb and not hasattr(DeviceClass, "device_name_factory"):
        print "In order to start %s with 'nodb' you need PyTango >= 7.2.3" % server_name
        sys.exit(1)

    if len(tango_args) < 2:
        valid = False
        while not valid:
            inst_name = raw_input("Please indicate %s instance name: " %
                                  server_name)
            # should be a instance name validator.
            valid_set = string.letters + string.digits + '_' + '-'
            out = ''.join([c for c in inst_name if c not in valid_set])
            valid = len(inst_name) > 0 and len(out) == 0
            if not valid:
                print "We only accept alphanumeric combinations"
        args.append(inst_name)
        tango_args.append(inst_name)
    else:
        inst_name = tango_args[1].lower()

    if "-nodb" in tango_args:
        return log_messages

    db = Database()
    if not exists_server_instance(db, server_name, inst_name):
        if ask_yes_no('%s does not exist. Do you wish to create a new '
                      'one' % inst_name,
                      default='y'):
            if server_name == 'MacroServer':
                # build list of pools to which the MacroServer should connect
                # to
                pool_names = []
                pools = get_dev_from_class(db, "Pool")
                all_pools = pools.keys()
                for pool in pools.values():
                    pool_alias = pool[2]
                    if pool_alias is not None:
                        all_pools.append(pool_alias)
                all_pools = map(str.lower, all_pools)
                pools_for_choosing = []
                for i in pools:
                    pools_for_choosing.append(pools[i][3])
                pools_for_choosing = sorted(pools_for_choosing,
                                            key=lambda s: s.lower())
                no_pool_msg = ("\nMacroServer %s has not been connected to "
                               "any Pool\n" % inst_name)
                if len(pools_for_choosing) == 0:
                    print(no_pool_msg)
                else:
                    print("\nAvailable Pools:")
                    for pool in pools_for_choosing:
                        print pool
                    print("")
                    while True:
                        msg = "Please select the Pool to connect to " \
                              "(return to finish): "
                        # user may abort it with Ctrl+C - this will not
                        # register anything in the database and the
                        # KeyboardInterrupt will be raised
                        elem = raw_input(msg).strip()
                        # no pools selected and user ended loop
                        if len(elem) == 0 and len(pool_names) == 0:
                            print(no_pool_msg)
                            break
                        # user ended loop with some pools selected
                        elif len(elem) == 0:
                            print(
                                "\nMacroServer %s has been connected to "
                                "Pool/s %s\n" % (inst_name, pool_names))
                            break
                        # user entered unknown pool
                        elif elem.lower() not in all_pools:
                            print "Unknown pool element"
                        else:
                            pool_names.append(elem)
                log_messages += register_sardana(db, server_name, inst_name,
                                                 pool_names)
            else:
                log_messages += register_sardana(db, server_name, inst_name)
        else:
            raise AbortException("%s startup aborted" % server_name)
    return log_messages
Esempio n. 24
0
def register_horizontal_motor():
    register("tomo/horizontal_motor/1", "HorizontalMotor", "HorizontalMotor/horizontal_motor")


def register_detector():
    register("tomo/detector/1", "Detector", "Detector/detector")


def register_shutter():
    register("tomo/shutter/1", "XRayShutter", "XRayShutter/shutter")


def register_source():
    register("tomo/source/1", "XRaySource", "XRaySource/source")


def register_tomograph():
    register("tomo/tomograph/1", "Tomograph", "Tomograph/tomograph")


db = Database()

# register_motor()
register_angle_motor()
register_horizontal_motor()
register_detector()
register_shutter()
register_source()
register_tomograph()
Esempio n. 25
0
def prepare_server(args, tango_args):
    """Register a proper server if the user gave an unknown server"""
    log_messages = []
    _, bin_name = os.path.split(args[0])
    server_name, _ = os.path.splitext(bin_name)

    if "-?" in tango_args:
        return log_messages

    nodb = "-nodb" in tango_args
    if nodb and not hasattr(DeviceClass, "device_name_factory"):
        print "In order to start %s with 'nodb' you need PyTango >= 7.2.3" % server_name
        sys.exit(1)

    if len(tango_args) < 2:
        valid = False
        while not valid:
            inst_name = raw_input("Please indicate %s instance name: " %
                                  server_name)
            # should be a instance name validator.
            valid_set = string.letters + string.digits + '_' + '-'
            out = ''.join([c for c in inst_name if c not in valid_set])
            valid = len(inst_name) > 0 and len(out) == 0
            if not valid:
                print "We only accept alphanumeric combinations"
        args.append(inst_name)
        tango_args.append(inst_name)
    else:
        inst_name = tango_args[1].lower()

    if "-nodb" in tango_args:
        return log_messages

    db = Database()
    if not exists_server_instance(db, server_name, inst_name):
        if ask_yes_no('%s does not exist. Do you wish create a new one' %
                      inst_name,
                      default='y'):
            if server_name == 'MacroServer':
                # build list of pools to which the MacroServer should connect
                # to
                pool_names = []
                pools = get_dev_from_class(db, "Pool")
                all_pools = pools.keys()
                for pool in pools.values():
                    pool_alias = pool[2]
                    if pool_alias is not None:
                        all_pools.append(pool_alias)
                all_pools = map(str.lower, all_pools)
                for i in pools:
                    print pools[i][3]
                while True:
                    elem = raw_input(
                        "Please select pool to connect to (return to finish): "
                    ).strip()
                    if not len(elem):
                        break
                    if elem.lower() not in all_pools:
                        print "Unknown pool element"
                        print all_pools
                    else:
                        pool_names.append(elem)
                log_messages += register_sardana(db, server_name, inst_name,
                                                 pool_names)
            else:
                log_messages += register_sardana(db, server_name, inst_name)
    return log_messages
Esempio n. 26
0
from PyTango import Database, DbDevInfo

#  A reference on the DataBase
db = Database()


new_device_name1 = "test/powersupply/1"


# Define the Tango Class served by this  DServer
new_device_info_mouse = DbDevInfo()
new_device_info_mouse._class = "PowerSupply"
new_device_info_mouse.server = "PowerSupplyDS/test" #servername/instance

# add the first device
print("Creating device: %s" % new_device_name1)
new_device_info_mouse.name = new_device_name1
db.add_device(new_device_info_mouse)