Demo entry 2157342

GPIB Communication

   

Submitted by anonymous on Jul 10, 2015 at 15:47
Language: Python. Code size: 5.6 kB.

#!/usr/bin/env python
import readline
import socket

class GPIB_Controller(object):
    ''' GPIB_Ethernet Controller.
    '''
    
    def __init__(self, ip, port):
        ''' Initialize a new connection to a GPIB-Ethernet Controller.
        Sets up a TCP connection to the controller at the specified ip address and port.
        '''
        self.ip = ip
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
        self.sock.connect((ip, port))
        self.sock.settimeout(1)
        # Initalize to the power meter.
        self.addr = 14
        
    def address(self, addr):
        ''' Change the address to the specified value. The address can range from 0 to 30.
        Args:
            int addr - address of the device to communicate with.
        Returns:
            None
        '''
        self.addr = addr
        self.send('++addr %d\n' % addr); self.read(prnt=False)
        
    def measure(self):
        ''' Query the power meter to return a measurement. Assumes the address is set to the power meter.
        Args:
            None
        Return:
            str res - the answer of the power meter.
            OR
            None - if the address is wrong.
        '''
        self.send('FETC?\n')
        res = self.read(prnt=False)
        return res
        
    def measure_temp(self, sens):
        ''' Query the temperature monitor to return a measurement. Assumes the address is set to the temperature monitor.
        Args:
            str sens - the sensor to read out
        Returns:
            str res - the answer of the temperature monitor.
            OR
            None - if the address is wrong.
        '''
        sensors = {'hot':1, 'cold':2, 'atm':4}
        self.send('KRDG? %d\n'%sensors[sens])
        res = self.read(prnt=False)
        return res
    
    def read(self, prnt=True, maxiter=2):
        ''' Read responses from the buffer. Keep looping until we receive None to make sure we have the response.
        Args:
            bool prnt - print the output to the console (default is True).
            int maxiter - number of secondary attempts to make when response is None (default is 2).
        Returns:
            str data or None - response of the GPIB controller.
        '''
        data = None
        itr = 0
        # Keep reading until we have everything.
        while (data is None) and (itr < maxiter):
            try:
                # Query the yellow box to speak to us.
                self.sock.send('++read \r\n')
                # Read from the socket; strip all whitespace (spaces, LF, CR etc.) on the right end.
                data = self.sock.recv(4096).rstrip()
            except socket.timeout:
                # No response or empty lines.
                pass
            finally:
                itr += 1
        if prnt:
            print data
        return data
    
    def send(self, cmd):
        ''' Send a command to the GPIB controller.
        Args:
            str cmd - command to send.
        Returns:
            bool True/False - success or failure of sending the command.
        '''
        try:
            self.sock.sendall(cmd+'\n')
            return True
        except:
            return False
    
    def set_measurespeed(self, rps=20, avg=1):
        ''' Sets the integration time of the telescope by specifiying the readings per second and the number of averages taken for a measurement.
        Args:
            int rps - readings per second. Available: 20, 40 or 200.
            int avg - number of averages for a measurement. Available: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024.
        Return:
            None
        '''
        rp = [20, 40, 200]
        av = [2**i for i in range(11)]
        rps = int(rps); avg = int(avg)
        if (rps not in rp) or (avg not in av):
            print 'Invalid value in measure speed.'
            return
        else:
            self.send('SENS:AVER:COUN %d' % avg)
            self.send('SENS:SPE %d' % rps)
    
    def get_measurespeed(self, p=True):
        ''' Requests the averaging rate and readings per second.
        Args:
            bool p - print the values to the terminal or not.
        Returns:
            int read - readings per second.
            int aver - the number of averages taken for a measurement.
        '''
        self.send('SENS:SPE?')
        aver = self.read(prnt=p)
        self.send('SENS:AVER:COUN?')
        read = self.read(prnt=p)
        return read, aver
        
    def units(self, un):
        ''' Set the units of measurement. Possible units are 'W' or 'dBm'.
        Args:
            str un - unit to return.
        Return:
            None
        '''
        u = un.lower()
        if u == 'w':
            self.send('UNIT:POW W')
            self.read(prnt=False)
        elif u == 'dbm':
            self.send('UNIT:POW DBM')
            self.read(prnt=False)
        else:
            print 'Invalid unit.'
            
    def quit(self):
        ''' Correctly close the connection to the controller.
        Args:
            None
        Return:
            None
        '''
        self.sock.close()
        
if __name__ == '__main__':
    YELLOW_BOX_IP = '192.168.0.142'
    PORT = 1234
    c = GPIB_Controller(YELLOW_BOX_IP, PORT)
    c.send('++ver')
    c.read()
    c.send('*idn?')
    c.read()
    while 1:
        cm = raw_input('>>> ')
        if cm == 'quit':
            c.quit()
            break
        else:
            c.send(cm)
            c.read()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).