コード例 #1
0
def load_settings_registry(cxn):
    '''
    Make a client connection to the labrad host specified in the
    environment (i.e., by the node server) and load the rest of the settings
    from there.

    This file also takes care of locking the datavault storage directory.
    The lock only works on the local host, so we also node lock the datavault:
    if the registry has a 'Node' key, the datavault will refuse to start
    on any other host.  This should prevent ever having two copies of the
    datavault running.
    '''
    path = ['', 'Servers', 'Data Vault', 'Multihead']
    reg = cxn.registry
    # try to load for this node
    p = reg.packet()
    p.cd(path)
    p.get("Repository", 's', key="repo")
    p.get("Managers", "*(sws)", key="managers")
    p.get("Node", "s", False, "", key="node")
    ans = yield p.send()
    if ans.node and (ans.node != util.getNodeName()):
        raise RuntimeError(
            'Node name "%s" from registry does not match current host "%s"' %
            (ans.node, util.getNodeName()))
    cxn.disconnect()
    returnValue((ans.repo, ans.managers))
コード例 #2
0
def load_settings_registry(cxn):
    '''
    Make a client connection to the labrad host specified in the
    environment (i.e., by the node server) and load the rest of the settings
    from there.

    This file also takes care of locking the datavault storage directory.
    The lock only works on the local host, so we also node lock the datavault:
    if the registry has a 'Node' key, the datavault will refuse to start
    on any other host.  This should prevent ever having two copies of the
    datavault running.
    '''
    path = ['', 'Servers', 'Data Vault', 'Multihead']
    reg = cxn.registry
    # try to load for this node
    p = reg.packet()
    p.cd(path)
    p.get("Repository", 's', key="repo")
    p.get("Managers", "*(sws)", key="managers")
    p.get("Node", "s", False, "", key="node")
    ans = yield p.send()
    if ans.node and (ans.node != util.getNodeName()):
        raise RuntimeError('Node name "%s" from registry does not match current host "%s"' % (ans.node, util.getNodeName()))
    cxn.disconnect()
    returnValue((ans.repo, ans.managers))
コード例 #3
0
class MCSConfig(SettingConfigWidget):
    node = ['', 'Servers', 'OrtecMCS', getNodeName()]

    def __init__(self, cxn):
        QtGui.QWidget.__init__()
        ui_class, ui_widget = uic.loadUiType('main.ui')
        self.ui = ui_class()
        self.ui.setupUi(self)

        self.reg = cxn.registry
        self.guiSetup()

    def guiSetup(self):
        self.update()

    @QtCore.pyqtSlot()
    def on_exeDialogButton_clicked(self):
        current = self.ui.exePathEdit.text()
        d, f = os.path.split(current)
        path = QtGui.QFileDialog.getOpenFileName(self, 'Exe Path', d,
                                                 "Executable (*.exe)")
        self.ui.exePathEdit.setText(path)

    def _exePathValid(self):
        self.ui.exeValidLabel.setText('')
        path = self.ui.exePathEdit.text()
        if os.path.exists(path):
            if os.path.isfile(path):
                d, f = os.path.split(path)
                parts = f.split('.')
                if parts[-1] == 'exe':
                    self.ui.exeValidLabel.setText('')
                    return True

        #if we got to here, it's invalid
        invStr = r'<font color="red">Invalid file location.</font>'
        self.ui.exeValidLabel.setText(invStr)
        return False

    def validate(self):
        vals = [self._exePathValid()]
        return all(vals)

    def update(self):
        p = self.reg.packet()
        p.cd(self.node)
        p.get('ExePath', key='exe')
        resp = p.send()

        self.ui.exePathEdit.setText(resp['exe'])
        self.ui.exeValidLabel.setText('')

    def save(self):
        path = self.ui.exePathEdit.text()

        p = self.reg.packet()
        p.cd(self.node)
        p.set('ExePath', path)
        p.send()
