def amplitude(self, c, a=None):
        """Get or set the CW amplitude."""
        if a is not None:
            float(self.write(self.instr, 'POWer {}'.format(float(a)))
            self.amplitude = a
        returnValue(amplitude)

    @setting(7, 'Output', os=['b'], returns=['b'])
    def output_state(self, c, os=None):
        """Get or set the output status."""
        if os is not None:
        	bool(self.write(self.instr, 'OUTput:STATe {}'.format(int(out))))
            self.output= os
        returnValue(output)



__server__ = RS_SMAServer()

if __name__ == '__main__':
    from labrad import util
    util.runServer(__server__)   
Example #2
0
        #                        s = sequence.pop(key)
        #                        sequence.update({c.key: s})
        #                    elif c.loc not in locs:
        #                        sequence.update({c.key: [
        #                            {'dt': dt, 'out': c.manual_output}
        #                                for dt in sequence[TRIGGER_CHANNEL]]})
        #        return sequence
        fixed_sequence = {}
        for old_id, channel_sequence in sequence.items():
            channel = self.id2channel(old_id)
            fixed_sequence[channel.key] = channel_sequence

        # make sure every channel has defined sequence
        for d in self.devices.values():
            for c in d.channels:
                if c.key not in fixed_sequence:
                    default_sequence = [{
                        'dt': s['dt'],
                        'out': c.manual_output
                    } for s in sequence[TRIGGER_CHANNEL]]
                    fixed_sequence.update({c.key: default_sequence})
        return fixed_sequence

    @setting(2)
    def send_update(self, c):
        yield self.update(True)

if __name__ == "__main__":
    from labrad import util
    util.runServer(SequencerServer())
Example #3
0
    
    @inlineCallbacks
    def initServer(self):
        yield self.client.registry.cd(['','Servers', 'wikiserver'])
        self.maindir = yield self.client.registry.get('wikipath')
        self.maindir = self.maindir[0] + '/'

    @setting(21, 'Update Wiki', sourcefile='s', destinationfile='s', returns='')
    def update_wiki(self, c, sourcefile, destinationfile):
        yield os.system("cp " + self.datadir + sourcefile + " " + self.maindir + self.wikidir + destinationfile)
        yield os.chdir(self.maindir)
        print os.getcwd()
        yield os.system("bash updatewiki.sh")
        
    @setting(22, 'Add wiki directory', wikidir='s',returns='')    
    def set_wiki_dir(self, c, wikidir):
        self.wikidir = wikidir + '/'
     
    @setting(23, 'Add data directory', datadir='s',returns='')    
    def set_data_dir(self, c, datadir):
        self.datadir = datadir + '/'
        
    @setting(24, 'Plot data for wiki', data)
    def plot_wiki(self, c):
        self.plot = plotdataforwiki(data)
        show()

if __name__ == "__main__":
    from labrad import util
    util.runServer(WikiServer())
Example #4
0
        self.s.connect((agilent_IP,agilent_port))
        self.s.settimeout(agilent_timeout)

    @setting(2,"set_freq",freq="v")
    def set_freq(self,c,freq):
        
        freq_GHz = freq['GHz']
        
        cmd = ":FREQ %.12f GHz\r\n;:OUTP ON\r\n" % freq_GHz
        
        print cmd
        self.send(cmd)
        
    
    @setting(3,"set_pow",power="v")
    def set_pow(self,c,power):
        """ Set the output power. Accepts input in dBm only. """
        pow_dBm = power['dBm']
        
        cmd = ":POW %.6f dBm\r\n;:OUTP ON\r\n" % pow_dBm
        
        print cmd
        self.send(cmd)




if __name__ == "__main__":
    from labrad import util
    util.runServer(AgilentE8257D())
Example #5
0
from datetime import datetime
from twisted.internet.task import LoopingCall
from twisted.internet import reactor
from labrad.gpib import GPIBManagedServer, GPIBDeviceWrapper

#def hyper_task(a):
#    print "I like to run fast", datetime.now(),a

def tired_task():
    print "I want to run slowly", datetime.now()

class xclass(GPIBManagedServer):

    
    lc = LoopingCall(lambda a='a':hyper_task(a))
    lc.start(0.1)

    def hyper_task(self, a):
        print "I like to run fast", datetime.now(),a

if __name__ == "__main__":
    from labrad import util
    x = xclass()
    util.runServer(x)

#reactor.run()
Example #6
0
            resultParams = self.pF.getResultParams()
            output = self.pF.returnResult()
            #delete previous dataset here
            print self.outputfile
            a = yield self.writehandle.call('new',self.outputfile, resultParams[0],resultParams[1])#make more general
            print a
            yield self.writehandle.call('add',output)
        
class ContextHandle( object ):
    def __init__( self, cxn, server ):
        self.cxn = cxn
        self.context = self.cxn.context()
        self.server = server  

    @inlineCallbacks
    def call( self, setting, *args, **kwargs ):
        kwargs['context'] = self.context
        result = yield self.cxn.servers[self.server].settings[setting]( *args, **kwargs )
        returnValue( result )
    
    def addListener( self, listener, ID ):
        self.cxn._addListener( listener = listener, source = None, ID = ID, context = self.context )

    def removeListener( self, listener, ID ):
        self.cxn._removeListener( listener = (listener,(),{}), source = None, ID = ID, context = self.context )


if __name__ == "__main__":
    from labrad import util
    util.runServer( dataProcessor() )
Example #7
0
        return dp.freqRange
    
    @setting(8, "Amplitude Range", returns = '(vv)')
    def amplRange(self, c):
        """Returns the frequency range in the current context"""
        dp = self.getDP(c)
        return dp.amplRange
    
    def getDP(self, context):
        if not 'doublePass' in context.keys(): raise Exception ('Double Pass not selected')
        return context['doublePass']
    
    def notifyOtherListeners(self, context, chanInfo):
        """
        Notifies all listeners except the one in the given context
        """
        notified = self.listeners.copy()
        notified.remove(context.ID)
        self.onNewUpdate(chanInfo, notified)
    
    def initContext(self, c):
        """Initialize a new context object."""
        self.listeners.add(c.ID)
    
    def expireContext(self, c):
        self.listeners.remove(c.ID)
    
if __name__ == "__main__":
    from labrad import util
    util.runServer(doublePassServer())
Example #8
0
    @staticmethod
    def makeComString( channel, binVolt ):
        hexrepr = hex( binVolt )[2:] #select ffff out of 0xfff'                                                                                                                          
        hexrepr = hexrepr.zfill( 4 ) #left pads to make sure 4 characters                                                                                                            
        numstr = binascii.unhexlify( hexrepr ) #converts ffff to ascii characters                                                                                            
        comstring = str( channel ) + ',' + numstr
        return comstring

    def mapMessage( self, givenChannel, value ):
        """
        Map value to serial string for specified channel.
        
        Note that channel is different from device channel.
        
        @param channel: Use channel to determine mapping parameters
        @param value: Value to be converted
        
        @return: value formatted for serial communication
        """
        def mapVoltage( value, range ):
            return ( float( value ) - float( range[0] ) ) * DAC_MAX / ( range[1] - range[0] )
        range = givenChannel.range
        chanNumber = givenChannel.chanNumber
        return self.makeComString( chanNumber, self.voltageToFormat( mapVoltage( value, range ) ) )
    
if __name__ == "__main__":
    from labrad import util
    util.runServer( laserDACServer() )


        This setting tries to guess the active channel unless in multiplex mode
        """
        if (channel == -1):
            channel = self.guess_channel()

        try:
            wavelength = self.binding.get_wavelength_num(channel)
            # return wavelength * nm;
            return wavelength
        except Exception as e:
            return self.handle_wavemeter_error(e)

    def guess_channel(self):
        if (self.get_multiplex_mode({})):
            return 1
        else:
            return self.get_channel({})

    @staticmethod
    def handle_wavemeter_error(e):
        print('(wavemeter) error: %s' % e)
        return None


if __name__ == '__main__':
    from labrad import util

    server = WavemeterServer()
    util.runServer(server)
Example #10
0
    @setting(1, "Send", subject='s', message='s', returns='')
    def selectDP(self, c, subject, message):
        """Select Double Pass in the current context"""
        if not self.toaddrs[c.ID]: raise Exception("Recipients not set")
        yield self.sending.acquire()
        session = smtplib.SMTP(self.smtp)
        session.starttls()
        session.login(self.username, self.password)
        toaddrs = self.toaddrs[c.ID]
        msg = MIMEMultipart()
        msg['From'] = self.fromaddr
        msg['To'] = COMMASPACE.join(toaddrs)
        msg['Subject'] = subject
        msg.attach(MIMEText(message, 'plain'))
        session.sendmail(self.fromaddr, toaddrs, msg.as_string())
        session.quit()
        self.sending.release()

    def initContext(self, c):
        """Initialize a new context object."""
        pass

    def expireContext(self, c):
        del (self.toaddrs[c.ID])


if __name__ == "__main__":
    from labrad import util
    util.runServer(emailer())
Example #11
0
            )  #converts the new state to hex and adds it to the sequence
            lastChannels = channels
        rep = rep + 2 * self.numToHex(0)  #adding termination
        return rep

    def humanRepresentation(self):
        """Returns the human readable version of the sequence for FPGA for debugging"""
        rep = self.progRepresentation()
        arr = numpy.fromstring(
            rep, dtype=numpy.uint16)  #does the decoding from the string
        arr = numpy.array(
            arr, dtype=numpy.uint32
        )  #once decoded, need to be able to manipulate large numbers
        arr = arr.reshape(-1, 4)
        times = (65536 * arr[:, 0] + arr[:, 1]) * timeResolution
        channels = (65536 * arr[:, 2] + arr[:, 3])

        def expandChannel(ch):
            '''function for getting the binary representation, i.e 2**32 is 1000...0'''
            expand = bin(ch)[2:].zfill(32)
            reverse = expand[::-1]
            return reverse

        channels = map(expandChannel, channels)
        return numpy.vstack((times, channels)).transpose()


if __name__ == "__main__":
    from labrad import util
    util.runServer(Pulser())
Example #12
0
    def close(self, c, _id):
        s = self._get_socket(_id)
        result = s.close()
        del self._sockets[_id]
        return result

    @setting(13, _id='i')
    def gettimeout(self, c, _id):
        s = self._get_socket(_id)
        return s.gettimeout()

    @setting(14, _id='i', buffersize='i', flags='i', returns='s')
    def recv(self, c, _id, buffersize, flags):
        s = self._get_socket(_id)
        return s.recv(buffersize, flags)

    @setting(15, _id='i', data='s', flags='i')
    def send(self, c, _id, data, flags):
        s = self._get_socket(_id)
        return s.send(data, flags)

    @setting(16, _id='i', timeout='v')
    def settimeout(self, c, _id, timeout):
        s = self._get_socket(_id)
        return s.settimeout(timeout)


if __name__ == '__main__':
    from labrad import util
    util.runServer(SocketServer())
Example #13
0
            yield self.ser.write('VSET?\n')
            yield self.ser.write('++read eoi\r\n')
            volt_str = yield self.ser.readline()
            voltage = volt_str[4:].strip()
            voltage = WithUnit(float(voltage), 'V')
        else:
            volt_str = 'VSET{0:.3f}V\n'.format(voltage['V'])
            yield self.ser.write(volt_str)
        returnValue(voltage)

    @setting(1, current='v[A]: current', returns='v[A]: current')
    def current(self, c, current=None):
        """
        Read or set the current setpoint
        """
        if current is None:
            yield self.ser.write('ISET?\n')
            yield self.ser.write('++read eoi\r\n')
            current_str = yield self.ser.readline()
            current_str = current_str[4:].strip()
            current = WithUnit(float(current_str), 'A')
        else:
            current_str = 'ISET{0:.3f}A\n'.format(current['A'])
            yield self.ser.write(current_str)
        returnValue(current)


if __name__ == "__main__":
    from labrad import util
    util.runServer(Agilent_6030A())
Example #14
0
class Photodetector(LabradServer):
    """Photodetector Server"""

    name = "photodetector"
    password = ""

    def initServer(self):
        self.device_dictionary = self.get_device_dictionary()

    def get_device_dictionary(self):
        with open('DeviceConfig.yaml', 'r') as f:
            deviceConfig = yaml.load(f)

        device_dictionary = {}
        for k in deviceConfig.keys():
            if deviceConfig[k]['server'] == 'photodetector':
                device_dictionary[k] = deviceConfig[k]['properties']

        return device_dictionary

    @setting(10, "acquire", detector='s', returns='v')
    def acquire(self, c, detector):
        NI6250_channel = self.device_dictionary[detector]['NI6250']
        value = self.client.ni6250.getstaticvoltage(NI6250_channel)
        return value


if __name__ == "__main__":
    from labrad import util
    util.runServer(Photodetector())
Example #15
0
        
        self.multipoleSet = multipoleSet # may want to keep track of the current set.
        realVolts = zeros(NUMCHANNELS)
        for key in self.multipoleVectors.keys():
            #print self.multipoleVectors[key]
            realVolts += dot(multipoleSet[key],self.multipoleVectors[key])
            #realVolts += multipoleSet[key] * self.multipoleVectors[key]
        self.setAnalogVoltages(c, realVolts)
        
        registry = self.client.registry
        yield registry.cd(['', 'cctdac', 'Multipoles'])
        yield registry.set('Multipole Set', ms)          
    
    @setting( 7, 'Get Multipole Voltages',returns='*(s,v)')
    def getMultipoleVolgates(self, c):
        return self.multipoleSet.items()
        
    @setting( 9, 'return number wells', returns = 'i')
    def returnNumWells(self, c):
	"""
	Return the number of wells as determined by the size of the current Cfile
	"""
	return self.numWells        
    
        
if __name__ == "__main__":
    from labrad import util
    util.runServer( CCTDACServer() )


Example #16
0
        try:
            self.dv = yield self.cxn.servers['Data Vault']
        except KeyError as error:
            error_msg = str(error) + '  ' + 'DataVault is not running'
            raise KeyError(error_msg)

        self.path = yield self.setup_datavault('Time', 'Multipole Values [V]')

    @inlineCallbacks
    def loops(self):

        # grab the multipoles
        mps = yield self.server.get_multipoles()
        self.time = self.time + self.rate

        # yield self.dv.add(self.time, mps[0], mps[1], mps[2], mps[3], mps[4], mps[5], mps[6], mps[7])


    @inlineCallbacks
    def setup_datavault(self, x_axis, y_axis):
        """
        adds parameters to datavault and parameter vault, define contexts for each laser
        """
        yield self.dv.cd(['', self.name], True)
        self.dataset = yield self.dv.new(self.name, [( 't', 'num')], [('Ex', '', 'num')], [('Ey', '', 'num')], [('Ez', '', 'num')], [('M1', '', 'num')], [('M2', '', 'num')], [('M3', '', 'num')], [('M4', '', 'num')], [('M5', '', 'num')])


if __name__ == "__main__":
    from labrad import util
    util.runServer(multipole_monitor())
    def _startMeasurement(self):
        #time.strftime("%Y%b%d_%H%M_%S",time.localtime())
#        dv = self.client.data_vault
#        yield dv.cd(['', 'QuickMeasurements', 'FajansBFieldMeasurements'], True)
#        yield dv.new('B-Field', [('Time', '')], [('B Field','','Gauss')])
        while(1):
            self._connect()
            self.cli.send(self.buffer)
            yield deferToThread(time.sleep, 2)
            data = self.cli.recv(BUFSIZE)
            print data
            self.currentMeasurement = data
            self._disconnect()
            #process and add it to datavault
            yield dv.add([])        

    @setting(1, "Get Current Measurement", returns="v")
    def getCurrentMeasurement(self, c, ):
        """Returns the current reading"""
        return self.currentMeasurement

    @setting(2, "Start Measurement", returns="")
    def startMeasurement(self, c, ):
        """Starts the Measurement"""
        yield deferToThread(self._startMeasurement)


if __name__ == "__main__":
    from labrad import util
    util.runServer(BFieldMonitorServer())
        if duration is not None:
            tracker.keep_line_measurements = duration['s']
            tracker.remove_old_measurements()
        return WithUnit(tracker.keep_line_measurements, 's')

    @setting(8, 'Get All History', tracker_number='i', returns='*(v[s]v[kHz])')
    def get_all_history(self, c, tracker_number=1):
        '''
        Return all points participating in the fit
        '''
        tracker_id = tracker_number - 1
        try:
            tracker = self.Line_tracker[
                tracker_id]  # access the correct tracker
        except IndexError:
            raise Exception("Tracker out of range.")

        return tracker.get_all_history()

    @setting(9, 'Get Tracker Number', returns='i')
    def get_tracker_number(self, c):
        '''
        Return the number of tracker initialized
        '''
        return self.numbers_of_tracker


if __name__ == '__main__':
    from labrad import util
    util.runServer(LineTracker())
                if not self.m%2:
                    self.start += 3 * dTime
                    duration = 13 * dTime
                    pulser.add_ttl_pulse(str(self.dat), self.start, duration)
                
        elif listy[numEntry]:
            self.m+=1
            n += 1
            self.g(listy, numEntry+1, n)
            
        elif not listy[numEntry]:
            duration = 3*n*dTime
            if n:                
                pulser.add_ttl_pulse(str(self.dat), self.start, duration)
                #print numEntry, duration 
            self.start += duration + 3 * dTime
            self.g(listy, numEntry+1, 0)
                                
    def f(self, num, listy): #binary representation of values in the form of a list
        for i in range(len(listy)):
            if num >= 2**(len(listy)-1)/(2**i):
                listy[i] = True
                num -= 2**(len(listy)-1)/(2**i)
            else:
                listy[i] = False 
        return listy
       
if __name__ == "__main__":
    from labrad import util
    util.runServer( CCTDACServer() )
Example #20
0
            print 'packets read in: ', len(reading)
            self.processPackets(reading)
            reactor.callLater(0, self.readNewData)

    @inlineCallbacks
    def processPackets(self, packets):
        for i in range(NUMTOCOLLECT):
            message = packets[i][3]
            num = message[31:35]
            readout = message[36:36 + 16]
            if num.isdigit(
            ):  #basic version of making sure packet is formatted well
                if int(
                        num
                ) == 0:  #if packet starts with 0000, then add the message unless it's the first one
                    encoded = base64.b64encode(self.d['TotalMessage'])
                    if self.d['TrialCount'] is not 0:
                        yield self.dv.add([str(self.d['TrialCount']), encoded])
                        ###testing to see how many counts we have for a low count rate
                        #ct1 = (encoded.count('B') + encoded.count('C') + encoded.count('E') + encoded.count('I') + encoded.count('Q') + encoded.count('g'))
                        #ct2 = 2 * (len(encoded) - encoded.count('A') - ct1)
                        #print ct1 + ct2
                    self.d['TrialCount'] += 1
                    self.d['TotalMessage'] = ''
            self.d['TotalMessage'] += readout


if __name__ == "__main__":
    from labrad import util
    util.runServer(TimeResolvedServer())
Example #21
0
    @setting(28, "Get WLM Output", returns = 'b')
    def getWLMOutput(self, c):
        value = yield self.wmdll.GetOperationState(c_short(0))
        if value == 2:
            value = True
        else:
            value = False
        returnValue(value)
    
    @setting(29, "Get Individual Lock State", returns = 'b')
    def getSingleLockState(self,c,chan):
        return False
        
    def measureChan(self):
        #TODO: Improve this with a looping call
        reactor.callLater(0.1, self.measureChan)
        for chan in range(8):
            if self.getSwitcherState(self, chan + 1):
                self.getFrequency(self, chan + 1) 
                self.getOutputVoltage(self, chan + 1)
                if self.getSingleLockState(self, chan + 1):
                    value = self.calcPID(chan)
                    print value
                    #self.setDACVoltage(chan + 1, value )
        
if __name__ == "__main__":
    from labrad import util
    util.runServer(MultiplexerServer())
    
    
Example #22
0
cmdline = %PYTHON% %FILE%
timeout = 20

[shutdown]
message = 987654321
timeout = 20
### END NODE INFO
"""
from labrad.server import Signal, setting
from twisted.internet.defer import returnValue

from server_tools.device_server import DeviceServer

UPDATE_ID = 698327


class FrequencyCounterServer(DeviceServer):
    update = Signal(UPDATE_ID, 'signal: update', 's')
    name = 'frequency_counter'

    @setting(10, returns='v')
    def frequency(self, c):
        device = self.get_selected_device(c)
        frequency = yield device.get_frequency()
        returnValue(frequency)


if __name__ == "__main__":
    from labrad import util
    util.runServer(FrequencyCounterServer())
    @inlineCallbacks
    def ForceRead(self):
        command = self.ForceReadStr()
        yield self.ser.write(command)
  
    def IdenStr(self):
        return '*IDN?'+'\n'

    # string to force read
    def ForceReadStr(self):
        return '++read eoi' + '\n'
    # string for prologix to request a response from instrument, wait can be 0 for listen / for talk
    def WaitRespStr(self, wait):
        return '++auto '+ str(wait) + '\n'
    
    # string to set the addressing of the prologix
    def SetAddrStr(self, addr):
        return '++addr ' + str(addr) + '\n'
    
    # Set the number of triggers
    def SetTrigCount(self, count):
        return 'TRIG:COUNT ' + str(count) + '\n'
    
    # start measurement
    def startMeasurement(self):
        return 'READ?' + '\n'
    
if __name__ == "__main__":
    from labrad import util
    util.runServer(KEITHLY6487())
            rawdata = []
        if len(rawdata) != 0:
            if self.currentMode == 'Normal':
                toDataVault = [ [elem[2] - self.startTime, elem[0], 0, 0] for elem in rawdata] # converting to format [time, normal count, 0 , 0]
            elif self.currentMode =='Differential':
                toDataVault = self.convertDifferential(rawdata)
            self.processRequests(toDataVault) #if we have any requests, process them
            self.processSignals(toDataVault)
            try:
                yield self.dv.add(toDataVault)
            except:
                print 'Not Able to Save To Data Vault'
    
    def processSignals(self, data):
        lastPt = data[-1]
        NormalCount = lastPt[1]
        self.onNewCount(NormalCount)
    
    def convertDifferential(self, rawdata):
        totalData = []
        for dataPoint in rawdata:
            t = str(dataPoint[1])
            self.lastDifferential[t] = float(dataPoint[0])
            diff = self.lastDifferential['ON'] - self.lastDifferential['OFF']
            totalData.append( [ dataPoint[2] - self.startTime, self.lastDifferential['ON'], self.lastDifferential['OFF'], diff ] )
        return totalData

if __name__ == "__main__":
    from labrad import util
    util.runServer( NormalPMTFlow() )
Example #25
0
        dev = self.selectDevice(c)
        chan = chan + 8
        if value > 2**16 - 1:
            value = 2**16 - 1
        elif value < 0:
            value = 0

        value = bin(value)[2:]

        if len(value) != 16:
            buff = 16 - len(value)
            value = '0'*buff + value

        value1 = value[0:8]
        value1 = int('0b' + value1, 2)
        value2 = value[8:]
        value2 = int('0b' + value2, 2)
        print 'chan = ', chan
        print 'first byte = ', value1
        print 'second byte = ', value2
        yield dev.write(chr(chan))
        yield dev.write(chr(value1))
        yield dev.write(chr(value2))

TIMEOUT = Value(1, 's')

if __name__ == "__main__":
    from labrad import util
    util.runServer(DAC8718())
    @setting(5, 'Process New Data', processName='s', newdata='?', returns='')
    def processNewData(self, c, processName, newdata):
        """
        Starts execution the specified process.  to execution to
        set any required inputs for the process.
        """
        if processName not in c['processInstances'].keys():
            raise Exception('Process does not exist')
        instance = c['processInstances'][processName]
        yield deferToThread(instance.processNewData, newdata)

    @setting(6, 'Get Result', processName='s', returns='?')
    def getResult(self, c, processName):
        if processName not in c['processInstances'].keys():
            raise Exception('Process does not exist')
        instance = c['processInstances'][processName]
        result = yield deferToThread(instance.getResult)
        returnValue(result)

    #@setting closeProcess (if necessary)
    #expireContext (if necessary)

    def initContext(self, c):
        c['inputs'] = {}
        c['processInstances'] = {}


if __name__ == "__main__":
    from labrad import util
    util.runServer(dataProcessor())
Example #27
0
    @setting(6, "Refresh Parameters", returns = '')
    def refresh_parameters(self, c):
        """Saves Parameters To Registry, then realods them"""
        yield self.save_parameters()
        yield self.load_parameters()
    
    @setting(7, "Reload Parameters", returns = '')
    def reload_parameters(self, c):
        """Discards current parameters and reloads them from registry"""
        yield self.load_parameters()

    @setting(8, 'Verify Parameter Defined', collection = 's', parameter_name = 's', returns = 'b')
    def verify_parameter_defined(self, c, collection, parameter_name):
        key = (collection, parameter_name)
        if key in self.parameters.keys():
            return True
        else:
            return False

    @inlineCallbacks
    def stopServer(self):
        try:
            yield self.save_parameters()
        except AttributeError:
            #if values don't exist yet, i.e stopServer was called due to an Identification Error
            pass
      
if __name__ == "__main__":
    from labrad import util
    util.runServer(ParameterVault())
Example #28
0
                print str(e)
                print 'Error: disconnecting...'
                self.disconnect()
        else:
            self.toWrite = volt

    @setting(1, 'Get Voltage', returns='v: previous voltage')
    def getVoltage(self, c):
        return self.lastVoltage

    def VoltageToFormat(self, volt):
        """
        function converts input voltage to microcontroller scale
        1023 is 4000 volts, scale is linear
        """
        if not 0 < volt < 4000: raise DCVSError('voltage not in range')
        num = round((volt / 4000.0) * 1023)
        return int(num)

    def MakeComString(self, num):
        """
        takes a a number of converts it to a string understood by microcontroller, i.e 23 -> C0023!
        """
        comstring = 'C' + str(num).zfill(4) + '!'
        return comstring


if __name__ == "__main__":
    from labrad import util
    util.runServer(DC0Server())
        self.setpoint = position_dict.copy()

    @setting(4, 'Return to setpoint')
    def return_to_setpoint(self, c):
        """
        Return all axes to the saved setpoint
        """
        axes = [1, 2, 3, 4]
        yield self.inCommunication.acquire()
        for axis in axes:
            yield self.controller.absolute_move( axis, self.setpoint[axis] )
            pos = self.setpoint[axis]
            self.position_dict[axis] = pos
            self.notifyOtherListeners(c, (axis, pos))
        self.inCommunication.release()

    def notifyOtherListeners(self, context, message):
        notified = self.listeners.copy()
        notified.remove(context.ID)
        self.on_position_change(message, notified)

    def initContext(self, c):
        self.listeners.add(c.ID)
    
    def expireContext(self, c):
        self.listeners.remove(c.ID)

if __name__ == "__main__":
    from labrad import util
    util.runServer( PicomotorServer() )
    @setting(11, host_kwargs_json='s', num='i', encoding='s', returns='s')
    def read(self, c, host_kwargs_json, num=-1, encoding='utf-8'):
        host_kwargs = json.loads(host_kwargs_json)
        inst = self._get_inst(**host_kwargs)
        response = inst.read(num, encoding)
        return response

    @setting(12, host_kwargs_json='s', returns='v')
    def get_timeout(self, c, host_kwargs_json):
        host_kwargs = json.loads(host_kwargs_json)
        inst = self._get_inst(**host_kwargs)
        return inst.timeout

    @setting(13, host_kwargs_json='s', timeout='v')
    def set_timeout(self, c, host_kwargs_json, timeout):
        host_kwargs = json.loads(host_kwargs_json)
        inst = self._get_inst(**host_kwargs)
        inst.timeout = timeout

    @setting(14, host_kwargs_json='s', message='s', encoding='s')
    def write(self, c, host_kwargs_json, message, encoding='utf-8'):
        host_kwargs = json.loads(host_kwargs_json)
        inst = self._get_inst(**host_kwargs)
        return inst.write(message, encoding)


if __name__ == '__main__':
    from labrad import util
    util.runServer(VXI11Server())
Example #31
0
            error = self.parent.parent.SetImage(1,1,self.parent.hstart,self.parent.hend,self.parent.vstart,self.parent.vend)
            print 'image error: ', error

        
    def closeEvent(self, evt):
        self.parent.parent.abortVideo()
        try:
            self.killTimer(self.cmon.timer)
        except AttributeError:
            pass 
        self.parent.reactor.stop() 
        
class MinimalServer(LabradServer):
    """This docstring will appear in the LabRAD helptext."""
    name = "Minimal Server"
    
    def initServer(self):
        self.win = AppWindow(self)
        self.win.show()        
        

    @setting(10, "Echo", data="?", returns="?")
    def echo(self, c, data):
        """This docstring will appear in the setting helptext."""
        print type(data)
        return data

if __name__ == "__main__":
    from labrad import util
    util.runServer(MinimalServer())
Example #32
0
                self.writeVoltages(voltages)
        else:
            if voltages != self._vToWrite:
                self._vToWrite = voltages

    @setting(2, "Get", returns="*v")
    def Get(self, c):
        """Get voltages"""
        return self._voltages


#function converts input voltage to microcontroller scale
#1023 is 4000 volts, scale is linear
def VoltageToFormat(volt):
    if (volt < 0 or volt > 4000):
        volt = 0
        print 'wrong voltage entered'
    num = round((volt / 4000.0) * 1023)
    return int(num)


#takes a a number of converts it to a string understood by microcontroller, i.e 23 -> C0023!
def MakeComString(num):
    comstring = 'C' + str(num).zfill(4) + '!'
    return comstring


if __name__ == "__main__":
    from labrad import util
    util.runServer(DCServer())
        return dp.amplRange
    
    @setting(9, "Device ID", returns = 's')
    def deviceID(self, c):
        """Returns the frequency range in the current context"""
        dp = self.getDP(c)
        return dp.deviceID
    
    def getDP(self, context):
        if not 'doublePass' in context.keys(): raise Exception ('Double Pass not selected')
        return context['doublePass']
    
    def notifyOtherListeners(self, context, chanInfo):
        """
        Notifies all listeners except the one in the given context
        """
        notified = self.listeners.copy()
        notified.remove(context.ID)
        self.onNewUpdate(chanInfo, notified)
    
    def initContext(self, c):
        """Initialize a new context object."""
        self.listeners.add(c.ID)
    
    def expireContext(self, c):
        self.listeners.remove(c.ID)
    
if __name__ == "__main__":
    from labrad import util
    util.runServer(Synthesizers())
Example #34
0
            elif err == -8:
                error_string = 'DeviceNotOpen'
            elif err == -9:
                error_string = 'InvalidEndpoint'
            elif err == -10:
                error_string = 'InvalidBlockSize'
            elif err == -11:
                error_string = 'I2CRestrictedAddress'
            elif err == -12:
                error_string = 'I2CBitError'
            elif err == -13:
                error_string = 'I2CNack'
            elif err == -14:
                error_string = 'I2CUnknownStatus'
            elif err == -15:
                error_string = 'UnsupportedFeature'
            elif err == -16:
                error_string = 'FIFOUnderflow'
            elif err == -17:
                error_string = 'FIFOOverflow'
            elif err == -18:
                error_string = 'DataAlignmentError'

            raise RuntimeError('Opal Kelly failed with error %s' %
                               (error_string))


if __name__ == "__main__":
    from labrad import util
    util.runServer(PTS())
Example #35
0
        self.listeners.remove(c.ID)
    
    @inlineCallbacks
    def stopServer(self):
        '''save the latest voltage information into registry'''
        try:
            yield self.client.registry.cd(['','Servers', 'DAC'], True)
            for name,channel in self.d.iteritems():
                yield self.client.registry.set(name, channel.voltage)
        except AttributeError:
            #if dictionary doesn't exist yet (i.e bad identification error), do nothing
            pass

    @setting(3, "Set Endcaps", voltage = 'v[V]', returns = '')
    def setEndcaps(self, c, voltage):
        for channel in ['comp1', 'comp2']:
            try:
                chan = self.d[channel]
                minim,total,channel_number = chan.min_voltage, chan.vpp, chan.channel_number
            except KeyError:
                raise Exception ("Channel {} not found".format(channel))
            voltage_value = voltage['V']
            value = self.voltage_to_val(voltage_value, minim, total)
            yield self.do_set_voltage(channel_number, value)
            chan.voltage = voltage_value
            self.notifyOtherListeners(c, (channel, voltage_value), self.onNewVoltage)

if __name__ == "__main__":
    from labrad import util
    util.runServer( DAC() )
Example #36
0
        f(message, notified)

    def initContext(self, c):
        """Initialize a new context object."""
        self.listeners.add(c.ID)

    def expireContext(self, c):
        self.listeners.remove(c.ID)

    @inlineCallbacks
    def stopServer(self):
        '''save the latest voltage information into registry'''
        ## set zero all channels when closing the server#
        for name, channel in self.d.iteritems():
            self.setVoltage(1, name, WithUnit(0.0, 'V'))


#         try:
#             #yield self.client.registry.cd(['','Servers', 'DAC'], True)
#             print "here"
#             for name,channel in self.d.iteritems():
#                 yield self.client.registry.set(name, channel.voltage)
#             print "lala"
#         except AttributeError:
#             #if dictionary doesn't exist yet (i.e bad identification error), do nothing
#             pass

if __name__ == '__main__':
    from labrad import util
    util.runServer(NI_Analog_Server())
    def SweepContinueStr(self):
        """String to continue sweeping (from pause point)"""
        return 'SWEEP:CONT' + '\n'

    def SweepResetStr(self):
        """String to reset sweeping point to start"""
        return 'SWEEP:RESET' + '\n'

    # ===== PROLOGIX =====

    def ForceReadStr(self):
        """String to force progolix to read device response"""
        return '++read eoi' + '\n'

    def WaitRespStr(self, wait):
        """String for prologix to request a response from instrument"""
        return '++auto ' + str(wait) + '\n'

    def EOIStateStr(self, state):
        """String to enable/disable EOI assertion with last character.
        State = 1 for enable, 0 for disable."""
        return '++eoi ' +  str(state) + '\n'
    
    def SetAddrStr(self, addr):
        """String to set addressing of prologix"""
        return '++addr ' +  str(addr) + '\n'

if __name__ == "__main__":
    from labrad import util
    util.runServer(MarconiServer())
Example #38
0
        if state:
            comstr = 'OUTP:STAT ON' + '\n'
        else:
            comstr = 'OUTP:STAT OFF' + '\n'
        return comstr

    # string to request current power
    def PowerReqStr(self):
        return 'POW:AMPL?' + '\n'

    # string to set power (in dBm)
    def PowerSetStr(self, pwr):
        return 'POW:AMPL ' + str(pwr) + 'DBM' + '\n'

    # string to force read
    def ForceReadStr(self):
        return '++read eoi' + '\n'

    # string for prologix to request a response from instrument, wait can be 0 for listen / for talk
    def WaitRespStr(self, wait):
        return '++auto ' + str(wait) + '\n'

    # string to set the addressing of the prologix
    def SetAddrStr(self, addr):
        return '++addr ' + str(addr) + '\n'


if __name__ == "__main__":
    from labrad import util
    util.runServer(HPServer())
Example #39
0
        return 'DATa:WIDth 1'

    def getYmultistr(self):
        return 'WFMPre:YMUlt?'

    def getYoffstr(self): #get Yoffset
        return 'WFMPre:YOFf?'

    def getY0str(self): #get Y0
        return 'WFMPre:YZEro?'

    def getdatalengthstr(self): #gets the number of elements sent by oscilloscope
        return 'DATa:STOP?'

    def setsingletriggerstr(self): #stops aqu. after single trigger
        return 'ACQuire:STOPAfter SEQuence'

    def getreadystr(self): #asks if Osc is ready to trigger
        return 'ACQuire:STATE 1'

    def setreadystr(self): #turns on aquisition
        return 'ACQuire:STATE?'

    def getDatastr(self): #gets current displayed waveform data
        return 'CURVe?'

        
if __name__ == "__main__":
    from labrad import util
    util.runServer(TPSserver())
Example #40
0

    @inlineCallbacks
    def ForceRead(self):
        command = self.ForceReadStr()
        yield self.ser.write(command)
  
    def IdenStr(self):
        return '?010\r'

    # string to force read
    def ForceReadStr(self):
        return '++read eoi' + '\n'
    
    def ChangeHex(self, label):
        if (label<16):
            x = '0'+hex(label).split('x')[1]
        else:
            x = hex(label).split('x')[1]
        return x
    
    def actRelayStr(self, label):
        return '!013'+ self.ChangeHex(label) + '\r'
    
    def deactRelayStr(self, label):
        return '!014'+ self.ChangeHex(label) + '\r'

if __name__ == "__main__":
    from labrad import util
    util.runServer( IA3133server() )
    def getState(self,c, label):
        ready = self.stateDict[label + 'displacement']
        yield ready
        returnValue(ready)
    

    def labelToNum(self, label):
        if label == 'x1':
            return '1'    
        if label == 'y1':
            return '2'
        if label == 'x2':
            return '3'    
        if label == 'y2':
            return '4'   
        else:
            return '5'

    def gtStateStr(self, label):
        return self.labelToNum(label) + 'TS\r\n'
     
    def gtDispStr(self, label):
        return self.labelToNum(label) + 'TP?\r\n'
    
    def mvAbsStr(self, label, netDisp):
        return self.labelToNum(label) + 'PA' + str(netDisp) + '\r\n'

if __name__ == "__main__":
    from labrad import util
    util.runServer(STS())
Example #42
0
                .format(script_ID))
        status.error_finish_confirmed(error_message)
        self.scheduler.remove_if_external(script_ID)

    @inlineCallbacks
    def stopServer(self):
        '''
        stop all the running scripts and exit
        '''
        yield None
        try:
            #cancel all scheduled scripts
            for scheduled, name, loop in self.scheduler.get_scheduled():
                self.scheduler.cancel_scheduled_script(scheduled)
            for ident, scan, priority in self.scheduler.get_queue():
                self.scheduler.remove_queued_script(ident)
            #stop all running scipts
            for ident, name in self.scheduler.get_running():
                self.scheduler.stop_running(ident)
            #wait for all deferred to finish
            running = DeferredList(self.scheduler.running_deferred_list())
            yield running
        except AttributeError:
            #if dictionary doesn't exist yet (i.e bad identification error), do nothing
            pass


