-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasrl.go
More file actions
282 lines (250 loc) · 7.54 KB
/
asrl.go
File metadata and controls
282 lines (250 loc) · 7.54 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
// Copyright (c) 2017-2026 The asrl developers. All rights reserved.
// Project site: https://github.com/gotmc/asrl
// 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 asrl
import (
"bufio"
"context"
"errors"
"fmt"
"strings"
"time"
"go.bug.st/serial"
)
// ErrDSRNotReady is returned when the Data Set Ready signal is not asserted
// within the ReadTimeout period.
var ErrDSRNotReady = errors.New("asrl: DSR not ready")
// Device models a serial device and implements the ivi.Transport interface.
type Device struct {
EndMark byte
HWHandshaking bool
DelayTime time.Duration
ReadTimeout time.Duration
port serial.Port
reader *bufio.Reader
}
// DeviceOption is a functional option for configuring a Device.
type DeviceOption func(*Device)
// WithEndMark sets the end-of-message byte used by Command and Query.
func WithEndMark(b byte) DeviceOption {
return func(d *Device) {
d.EndMark = b
}
}
// WithHWHandshaking enables or disables hardware handshaking (DSR polling).
func WithHWHandshaking(enabled bool) DeviceOption {
return func(d *Device) {
d.HWHandshaking = enabled
}
}
// WithDelayTime sets the delay between serial operations.
func WithDelayTime(t time.Duration) DeviceOption {
return func(d *Device) {
d.DelayTime = t
}
}
// WithReadTimeout sets the read timeout on the serial port.
func WithReadTimeout(t time.Duration) DeviceOption {
return func(d *Device) {
d.ReadTimeout = t
}
}
// NewDevice opens a serial Device using the given VISA address resource string.
// The context is checked before opening the serial port. Optional DeviceOption
// values can be provided to override the default settings for EndMark,
// HWHandshaking, DelayTime, and ReadTimeout.
func NewDevice(ctx context.Context, address string, opts ...DeviceOption) (*Device, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
v, err := NewVisaResource(address)
if err != nil {
return nil, err
}
mode := &serial.Mode{
BaudRate: v.baud,
Parity: v.parity,
DataBits: v.dataBits,
StopBits: v.stopBits,
}
port, err := serial.Open(v.address, mode)
if err != nil {
return nil, err
}
d := &Device{
port: port,
reader: bufio.NewReader(port),
HWHandshaking: false,
EndMark: '\n',
DelayTime: 70 * time.Millisecond,
ReadTimeout: 5 * time.Second,
}
for _, opt := range opts {
opt(d)
}
if err := port.SetReadTimeout(d.ReadTimeout); err != nil {
_ = port.Close()
return nil, fmt.Errorf("setting read timeout: %w", err)
}
return d, nil
}
// Close closes the underlying serial port.
func (d *Device) Close() error {
time.Sleep(d.DelayTime)
return d.port.Close()
}
// Read reads from the serial port into the given byte slice.
func (d *Device) Read(p []byte) (n int, err error) {
return d.port.Read(p)
}
// Write writes the given data to the serial port.
func (d *Device) Write(p []byte) (n int, err error) {
return d.port.Write(p)
}
// WriteString writes a string to the serial port. An endmark character, such
// as a newline, is not automatically added to the end of the string.
func (d *Device) WriteString(s string) (n int, err error) {
return d.Write([]byte(s))
}
// ReadBinary reads binary data from the serial port without terminator
// interpretation. If the context is canceled before the read completes,
// ReadBinary sets a short timeout to unblock the read, waits for the goroutine
// to finish, and returns the context error.
func (d *Device) ReadBinary(ctx context.Context, p []byte) (int, error) {
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 := d.port.Read(p)
ch <- result{n, err}
}()
select {
case <-ctx.Done():
// Set a short read timeout to unblock the goroutine stuck on Read,
// then wait for it to finish so we don't leak it.
_ = d.port.SetReadTimeout(1 * time.Millisecond)
<-ch
_ = d.port.SetReadTimeout(d.ReadTimeout)
return 0, ctx.Err()
case r := <-ch:
return r.n, r.err
}
}
// WriteBinary writes binary data to the serial port without adding a
// terminator. If the context is already canceled before the write begins,
// WriteBinary returns the context error. Serial writes are typically
// non-blocking, so no goroutine-based cancellation is needed.
func (d *Device) WriteBinary(ctx context.Context, p []byte) (int, error) {
if err := ctx.Err(); err != nil {
return 0, err
}
return d.port.Write(p)
}
// Command sends a SCPI/ASCII command to the serial port. The command can be
// optionally formatted according to a format specifier. An endmark character,
// such as newline, is automatically added to the end of the string.
func (d *Device) Command(ctx context.Context, cmd string, a ...any) error {
if err := ctx.Err(); err != nil {
return err
}
if d.HWHandshaking {
if err := d.napIfDataSetNotReady(ctx); err != nil {
return err
}
}
if len(a) > 0 {
cmd = fmt.Sprintf(cmd, a...)
}
cmd = strings.TrimSpace(cmd) + string(d.EndMark)
if _, err := d.WriteBinary(ctx, []byte(cmd)); err != nil {
return err
}
return sleepContext(ctx, d.DelayTime)
}
// Query writes the given SCPI/ASCII command to the serial port and returns the
// response string. The device's endmark character (newline by default) is
// automatically added to the query command. The string returned is not
// stripped of any whitespace. The context is used for cancellation; if the
// context is canceled while waiting for a response, Query returns the context
// error.
func (d *Device) Query(ctx context.Context, cmd string) (string, error) {
if err := d.Command(ctx, "%s", cmd); err != nil {
return "", err
}
type result struct {
s string
err error
}
ch := make(chan result, 1)
go func() {
s, err := d.reader.ReadString(d.EndMark)
ch <- result{s, err}
}()
select {
case <-ctx.Done():
// Set a short read timeout to unblock the goroutine stuck on
// ReadString, then wait for it to finish so we don't leak it or
// race on the bufio.Reader.
_ = d.port.SetReadTimeout(1 * time.Millisecond)
<-ch
_ = d.port.SetReadTimeout(d.ReadTimeout)
d.reader.Reset(d.port)
return "", ctx.Err()
case r := <-ch:
return r.s, r.err
}
}
func isDSR(port serial.Port) (bool, error) {
msb, err := port.GetModemStatusBits()
if err != nil {
return false, fmt.Errorf("getting modem status bits: %w", err)
}
return msb.DSR, nil
}
func (d *Device) napIfDataSetNotReady(ctx context.Context) error {
// If I use 40 ms instead of 50 ms for the delay time, the Keysight E3631A DC
// power supply will hang when sending commands/queries. Using 50 ms causes
// the power supply to hang sometimes. I'm currently using 70 ms to be safe.
timeout := time.NewTimer(d.ReadTimeout)
defer timeout.Stop()
ticker := time.NewTicker(d.DelayTime)
defer ticker.Stop()
for {
ready, err := isDSR(d.port)
if err != nil {
return err
}
if ready {
break
}
select {
case <-ctx.Done():
return ctx.Err()
case <-timeout.C:
return fmt.Errorf("%w after %s", ErrDSRNotReady, d.ReadTimeout)
case <-ticker.C:
}
}
// Sleep a bit longer once the Data Set Ready is true. Without this, the
// Keysight E3631A DC power supply will sometimes hang when sending
// commands/queries.
return sleepContext(ctx, d.DelayTime)
}
// sleepContext pauses for the given duration but returns early with the context
// error if the context is canceled.
func sleepContext(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}