コード例 #4
0
class BNCConfig(SettingConfigWidget):
    regDir = ['', 'Servers', 'BNC Serial', getNodeName(), 'Links']
    serName = '%s_serial_server' % getNodeName().lower()

    def __init__(self, cxn):
        QtGui.QWidget.__init__()
        ui_class, ui_widget = uic.loadUiType('bnc_config.ui')
        self.ui = ui_class()
        self.ui.setupUi(self)

        self.cxn = cxn
        self.guiSetup()

    def guiSetup(self):
        self._populateBoxes()

    def _populateBoxes(self):
        ser = self.cxn[self.serName]

        port = ser.list_serial_ports()
        baud = ser.baudrate()

        self.ui.comBox.addItems(port)
        self.ui.baudBox.addItems(baud)

    def validate(self):
        return True

    def update(self):
        self._populateBoxes()

    def save(self):
        idN = int(self.ui.deviceBox.currentText())
        port = self.ui.comBox.currentText()
        baud = int(self.ui.baudBox.currentText())

        entry = (idN, port, baud)

        reg = self.cxn.registry
        reg.cd(self.regDir)
        vals = reg.get(self.serName)

        if entry not in vals:
            vals.append(entry)
            reg.set(self.serName, vals)
コード例 #5
0
class NodeOptions(usage.Options):
    optParameters = [
            ['name', 'n', util.getNodeName(), 'Node name.'],
            ['port', 'p', C.MANAGER_PORT, 'Manager port.'],
            ['host', 'h', C.MANAGER_HOST, 'Manager location.'],
            ['tls', '', C.MANAGER_TLS,
             'TLS mode for connecting to manager (on/starttls/off)'],
            ['logfile', 'l', None, 'Enable logging to a file'],
            ['syslog_socket', 'x', None,
             'Override default syslog socket. Absolute path or host[:port]']]
    optFlags = [['syslog', 's', 'Enable syslog'],
                ['verbose', 'v', 'Enable debug output']]
コード例 #6
0
class BNCSerialServer(BNCBaseServer):
    '''
    Generic BNC device server. All pulser types can be run from this.
    Does not include device-specific features (ie. 35V out, multiplexing).
    '''

    name = '%LABRADNODE% BNC Serial Server'
    ID = 54333

    nodeDirectory = ['', 'Servers', 'BNC Serial', getNodeName(), 'Links']

    def serverConnected(self, ID, name):
        if 'serial' in name.lower():
            self.refreshDeviceList()

    def serverDisconnected(self, ID, name):
        if 'serial' in name.lower():
            self.refreshDeviceList()

    @inlineCallbacks
    def findDevices(self):
        p = self.client.registry.packet()
        p.cd(self.nodeDirectory, True)
        p.dir()
        resp = yield p.send()
        dirs, keys = resp['dir']

        p = self.client.registry.packet()
        for k in keys:
            p.get(k, key=k)
        resp = yield p.send()

        devList = []
        for serverName in keys:
            if serverName not in self.client.servers:
                continue

            server = self.client[serverName]
            portList = yield server.list_serial_ports()

            for (model, port, baud) in resp[serverName]:
                if port not in portList:
                    continue

                devName = 'BNC%d-%s' % (model, port)
                dev = (devName, (server, port, baud), {})
                devList.append(dev)

        returnValue(devList)

    def chooseDeviceWrapper(self, name, *args, **kw):
        model = int(name[3:6])
        return DEVICE_MAP[model]
コード例 #7
0
 def initServer(self):
     # load configuration info from registry
     # global DATADIR
     try:
         path = ['', 'Servers', self.name, 'Repository']
         nodename = util.getNodeName()
         reg = self.client.registry
         try:
             # try to load for this node
             p = reg.packet()
             p.cd(path)
             p.get(nodename, 's')
             ans = yield p.send()
         except:
             # try to load default
             p = reg.packet()
             p.cd(path)
             p.get('__default__', 's')
             ans = yield p.send()
         # DATADIR = ans.get
         gotLocation = True
     except:
         try:
             print('Could not load repository location from registry.')
             print(
                 'Please enter data storage directory or hit enter to use the current directory:'
             )
             DATADIR = input('>>>')
             if DATADIR == '':
                 DATADIR = os.path.join(
                     os.path.split(__file__)[0], '__data__')
             if not os.path.exists(DATADIR):
                 os.makedirs(DATADIR)
             # set as default and for this node
             p = reg.packet()
             p.cd(path, True)
             p.set(nodename, DATADIR)
             p.set('__default__', DATADIR)
             yield p.send()
             print(DATADIR, "has been saved in the registry", end=' ')
             print("as the data location.")
             print("To change this, stop this server,")
             print("edit the registry keys at", path, end=' ')
             print("and then restart.")
         except Exception as E:
             print()
             print(E)
             print()
             print("Press [Enter] to continue...")
             input()
             sys.exit()
     # create root session
     root = Session([''], self)
