hpib.py 2.2 KB
Newer Older
1
2
3
4
5
6
"""Implementation of the GPIB protocol for use with serial.threading

This class implements the GPIB (General Purpose Interface Bus) protocol following the example at
https://github.com/pyserial/pyserial/blob/master/examples/at_protocol.py
"""

7
8
9
10
11
12
13
14
15
16
import serial.threaded
import threading

try:
    import queue
except ImportError:
    import Queue as queue


class GPIBProtocol(serial.threaded.LineReader):
Tammo Jan Dijkema's avatar
Tammo Jan Dijkema committed
17
18
    """Implementation of the GPIB protocol"""

19
20
21
22
23
24
25
26
    TERMINATOR = b'\n'

    def __init__(self):
        super(GPIBProtocol, self).__init__()
        self.responses = queue.Queue()
        self.lock = threading.Lock()

    def init_hpib(self):
Tammo Jan Dijkema's avatar
Tammo Jan Dijkema committed
27
        """Execute some setup commands for the HPIB system"""
28
29
30
31
32
33
34
35
36
37
        with self.lock:
            self.write_line("++savecfg 0")
            self.write_line("++auto 0")
            self.write_line("++eoi 1")
            self.write_line("++eos 2")
            self.write_line("++eot_enable 0")
            self.write_line("++eot_char 0")
            self.write_line("++read_tmo_ms 500")

    def command(self, command, timeout=0.2, address=None):
Tammo Jan Dijkema's avatar
Tammo Jan Dijkema committed
38
39
40
41
42
43
44
45
46
        """Execute a HPIB command

        Args:
            command (str): Command to execute (can be a query)
            timeout (float): How long to wait for a reply
            address (int): HPIB address to send the command to

        Returns:
             If the command contains '?', the value returned by
47
48
49
50
             the HPIB device is returned.

        Raises:
             RuntimeError: if no response was received to a query.
Tammo Jan Dijkema's avatar
Tammo Jan Dijkema committed
51
        """
52
53
54
55
56
57
58
        with self.lock:
            if address:
                self.write_line("++addr {:d}".format(address))
            self.write_line(command)
            if "?" in command:
                self.write_line("++read eoi")
                # The command was a query, wait for response
Tammo Jan Dijkema's avatar
Tammo Jan Dijkema committed
59
60
                try:
                    line = self.responses.get(timeout=timeout)
Tammo Jan Dijkema's avatar
Tammo Jan Dijkema committed
61
                except queue.Empty:
62
                    raise RuntimeError("HPIB device at address did not respond to query:", command)
63
64
65
66
67
                return line
            else:
                pass

    def handle_line(self, line):
Tammo Jan Dijkema's avatar
Tammo Jan Dijkema committed
68
        """Handle input from serial port, put it in the queue"""
69
        self.responses.put(line)