gpib_plotter.py

changeset 32
59da528bc470
parent 31
c869766e25ff
child 33
61809bb871bf
equal deleted inserted replaced
31:c869766e25ff 32:59da528bc470
1 import sys, os
2 import time
3 import gpib
4
5 import gpib
6 from prologix import GPIB
7 class GPIBplotter(GPIB):
8 _replies={
9 "OE": "0",
10 "OH": "0,0,10000,7500",
11 "OI": "7470A",
12 "OP": "0,0,10000,7500",
13 "OO": "0,1,0,0,0,0,0,0",
14 "OF": "40,40",
15 "OS": "24",
16 }
17 def __init__(self, device="/dev/ttyUSB0", baudrate=115200, timeout=0.1,
18 address=5):
19 super(GPIBplotter, self).__init__(device, baudrate, timeout, address, mode=0)
20
21 def plotStarted(self):
22 pass
23
24 def load_plot(self, wait_timeout=0):
25 """
26 Make a full plot process.
27
28 'wait_timeout' is the first timeout. Same semantic as the
29 'timeout' property of a serial connection (if set to None, it
30 will block until the GPIB device actually perform a plot
31 command.)
32 """
33 res = ""
34 i=0
35 replies = self._replies.copy()
36 if wait_timeout is not None and not isinstance(wait_timeout, (float, int)):
37 raise TypeError, "wait_timeout (%s:%s) has wrong type"%(repr(wait_timeout), type(wait_timeout))
38 if wait_timeout<0:
39 raise ValueError
40
41 self._cnx.timeout = wait_timeout
42 firstloop = True
43 newdata = False
44 while i<self._retries:
45 l = self._cnx.readline().strip()
46 if firstloop:
47 self._cnx.timeout = self._timeout
48 firstloop = False
49 self.plotStarted()
50 if l == "":
51 if i == 0:# > (self._retries/2):
52 # ie. we just received new stuffs (i is reset in the else block)
53 for k, v in replies.items():
54 # check wether we should reply smthg
55 eres = res.replace('\n', '').strip()
56 if eres.endswith(k) or eres.endswith(k+';') or eres.endswith(k+';OE'):
57 self._cnx.write("%s"%v)
58 if k == "OS":
59 replies[k] = "16"
60 break
61 self._cnx.write('\r')
62 #time.sleep(0.1)
63 i += 1
64 else:
65 if not res:
66 print "Plotting..."
67 res += l + '\n'
68 i = 0
69 #time.sleep(0.1)
70 if res:
71 print "DONE (received %d characters)"%len(res)
72 return res
73
74 if __name__ == '__main__':
75 import optparse
76 opt = optparse.OptionParser('A simple HP7470A GPIB plotter emulator for USB-GPIB bundle (ProLogix)')
77 opt.add_option('-f', '--filename', default=None,
78 dest='filename',
79 help='Output filename. If not set, write to stdout')
80 opt.add_option('-d', '--device', default='/dev/ttyUSB0',
81 dest='device',
82 help='Device of the RS232 connection (default: /dev/ttyUSB0)',
83 )
84 opt.add_option('-a', '--address', default=0,
85 dest='address',
86 help='GPIB address of the device',
87 )
88 opt.add_option('-l', '--loop', default=False,
89 action="store_true",
90 dest="loop",
91 help="Continuously wait for new plots. If set, filename must be set and files will be created with _n at the end")
92 opt.add_option('-v', '--verbose', default=False,
93 action="store_true",
94 dest="verbose",
95 help="Verbose mode",)
96
97 options, argv = opt.parse_args(sys.argv)
98
99 if options.loop and not options.filename:
100 opt.error('If loop is set, you *must* provide a filename')
101
102 if options.filename:
103 outf = open(options.filename, "w")
104 else:
105 outf = sys.stdout
106
107
108 try:
109 plotter = GPIBplotter(device=options.device, address=int(options.address),
110 timeout=0.06)
111 except (gpib.SerialException, gpib.ConnectionError), e:
112 sys.stderr.write('Connection error:\n\t' + '\n\t'.join([str(x) for x in e.args]) + '\n')
113 sys.stderr.write('Check your parameters\n')
114 sys.exit(1)
115 if options.verbose:
116 sys.stderr.write('connection established\n')
117
118 loop = True
119 nloop = 0
120 while loop:
121 plot = plotter.load_plot(wait_timeout=0.1)
122 if options.verbose:
123 sys.stderr.write('.')
124 if plot:
125 outf.write(plot)
126 if options.verbose:
127 sys.stderr.write('\n')
128 sys.stderr.write('Received a new plot (written to %s)\n'%outf.name)
129 if not options.loop:
130 loop = False
131 else:
132 nloop += 1
133 fname, ext = os.path.splitext(options.filename)
134 outf = open(fname + "_%d"%nloop + ext, 'w')
135
136
137
138
139

mercurial