コード例 #8
0
 def initServer(self):
     # load configuration info from registry
     global DATADIR
     try:
         path = ['', 'Servers', self.name, 'Repository']
         nodename = util.getNodeName()
         reg = self.client.registry
         try:
             # try to load for this node
             p = reg.packet()
             p.cd(path)
             p.get(nodename, 's')
             ans = yield p.send()
         except:
             # try to load default
             p = reg.packet()
             p.cd(path)
             p.get('__default__', 's')
             ans = yield p.send()
         DATADIR = ans.get
         gotLocation = True
     except:
         try:
             print 'Could not load repository location from registry.'
             print 'Please enter data storage directory or hit enter to use the current directory:'
             DATADIR = raw_input('>>>')
             if DATADIR == '':
                 DATADIR = os.path.join(os.path.split(__file__)[0], '__data__')
             if not os.path.exists(DATADIR):
                 os.makedirs(DATADIR)
             # set as default and for this node
             p = reg.packet()
             p.cd(path, True)
             p.set(nodename, DATADIR)
             p.set('__default__', DATADIR)
             yield p.send()
             print DATADIR, "has been saved in the registry",
             print "as the data location."
             print "To change this, stop this server,"
             print "edit the registry keys at", path,
             print "and then restart."
         except Exception, E:
             print
             print E
             print
             print "Press [Enter] to continue..."
             raw_input()
             sys.exit()
コード例 #9
0
 def initServer(self):
     # load configuration info from registry
     # global DATADIR
     try:
         path = ['', 'Servers', self.name, 'Repository']
         nodename = util.getNodeName()
         reg = self.client.registry
         try:
             # try to load for this node
             p = reg.packet()
             p.cd(path)
             p.get(nodename, 's')
             ans = yield p.send()
         except:
             # try to load default
             p = reg.packet()
             p.cd(path)
             p.get('__default__', 's')
             ans = yield p.send()
         # DATADIR = ans.get
         gotLocation = True
     except:
         try:
             if not os.path.exists(DATADIR):
                 os.makedirs(DATADIR)
             # set as default and for this node
             p = reg.packet()
             p.cd(path, True)
             p.set(nodename, DATADIR)
             p.set('__default__', DATADIR)
             yield p.send()
             print DATADIR, "has been saved in the registry",
             print "as the data location."
             print "To change this, stop this server,"
             print "edit the registry keys at", path,
             print "and then restart."
         except Exception, E:
             print
             print E
             print
             print "Press [Enter] to continue..."
             raw_input()
             sys.exit()