if __name__ == "__main__":
    from labrad import util
    util.runServer(ScriptScanner())
Example #43
0
        Returns true if Paul Box sequence has completed within a timeout period
        """
        requestCalls = int(timeout / 0.050 ) #number of request calls
        for i in range(requestCalls):
            yield self.inCommunication.acquire()
            done = yield deferToThread(self._isSequenceDone)
            yield self.inCommunication.release()
            if done: returnValue(True)
            yield deferToThread(time.sleep, 0.050)
        returnValue(False)
        
    def notifyOtherListeners(self, context, message):
        """
        Notifies all listeners except the one in the given context
        """
        notified = self.listeners.copy()
        notified.remove(context.ID)
        self.onNewUpdate(message, notified)     
            
    def initContext(self, c):
        """Initialize a new context object."""
        self.listeners.add(c.ID)
    
    def expireContext(self, c):
        self.listeners.remove(c.ID)
                           

if __name__ == "__main__":
    from labrad import util
    util.runServer( TriggerFPGA() )
Example #44
0
             'Multiple Fit',
             sparam='s',
             dirname='*s',
             shunt='b',
             ifcal='b',
             caldir='*s',
             calnum='w',
             ifrange='b',
             rangemin='v',
             rangemax='v',
             ifback='b',
             backmin='v',
             backmax='v',
             backorder='w',
             returns='?')
    def multiple_fit(self, c, sparam, dirname, shunt, ifcal, caldir, calnum,
                     ifrange, rangemin, rangemax, ifback, backmin, backmax,
                     backorder):
        """Fits multiple S21 traces with calibration."""
        fitDict = yield self.multifile_fit(
            sparam, dirname, shunt, (ifcal, caldir, calnum),
            (ifrange, rangemin, rangemax),
            (ifback, backmin, backmax, backorder))
        returnValue(tuple(fitDict.items()))


#Run this server if this is being run as a script, not imported by another script.
if __name__ == "__main__":
    from labrad import util
    util.runServer(ResonatorFit())
Example #45
0
    def FreqSetStr(self,freq):
	return 'SOURce:FREQuency '+ str(freq) +'MHZ'+'\n'
	  
    # string to request on/off?
    def StateReqStr(self):
	return 'OUTput:STATe?'+'\n'

    # string to set on/off (state is given by 0 or 1)
    def StateSetStr(self, state):
	return 'OUTput:STATe '+ str(state) +'\n'

    # string to request current power
    def PowerReqStr(self):
	return 'POWer?'+'\n'

    # string to set power (in dBm)
    def PowerSetStr(self,pwr):
	return 'POWer '+ str(pwr)+'\n'
	  
    # string for prologix to request a response from instrument, wait can be 0/1
    def WaitRespStr(self, wait):
	return '++auto '+ str(wait) + '\n'
	  
    # string to set the addressing of the prologix
    def SetAddrStr(self, addr):
	return '++addr ' + str(addr) + '\n'

if __name__ == "__main__":
    from labrad import util
    util.runServer(DCServer())
Example #46
0
             exposure='w : exposure in ms',
             returns='')
    def setExposure(self, c, chanName, exposure):
        self.validateInput(chanName, 'channelName')
        self.validateInput(exposure, 'exposure')
        self.info.setExposure(chanName, exposure)
        notified = self.getOtherListeners(c)
        self.onNewExposure((chanName, exposure), notified)
        self.saveChannelInfo()

    @setting(9,
             'Get Wavelength From Channel',
             chanName='s: name of the channel, i.e 422',
             returns='s')
    def wlfromch(self, c, chanName):
        self.validateInput(chanName, 'channelName')
        return self.info.getWavelength(chanName)

    @setting(10,
             'Get Frequency',
             chanName='s: name of the channel, i.e 422',
             returns='v: laser frequency')
    def getFreq(self, c, chanName):
        self.validateInput(chanName, 'channelName')
        return self.info.getFreq(chanName)


if __name__ == "__main__":
    from labrad import util
    util.runServer(Multiplexer())
Example #47
0
            self.prevoutput = output
            self.server.set_dac_voltage(self.dac, output)

    @setting(13, state='b')
    def toggle(self, c, state):
        '''
        Sends switches cal vs switcher
        '''
        if state:
            self.lc.start(self.timer)
        else:
            self.lc.stop()

    @setting(14, value='v')
    def offset(self, c, value):
        yield self.server.set_dac_voltage(3, value)
        self.prevoutput = value

    @setting(15, gain='v')
    def set_gain(self, c, gain):
        self.gain = gain

    @setting(16, setpoint='v')
    def set_point(self, c, setpoint):
        self.set = setpoint


if __name__ == "__main__":
    from labrad import util
    util.runServer(ind_WM_lock_Server())
Example #48
0
    @setting(4, 'Write', string='s')
    def write(self, c, string):
        self.inCommunication.acquire()
        self.ser.write(string)
        self.inCommunication.release()

    @setting(5, 'Update IO')
    def update_IO(self, c):
        self.inCommunication.acquire()
        self.ser.write('U\r')
        self.inCommunication.release()

    @setting(6, 'Reset IO')
    def reset_IO(self, c):
        self.inCommunication.acquire()
        self.ser.write('S\r')
        self.inCommunication.release()

    def _read(self):
        self.inCommunication.acquire()
        data = ""
        data += self.ser.read(1)
        while self.ser.in_waiting:
            data += self.ser.read()
        return data


if __name__ == "__main__":
    from labrad import util
    util.runServer(AD9910())
Example #49
0
            for collection, parameter_name in parameters:
                defined = yield pv.verify_parameter_defined(collection, parameter_name)
                if not defined: invalid.append( (collection, parameter_name) )
        returnValue( invalid )

    @inlineCallbacks
    def stopServer(self):
        '''
        stop all the running scripts and exit
        '''
        yield None
        try:
            #cancel all scheduled scripts
            for scheduled,name,loop in self.scheduler.get_scheduled():
                self.scheduler.cancel_scheduled_script(scheduled)
            for ident, scan, priority in self.scheduler.get_queue():
                self.scheduler.remove_queued_script(ident)
            #stop all running scipts
            for ident, name in self.scheduler.get_running():
                self.scheduler.stop_running(ident)
            #wait for all deferred to finish
            running = DeferredList(self.scheduler.running_deferred_list())
            yield running
        except AttributeError:
            #if dictionary doesn't exist yet (i.e bad identification error), do nothing
            pass

if __name__ == "__main__":
    from labrad import util
    util.runServer( ScriptScanner() )
Example #50
0
            serial = fp.GetDeviceListSerial(i)
            tmp = ok.FrontPanel()
            tmp.OpenBySerial(serial)
            device_id = tmp.GetDeviceID()
            print(device_id)
            tmp.LoadDefaultPLLConfiguration()
            self.interfaces[device_id] = tmp

    @setting(3, filename='s')
    def program_bitfile(self, c, filename):
        self.call_if_available('ConfigureFPGA', c,
                               'bit_files' + SEP + filename)

    @setting(11, wire='i', byte_array='s')
    def write_to_pipe_in(self, c, wire, byte_array):
        byte_array = json.loads(byte_array)
        self.call_if_available('WriteToPipeIn', c, wire, bytearray(byte_array))

    @setting(12, wire='i', value='i')
    def set_wire_in(self, c, wire, value):
        self.call_if_available('SetWireInValue', c, wire, value)

    @setting(13)
    def update_wire_ins(self, c):
        self.call_if_available('UpdateWireIns', c)


if __name__ == "__main__":
    from labrad import util
    util.runServer(OKFPGAServer())
Example #51
0
        # important to set this before specifying voltages
        if load > 50:
            command_strings.append(r":OUTP:LOAD INF")
        else:
            command_strings.append(r":OUTP:LOAD 50")
        command_strings.append(r":OUTP:POL NORM")

        command_strings.append(r":VOLT:RANG:AUTO ON")

        freq = 1.0 / ttot
        command_strings.append(":FREQ %f" % freq)

        command_strings.append(r":VOLT:HIGH %f" % Vtop)
        command_strings.append(r":VOLT:LOW %f" % Vbot)

        command_strings.append(r":OUTP ON")

        command_total = ""
        for s in command_strings:
            command_total += s + ";"

        self.inst.write(command_total)

        print "Sent: %s" % command_total


if __name__ == "__main__":
    from labrad import util

    util.runServer(Agilent_Arb())
        if func == 'SINE':
            comstr = 'FUNCtion ' + 'SIN' + '\r\n'
        elif func == 'SQUARE':
            comstr = 'FUNCtion ' + 'SQU' + '\r\n'
        elif func == 'RAMP':
            comstr = 'FUNCtion ' + 'RAMP' + '\r\n'
        elif func == 'PULSE':
            comstr = 'FUNCtion ' + 'PULSe' + '\r\n'
        elif func == 'NOISE':
            comstr = 'FUNCtion ' + 'NOISe' + '\r\n'
        elif func == 'DC':
            comstr = 'FUNCtion ' + 'DC' + '\r\n'
        return comstr

    # string to force read
    def ForceReadStr(self):
        return '++read eoi' + '\r\n'

    # string for prologix to request a response from instrument, wait can be 0 for listen / for talk
    def WaitRespStr(self, wait):
        return '++auto ' + str(wait) + '\r\n'

    # string to set the addressing of the prologix
    def SetAddrStr(self, addr):
        return '++addr ' + str(addr) + '\r\n'


if __name__ == "__main__":
    from labrad import util
    util.runServer(AgilentServer())
Example #53
0

    def wait(self, seconds, result=None):
        """Returns a deferred that will be fired later"""
        d = Deferred()
        reactor.callLater(seconds, d.callback, result)
        return d

    def stop(self):
        self._stopServer()

    @inlineCallbacks
    def stopServer(self):
        """Shuts down camera before closing"""
        try:
            if self.gui.live_update_running:
                yield self.gui.stop_live_display()
            print 'acquiring: {}'.format(self.stopServer.__name__)
            yield self.lock.acquire()
            print 'acquired : {}'.format(self.stopServer.__name__)
            self.camera.shut_down()
            print 'releasing: {}'.format(self.stopServer.__name__)
            self.lock.release()
        except Exception:
            #not yet created
            pass

if __name__ == "__main__":
    from labrad import util
    util.runServer(AndorServer())
Example #54
0
            #self.server.set_dac_voltage(self.dac, output)

    @setting(13, state='b')
    def toggle(self, c, state):
        '''
        Sends switches cal vs switcher
        '''
        if state:
            self.lc.start(self.timer)
        else:
            self.lc.stop()

    @setting(14, value='v')
    def offset(self, c, value):
        #yield self.server.set_dac_voltage(self.dac, value)
        print value
        self.prevoutput = value

    @setting(15, gain='v')
    def set_gain(self, c, gain):
        self.gain = gain

    @setting(16, setpoint='v')
    def set_point(self, c, setpoint):
        self.set = setpoint


if __name__ == "__main__":
    from labrad import util
    util.runServer(ind_WM_lock_Server())
        self.acq.force_stop = False
        self.thd_acq.start()
        
        print time.time()
        
        return 0
    
    @setting(2,'is_running',returns='w')
    def is_running(self,c):
        #if self.acq.running:
        #    return 1
        if getattr(self,'subproc_running',None) is not None:
            if self.subproc_running.value is True:
                #print "Acquisition already running!"
                return 1
        return 0
        
    @setting(3,'force_stop')
    def force_stop(self,c):
        self.acq.force_stop = True


    

if __name__ == "__main__":
    from labrad import util
    util.runServer(HRMTime())

#os.execlp('python ',sys.argv[0])
#os.spawnv(os.P_NOWAIT,sys.executable, (sys.executable,sys.argv[0]) )
#os.execv(sys.executable, [sys.executable] + sys.argv)
Example #56
0
        previous_experiment_numbers = [
            int(pathname.split('#')[-1]) for pathname in previous_experiments
        ]
        if previous_experiment_numbers:
            experiment_number = max(previous_experiment_numbers) + 1
        else:
            experiment_number = 0
        self.experiment['experiment_number'] = experiment_number
        self.experiment['name'] = os.path.join(
            time_string, '{}#{}'.format(name, experiment_number))

    def _log_experiment_number(self):
        log_path = os.path.join(self.experiment_directory,
                                self.experiment.get('name'))
        log_dir, log_name = os.path.split(log_path)
        if not os.path.isdir(log_dir):
            os.makedirs(log_dir)
        open(log_path, 'a').close()

    def _send_update(self, update):
        update_json = json.dumps(update, default=lambda x: None)
        self.update(update_json)


Server = ConductorServer

if __name__ == "__main__":
    from labrad import util
    reactor.suggestThreadPoolSize(5)
    util.runServer(Server())
Example #57
0
        self.listeners.remove(c.ID)

    def getOtherListeners(self, c):
        notified = self.listeners.copy()
        notified.remove(c.ID)
        return notified

    @setting(1, "get_wavelength", returns='v')
    def get_wavelength(self, c):
        yield None
        returnValue(self.freqchanged)

    @setting(2, "get_power", returns='v')
    def get_power(self, c):
        yield None
        returnValue(self.powerchanged)

    def measure(self):
        # TODO: Improve this with a looping call
        wl = self.dll.CLGetLambdaReading(self.handle)
        power = self.dll.CLGetPowerReading(self.handle)
        self.freqchanged = wl
        self.powerchanged = power
        reactor.callLater(0.1, self.measure)



if __name__ == "__main__":
    from labrad import util
    util.runServer(BristolServer())
Example #58
0
        Starts or stops continous motion in forward direction. Other kinds of motions are stopped.

        Parameters
            axisNo	Axis number (0 ... 2)
            start	Starts (1) or stops (0) the motion
            backward	If the move direction is forward (0) or backward (1)
        Returns
            None
        '''
        yield ANC.startContinousMove(self.device, axisNo, start, backward)

    @setting(131, axisNo='i', backward='b', returns='')
    def start_single_step(self, c, axisNo, backward):
        '''
        Triggers a single step in desired direction.

        Parameters
            axisNo	Axis number (0 ... 2)
            backward	If the step direction is forward (0) or backward (1)
        Returns
            None
        '''
        yield ANC.startSingleStep(self.device, axisNo, backward)


__server__ = ANC350Server()

if __name__ == '__main__':
    from labrad import util
    util.runServer(__server__)
Example #59
0
                 subject='s', msg='s', username='******', returns='b{success}*s{failures}')
    def send_mail(self, c, toAddrs, subject, msg, username='******'):
        success, failures = email(toAddrs, subject, msg, self.domain, self.smtpServer, username, self.password)
        return (success, failures)
            
    @setting(11, subject='s', msg='s', recipients=['*s','s'], username='******', returns='b{success}*s{failures}')
    def send_sms(self, c, subject, msg, recipients, username='******'):
        if not isinstance(recipients,list):
            recipients = [recipients]
        recipients = [self.smsUsers[name.upper()] for name in recipients if name.upper() in self.smsUsers]
        success, failures = textMessage(recipients, subject, msg, self.domain, self.smtpServer, username, self.password)
        return (success, failures)


    @setting(12, returns='ss')
    def dump_data(self, c):
        return (str(self.domain), str(self.smtpServer))

    @setting(20, returns='')
    def refresh_connection_data(self, c):
        yield self._refreshConnectionData()
    @setting(25, returns='*s')
    def userlist(self, c):
        return self.smsUsers.keys()

__server__ = TelecommServer()

if __name__ == '__main__':
    from labrad import util
    util.runServer(__server__)
Example #60
0
    def initContext(self, c):
        self.listeners.add(c.ID)

    def expireContext(self, c):
        self.listeners.remove(c.ID)
    
    def notifyOtherListeners(self, context):
        notified = self.listeners.copy()
        try: notified.remove(context.ID)
        except: pass
        self.onNewUpdate('Channels updated', notified)

if __name__ == "__main__":
    from labrad import util
    util.runServer( DACServer() )

"""
Notes for DACSERVER:

example of a Cfile corresponding to a trap w/ 23 electrodes, 4 multipole values, and (axial) trap position of 850um:

multipoles: Ex, Ey, Ez, U2
Ex_1
Ex_2
.
.
.
Ex_23
Ey_1
.