-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontroller.go
More file actions
349 lines (319 loc) · 10.6 KB
/
controller.go
File metadata and controls
349 lines (319 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Copyright (c) 2020–2024 The prologix developers. All rights reserved.
// Project site: https://github.com/gotmc/prologix
// Use of this source code is governed by a MIT-style license that
// can be found in the LICENSE.txt file for the project.
package prologix
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"log"
"strings"
)
// ContextReader is an optional interface that an io.ReadWriter can implement
// to support context-aware reads.
type ContextReader interface {
ReadContext(ctx context.Context, p []byte) (n int, err error)
}
// ContextWriter is an optional interface that an io.ReadWriter can implement
// to support context-aware writes.
type ContextWriter interface {
WriteContext(ctx context.Context, p []byte) (n int, err error)
}
// Controller models a GPIB controller-in-charge.
type Controller struct {
rw io.ReadWriter
reader *bufio.Reader
primaryAddr int
hasSecondaryAddr bool
secondaryAddr int
auto bool
eoi bool
usbTerm byte
eotChar byte
debug bool // if true, print controller commands before sending. Set via WithDebug().
ar488 bool // compatibility with Arduino AR488 - see WithAR488 documentation for details.
}
// ControllerOption applies an option to the controller.
type ControllerOption func(*Controller)
// NewController creates a GPIB controller-in-charge at the given address using
// the given Prologix driver, which can either be a Virtual COM Port (VCP), USB
// direct, or Ethernet. Enable clear to send the Selected Device Clear (SDC)
// message to the GPIB address. Optionally controller configuration can be
// included using a ControllerOption.
func NewController(
rw io.ReadWriter,
addr int,
clear bool,
opts ...ControllerOption,
) (*Controller, error) {
c := Controller{
rw: rw,
reader: bufio.NewReader(rw),
primaryAddr: addr,
hasSecondaryAddr: false,
auto: false,
eoi: true,
usbTerm: '\n',
eotChar: '\n',
}
// Apply options using the functional option pattern.
for _, opt := range opts {
opt(&c)
}
// Verify validate primary address.
if !isPrimaryAddressValid(c.primaryAddr) {
return nil, fmt.Errorf("invalid primary address %d (must by 0-30)", c.primaryAddr)
}
// Configure the Prologix GPIB controller.
addrCmd := fmt.Sprintf("addr %d", c.primaryAddr)
if c.hasSecondaryAddr {
if !isSecondaryAddressValid(c.secondaryAddr) {
return nil, fmt.Errorf("invalid secondary address %d (must be 96-126)", c.secondaryAddr)
}
addrCmd = fmt.Sprintf("addr %d %d", c.primaryAddr, c.secondaryAddr)
}
eotCharCmd := fmt.Sprintf("eot_char %d", c.eotChar)
cmds := []string{}
if !c.ar488 {
cmds = append(cmds,
"verbose 0", // turn off verbosity if on
"savecfg 0", // Disable saving of configuration parameters in EPROM
)
}
cmds = append(cmds,
addrCmd, // Set the primary address.
"mode 1", // Switch to controller mode.
"auto 0", // Turn off read-after-write and address instrument to listen.
"eoi 1", // Enable EOI assertion with last character.
"eos 0", // Set GPIB termination.
"read_tmo_ms 500", // Set the read timeout to 500 ms.
eotCharCmd, // Set the EOT char
"eot_enable 1", // Append character when EOI detected?
)
if !c.ar488 {
cmds = append(cmds,
"savecfg 1", // Enable saving of configuration parameters in EPROM
)
}
if clear {
cmds = append(cmds, "clr")
}
for _, cmd := range cmds {
if err := c.CommandController(cmd); err != nil {
return nil, err
}
}
return &c, nil
}
// WithSecondaryAddress sets a secondary address, which must be in the range of
// 96 and 126, inclusive.
func WithSecondaryAddress(addr int) ControllerOption {
return func(c *Controller) {
c.hasSecondaryAddr = true
c.secondaryAddr = addr
}
}
// WithDebug causes commands and responses to be logged.
func WithDebug() ControllerOption { return func(c *Controller) { c.debug = true } }
// WithAR488 slightly alters the init commands, for compatibility with the
// Arduino-based AR488. Specifically, we do not emit 'verbose 0', nor do
// we toggle savecfg.
func WithAR488() ControllerOption { return func(c *Controller) { c.ar488 = true } }
// Write writes the given data to the instrument at the currently assigned GPIB
// address.
func (c *Controller) Write(p []byte) (n int, err error) {
return c.rw.Write(p)
}
// WriteBinary writes binary data to the instrument at the currently assigned
// GPIB address without adding a terminator. If the underlying writer implements
// ContextWriter, the call is delegated directly. Otherwise, the write is
// performed in a goroutine so the context cancellation is respected.
func (c *Controller) WriteBinary(ctx context.Context, p []byte) (n int, err error) {
if cw, ok := c.rw.(ContextWriter); ok {
return cw.WriteContext(ctx, p)
}
if err := ctx.Err(); err != nil {
return 0, err
}
type result struct {
n int
err error
}
ch := make(chan result, 1)
go func() {
n, err := c.rw.Write(p)
ch <- result{n, err}
}()
select {
case <-ctx.Done():
return 0, ctx.Err()
case r := <-ch:
return r.n, r.err
}
}
// Read reads from the instrument at the currently assigned GPIB address into
// the given byte slice.
func (c *Controller) Read(p []byte) (n int, err error) {
return c.rw.Read(p)
}
// ReadBinary reads binary data from the instrument at the currently assigned
// GPIB address into the given byte slice without terminator interpretation. If
// the underlying reader implements ContextReader, the call is delegated
// directly. Otherwise, the read is performed in a goroutine so the context
// cancellation is respected.
func (c *Controller) ReadBinary(ctx context.Context, p []byte) (n int, err error) {
if cr, ok := c.rw.(ContextReader); ok {
return cr.ReadContext(ctx, p)
}
if err := ctx.Err(); err != nil {
return 0, err
}
type result struct {
n int
err error
}
ch := make(chan result, 1)
go func() {
n, err := c.rw.Read(p)
ch <- result{n, err}
}()
select {
case <-ctx.Done():
return 0, ctx.Err()
case r := <-ch:
return r.n, r.err
}
}
// WriteString writes a string to the instrument at the currently assigned GPIB
// address.
func (c *Controller) WriteString(s string) (n int, err error) {
cmd := fmt.Sprintf("%s%c", strings.TrimSpace(s), c.usbTerm)
log.Printf("prologix driver writing string: %s", cmd)
return c.rw.Write([]byte(cmd))
}
// Command formats according to a format specifier if provided and sends a
// SCPI/ASCII command to the instrument at the currently assigned GPIB address.
// All leading and trailing whitespace is removed before appending the USB
// terminator to the command sent to the Prologix.
func (c *Controller) Command(ctx context.Context, cmd string, a ...any) error {
if a != nil {
cmd = fmt.Sprintf(cmd, a...)
}
if err := ctx.Err(); err != nil {
return err
}
cmd = fmt.Sprintf("%s%c", strings.TrimSpace(cmd), c.usbTerm)
if c.debug {
log.Printf("cmd %q (%x)", cmd, cmd)
}
_, err := fmt.Fprint(c.rw, cmd)
return err
}
// Query queries the instrument at the currently assigned GPIB using the given
// SCPI/ASCII command. The cmd string does not need to include a new line
// character, since all leading and trailing whitespace is removed before
// appending the USB terminator to the command sent to the Prologix. When data
// from host is received over USB, the Prologix controller removes all
// non-escaped LF, CR and ESC characters and appends the GPIB terminator, as
// specified by the `eos` command, before sending the data to instruments. To
// change the GPIB terminator use the SetGPIBTermination method.
func (c *Controller) Query(ctx context.Context, cmd string) (string, error) {
if err := ctx.Err(); err != nil {
return "", err
}
cmd = fmt.Sprintf("%s%c", strings.TrimSpace(cmd), c.usbTerm)
if c.debug {
log.Printf("query: %q", cmd)
}
_, err := fmt.Fprint(c.rw, cmd)
if err != nil {
return "", fmt.Errorf("error writing command: %w", err)
}
// If read-after-write is disabled, need to tell the Prologix controller to
// read.
if !c.auto {
readCmd := "++read eoi"
_, err = fmt.Fprintf(c.rw, "%s%c", readCmd, c.usbTerm)
if err != nil {
return "", fmt.Errorf("error sending %q command: %w", readCmd, err)
}
}
s, err := c.reader.ReadString(c.eotChar)
if errors.Is(err, io.EOF) {
log.Printf("found EOF")
return s, nil
}
return s, err
}
// Close closes the underlying transport if it implements io.Closer.
func (c *Controller) Close() error {
if closer, ok := c.rw.(io.Closer); ok {
return closer.Close()
}
return nil
}
// QueryController sends the given command to the Prologix controller and
// returns its response as a string. To indicate this is a command for the
// Prologix controller, thereby not transmitting over GPIB, two plus signs `++`
// are prepended. Addtionally, a new line is appended to act as the USB
// termination character.
func (c *Controller) QueryController(cmd string) (string, error) {
err := c.CommandController(cmd)
if err != nil {
return "", err
}
s, err := c.reader.ReadString(c.eotChar)
if c.debug {
log.Printf("read data: %q", s)
}
return s, err
}
// CommandController sends the given command to the Prologix controller. To
// indicate this is a command for the Prologix controller, thereby not
// transmitting to the instrument over GPIB, two plus signs `++` are prepended.
// Addtionally, a new line is appended to act as the USB termination character.
func (c *Controller) CommandController(cmd string) error {
cmd = fmt.Sprintf("++%s%c", strings.ToLower(strings.TrimSpace(cmd)), c.usbTerm)
if c.debug {
log.Printf("cmd %q (%2x)", cmd, cmd)
}
_, err := c.rw.Write([]byte(cmd))
return err
}
// GpibTerm provides the type for the available GPIB terminators.
type GpibTerm int
// Available GPIB terminators for the Prologix Controller.
const (
AppendCRLF GpibTerm = iota
AppendCR
AppendLF
AppendNothing
)
var gpibTermDesc = map[GpibTerm]string{
AppendCRLF: `Append CR+LF (\r\n) to instrument commands`,
AppendCR: `Append CR (\r) to instrument commands`,
AppendLF: `Append LF (\n) to instrument commands`,
AppendNothing: `Do not append anything to instrument commands`,
}
func (term GpibTerm) String() string {
return gpibTermDesc[term]
}
// isPrimaryAddressValid checks that the primary GPIB address is between 0 and
// 30, inclusive.
func isPrimaryAddressValid(addr int) bool {
if addr < 0 || addr > 30 {
return false
}
return true
}
// isSecondaryAddressValid checks that the secondary GPIB address is between 96
// and 126, inclusive.
func isSecondaryAddressValid(addr int) bool {
if addr < 96 || addr > 126 {
return false
}
return true
}