コード例 #10
0
ファイル: mcs.py プロジェクト: mcconkeylabs/labrad_servers
class MCSServer(LabradServer):
    
    name = '%LABRADNODE% OrtecMCS Server'
    ID = 654321
    
    regPath = ['', 'Servers', 'OrtecMCS', getNodeName()]    
    
    ##### SIGNALS #####    
    onScanStart = Signal(66777, 'signal: scan started', 's')
    onScanComplete = Signal(66778, 'signal: scan complete', 's')
    
    @inlineCallbacks
    def initServer(self):
        self.reg = self.client.registry
        yield self._loadRegistry()
        
        self.tmpDir = T.mkdtemp()
        self.jobPath = OP.join(self.tmpDir, JOB_NAME)
        
    @inlineCallbacks
    def stopServer(self):
        yield self._updateRegistry()
        rmtree(self.tmpDir)
        
    @inlineCallbacks
    def _loadRegistry(self):
        p = self.reg.packet()
        p.cd(self.regPath, True)
        p.get('ExePath', True, EXE_DEFAULT, key='exe')
        p.cd('Settings', True)
        for (k, v) in DEFAULT_PARAMETERS.items():
            p.get(k, True, v, key=k)
        resp = yield p.send()
        
        #parse response
        self.exePath = resp['exe']
        self.params = dict([(k, resp[k]) for k in\
                            DEFAULT_PARAMETERS.keys()])
    
    @inlineCallbacks
    def _updateRegistry(self):
        p = self.reg.packet()
        p.cd(self.regPath, True)
        p.set('ExePath', self.exePath)
        p.cd('Settings')
        for (k,v) in self.params.items():
            p.set(k, v)
        yield p.send()
        
    def _runJob(self, lines):
        #write job file
        output = ['SET_MCS 1'] + lines
        with open(self.jobPath, 'w') as job:
            job.writelines('\n'.join(output))
            print '\n'.join(output)
            
        #execute MCS program with job file
        args = [self.exePath, '-J', self.jobPath]
        self.proc = Popen(args)
        
    def _isRunning(self):
        if hasattr(self, 'proc'):
            return self.proc.poll() is None
        else:
            return False
            
    def _monitorScan(self):
        def run():
            while self.proc.poll() is None:
                sleep(0.5)
            self.onScanComplete(self._savePath())
                
        cmds = [(run, [], {})]
        callMultipleInThread(cmds)
            
    ###OVERWRITES OLD SCAN. INEFFICIENT TO KEEP GENERATING!!!
    def _savePath(self):
        path = os.path.join(self.tmpDir, SAVE_NAME)
        return path
        
    
    
    ##### SETTINGS #####
    @setting(100, 'Pass Length', length = 'w', returns = 'w')
    def pass_length(self, c, length=None):
        '''Set/query the number of bins in the scan pass. (None queries)'''
        if length is not None:
            if length < jobs.LEN_MIN or length > jobs.LEN_MAX:
                string = 'Pass length must be between %d and %d' %\
                         (jobs.LEN_MIN, jobs.LEN_MAX)
                raise Error(string)
                
            self.params['Length'] = length   
            
        return self.params['Length']
    
    @setting(101, 'Passes', passes = 'w', returns='w')
    def sweeps(self, c, passes=None):
        '''Set/query the number of scan sweeps. (None queries)'''
        if passes is not None:
            if passes < jobs.PASS_MIN or passes > jobs.PASS_MAX:
                string = 'Pass count must be between %d and %d'\
                         % (jobs.PASS_MIN, jobs.PASS_MAX)
                raise Error(string)
                
            self.params['Passes'] = passes
            
        return self.params['Passes']
    
    @setting(102, 'Acquisition Mode', mode='s', returns='s')
    def acquisition_mode(self, c, mode = None):
        '''Set/query acquisition mode. 
        
        Input
        None : Query current setting
        Mode : Set mode to one of 'Rep', 'Sum', 'RepSum'
        
        Returns
        Currently set acquisition mode.
        '''
        if mode is not None:
            if mode not in ACQ_MODES:
                opts = ', '.join(ACQ_MODES)
                string = 'Acquisition mode must be one of %s' % opts
                raise Error(string)
            self.params['AcqMode'] = mode
            
        return self.params['AcqMode']
    
    @setting(103, 'Discriminator Level', level='v[V]', returns='v[V]')
    def discriminator_level(self, c, level=None):
        '''Set/query current discriminator voltage'''
        if level is not None:
            if level['V'] < jobs.DISC_MIN or level['V'] > jobs.DISC_MAX:
                string = 'Discriminator level must be between %f and %f'\
                         % (jobs.DISC_MIN, jobs.DISC_MAX)
                raise Error(string)
            self.params['DiscLevel'] = level
            
        return self.params['DiscLevel']
    
    @setting(104, 'Discriminator Edge', 
             rising=['s: Rising or Falling',
                     'b: True for rising edge'],
             returns='s: Current edge')
    def discriminator_edge(self, c, rising=None):
        '''Set/query input channel discriminator edge. 
        
        None queries input. Can be set with edge type
        'Rising' or 'Falling' or by
        True/False for rising/falling edge.
        
        Returns the edge type as text
        '''
        if rising is not None:
            if type(rising) is str:
                rStr = rising.lower()
                if rStr not in ['rising', 'falling']:
                    
                    rvals = ', '.join(['Rising', 'Falling'])
                    raise Error('Edge must be one of %s' % rvals)
                else:
                    rVal = rStr == 'rising'
            else:
                rVal = rising
                
            self.params['DiscEdge'] = rVal
            
        return 'Rising' if self.params['DiscEdge'] else 'Falling'
        
    @setting(105, 'Input Impedance', 
             imped=['v[Ohm]: Impedance value (50 or 1K)',
                    'b: True for 50 Ohms'], 
             returns='v[Ohm]: Current input impedance')
    def input_impedance(self, c, imped=None):
        '''Set/query input signal impedance
        
        None : Query current setting
        True : Input at 50 Ohm impedance
        False : Input at 1 kOhm impedance
        Value can also be actual impedance value
        
        Returns : Impedance value
        '''
        if imped is not None:
            if type(imped) is bool:
                val = imped
            else:
                if imped['Ohm'] not in [50, 1000]:
                    raise Error('Impedance must be 50, 1000 Ohms or boolean')
                else:
                    val = imped['Ohm'] == 50
            
            self.params['Impedance'] = val
            
        return U.Value(50 if self.params['Impedance'] else 1000, 'Ohm')
    
    @setting(106, 'Voltage Ramp', 
             start='v[V]', stop='v[V]', middle='v[V]', 
             returns='*v[V]')
    def voltage_ramp(self, c, start=None, stop=None, middle=None):
        if start is not None:
            vs = [start, stop, middle]
            self.params['Ramp'] = [v for v in vs if v is not None]
        return self.params['Ramp']
    
    @setting(107, 'Dwell',
             dwell = ['v[s] : Internal dwell time (seconds)',
                      'v[V] : External dwell threshold (voltage)'],
             returns = ['(sv[s])', '(sv[V])'])
    def dwell(self, c, dwell=None):
        '''Set/query the dwell trigger.
        
        Input:
        dwell - Time in seconds if internal dwell timer used
              - Voltage threshold of external advance signal used
              
        Returns:
        (type, parameter) - Type is 'Internal' or 'External' with
                            associated dwell time/threshold
        '''
        if dwell is not None:
            if dwell.isCompatible('s'):
                if dwell['s'] < jobs.DWELL_MIN or dwell['s'] > jobs.DWELL_MAX:
                    string = 'Dwell time must be between %f and %f seconds' %\
                             (jobs.DWELL_MIN, jobs.DWELL_MAX)
                    raise Error(string)
            else:
                if dwell['V'] < jobs.DISC_MIN or dwell['V'] > jobs.DISC_MAX:
                    string = 'Dwell trigger threshold must be between %f and %f volts' %\
                             (jobs.DISC_MIN, jobs.DISC_MAX)
                    raise Error(string)
                    
            self.params['Dwell'] = (dwell.isCompatible('s'), dwell)
        
        isInt, value = self.params['Dwell']
        string = 'Internal' if isInt else 'External'
        return (string, value)
        
    @setting(108, 'External Trigger',
             external = 'b', returns='b')
    def external_trigger(self, c, external=None):
        '''Set/query start trigger setting.
        None queries, True/False for External/Internal trigger
        '''
        if external is not None:
            self.params['ExtTrigger'] = external
        return self.params['ExtTrigger']
    
    @setting(200, 'Start', path='s: Save path')
    def start(self, c, path=None):
        '''Start the MCS with the current settings.
        path: File name or directory to place .mcs spectrum file.
              Defaults to None in which case currently set directory is used.
              If directory provided, saves file with format
              YY_MM_DD_NN.mcs    where NN increments with successive saves
        '''
        if self._isRunning():
            raise MCSRunningError()
            
        sp = self._savePath() if path is None else path
        lines = list(chain(jobs.parameterLines(self.params),
                           jobs.SCAN_LINES, [jobs.saveLine(sp)]))
        self._runJob(lines)
        self.onScanStart(self._savePath())
        self._monitorScan()
    
    @setting(201, 'Stop')
    def stop(self, c):
        '''Stop the current run.'''
        if self._isRunning():
            self.proc.terminate()
    
    @setting(202, 'Clear')
    def clear_buffer(self, c):
        '''Clear all data in the hardware buffers. 
        Will not clear if the device is running.'''
        if self._isRunning():
            raise MCSRunningError()
        self._runJob(jobs.CLEAR_LINES)
        
    @setting(203, 'Run State', returns='b')
    def run_state(self, c):
        '''Current MCS run state.'''
        return self._isRunning()
        
    #THIS IS NO GOOD. NEED TO SAVE LOCATION TO PASS ON
    #DOES NOT PROCESS BINARY FILE!!!
    @setting(204, 'Save Data', path='s', returns='s')
    def save_data(self, c, path=None):
        '''Save current MCS buffer to specified path. Writes to default
        otherwise.'''
        
        if self._isRunning():
            raise MCSRunningError()
        sp = self._savePath() if path is None else path
        lines = ['SET_MCS 1', jobs.saveLine(sp)]
        self._runJob(lines)
        return sp
コード例 #11
0
ファイル: client.py プロジェクト: HaeffnerLab/sqip
 def __init__(self, name):
     self.name = name or 'Python Client (%s)' % util.getNodeName()
     self.connected = False
     self._next_context = 1