feat(psu): switch a Modbus RTU bench supply from OpsLog

The manufacturer's document arrived, so this is no longer guesswork: 9600 8N1,
function codes 03 and 06 only, and a register map with the output on/off at
0x0001, the measurements at 0x0010…0x0013 and the set points at 0x0030/0x0031.

ONE REGISTER IS WRITTEN — 0x0001, the output. The map also exposes the voltage
and current set points and the three protection trip levels as writable, and
none of them belong to a logbook: a wrong value there is 30 V where a radio
expected 13.8, or a trip level lifted on a supply feeding an amplifier. They are
read and displayed instead, next to the measured values, which is also how an
operator sees at a glance that the supply is on and the radio is drawing nothing.

The wire layer is tested where it can be. CRC-16/MODBUS is pinned against its
published check value — the CRC of "123456789" is 0x4B37 — which fixes the
polynomial, the initial value, the reflection and the absence of a final xor all
at once; the rest of the protocol is checked frame by frame against the manual,
including the byte order of the CRC, an exception reply told apart from a broken
line, and a reply from another slave on the bus refused. The write echo must
match the value sent: it is the only confirmation the output really switched,
and accepting the frame without it is how a radio ends up dark behind a green
light.

Framing follows the manual's own rules: 3.5 character times of silence between
frames (4 ms at 9600), and a frame is over when the line falls quiet — Modbus
RTU has no terminator, and a serial read that times out returns (0, nil) here,
so the reader is built on a deadline and a quiet-time rather than on an error
that never comes.

Untested against hardware — nobody here has the supply.
This commit is contained in:
2026-08-16 13:15:55 +02:00
parent 9f8e3c73d9
commit 8683a450a7
12 changed files with 1038 additions and 4 deletions
+239
View File
@@ -0,0 +1,239 @@
// Package psu drives a bench power supply over Modbus RTU — the BSIDE / Wanptek
// family of programmable supplies that sit in a shack feeding the radios.
//
// The register map and the wire settings come from the manufacturer's own
// document ("This machine only support function code 03,06", version 20180611):
//
// 9600 baud, 8 data bits, no parity, 1 stop bit
// function 03 read holding registers
// function 06 write single register
// slave address 1…15, address 0 broadcast
//
// NOTHING ELSE IS WRITTEN. The map also carries the output voltage and current
// SET points, and the over-voltage, over-current and over-power trip levels, all
// read/write. This driver reads them and writes exactly one register: 0x0001,
// the output on/off. A wrong value in any of the others is not a wrong reading —
// it is 30 V where a radio expected 13.8, or a protection trip lifted on a
// supply feeding an amplifier. There is no reason for a logbook to set them, so
// it cannot.
package psu
import (
"encoding/binary"
"fmt"
"io"
"time"
)
// Registers, from the manufacturer's table. Addresses are as printed there.
const (
regOnOff = 0x0001 // output on/off — 1 or 0. The ONLY register written.
regProtect = 0x0002 // protection status word
regModel = 0x0003 // specification model
regDecimals = 0x0005 // "V_A_W number of digits" — see readDecimals
regVolts = 0x0010 // measured output voltage, 2 decimals
regAmps = 0x0011 // measured output current, 3 decimals
regWatts = 0x0012 // measured output power, 32-bit across 0x0012/0x0013, 3 decimals
regSetVolts = 0x0030 // voltage set point, 2 decimals
regSetAmps = 0x0031 // current set point, 3 decimals
)
const (
fnRead = 0x03
fnWrite = 0x06
)
// Fixed scaling from the manufacturer's "Decimal place" column. The supply also
// reports its own digit counts in 0x0005, but the document's "Note 2" that
// explains how to decode that word is not in the manual we have — so the
// documented per-register values are used, and the raw word is logged once at
// connect. If an operator ever reports readings out by a factor of ten, that
// line is what says how to decode it properly.
const (
voltScale = 100.0 // 2 decimals
ampScale = 1000.0 // 3 decimals
wattScale = 1000.0 // 3 decimals
)
// crc16 is the Modbus RTU frame check: CRC-16/MODBUS — reflected, polynomial
// 0xA001, initial value 0xFFFF, no final xor. Transmitted low byte first.
func crc16(b []byte) uint16 {
crc := uint16(0xFFFF)
for _, c := range b {
crc ^= uint16(c)
for i := 0; i < 8; i++ {
if crc&1 != 0 {
crc = (crc >> 1) ^ 0xA001
} else {
crc >>= 1
}
}
}
return crc
}
// appendCRC closes a frame: low byte first, as the manual states.
func appendCRC(f []byte) []byte {
c := crc16(f)
return append(f, byte(c&0xFF), byte(c>>8))
}
// buildRead frames a function 03 "read holding registers".
func buildRead(addr byte, reg uint16, count uint16) []byte {
f := []byte{addr, fnRead, byte(reg >> 8), byte(reg), byte(count >> 8), byte(count)}
return appendCRC(f)
}
// buildWrite frames a function 06 "write single register".
func buildWrite(addr byte, reg, val uint16) []byte {
f := []byte{addr, fnWrite, byte(reg >> 8), byte(reg), byte(val >> 8), byte(val)}
return appendCRC(f)
}
// modbusError is an exception response — the supply understood the frame and
// refused it. Kept distinct from a transport failure: one means "ask
// differently", the other means "the cable".
type modbusError struct {
fn byte
code byte
}
func (e modbusError) Error() string {
what := map[byte]string{
1: "illegal function",
2: "illegal data address",
3: "illegal data value",
4: "slave device failure",
6: "device busy",
}[e.code]
if what == "" {
what = fmt.Sprintf("exception %d", e.code)
}
return fmt.Sprintf("supply refused function 0x%02X: %s", e.fn, what)
}
// parseRead validates a function 03 reply and returns the register values.
func parseRead(addr byte, want uint16, frame []byte) ([]uint16, error) {
if err := checkFrame(addr, fnRead, frame, 5); err != nil {
return nil, err
}
n := int(frame[2])
if n != int(want)*2 {
return nil, fmt.Errorf("reply carries %d data byte(s), expected %d", n, want*2)
}
if len(frame) != 3+n+2 {
return nil, fmt.Errorf("reply is %d bytes, expected %d", len(frame), 3+n+2)
}
out := make([]uint16, want)
for i := range out {
out[i] = binary.BigEndian.Uint16(frame[3+i*2:])
}
return out, nil
}
// parseWriteEcho validates a function 06 reply, which echoes the request.
func parseWriteEcho(addr byte, reg, val uint16, frame []byte) error {
if err := checkFrame(addr, fnWrite, frame, 8); err != nil {
return err
}
if len(frame) != 8 {
return fmt.Errorf("write reply is %d bytes, expected 8", len(frame))
}
if got := binary.BigEndian.Uint16(frame[2:]); got != reg {
return fmt.Errorf("write reply is for register 0x%04X, not 0x%04X", got, reg)
}
// The echoed VALUE is the confirmation that the output actually changed.
// Accepting the frame without checking it would report an on/off that the
// supply never made.
if got := binary.BigEndian.Uint16(frame[4:]); got != val {
return fmt.Errorf("supply echoed value %d, not the %d it was sent", got, val)
}
return nil
}
// checkFrame covers what every reply must satisfy: our address, our function
// (or its exception), and a good CRC.
func checkFrame(addr, fn byte, frame []byte, min int) error {
if len(frame) < 4 {
return fmt.Errorf("short reply (%d bytes)", len(frame))
}
if frame[0] != addr {
return fmt.Errorf("reply from address %d, expected %d", frame[0], addr)
}
if frame[1] == fn|0x80 {
if len(frame) < 5 {
return fmt.Errorf("short exception reply (%d bytes)", len(frame))
}
if !crcOK(frame[:5]) {
return fmt.Errorf("exception reply failed its CRC")
}
return modbusError{fn: fn, code: frame[2]}
}
if frame[1] != fn {
return fmt.Errorf("reply to function 0x%02X, expected 0x%02X", frame[1], fn)
}
if len(frame) < min {
return fmt.Errorf("short reply (%d bytes, expected at least %d)", len(frame), min)
}
if !crcOK(frame) {
return fmt.Errorf("reply failed its CRC")
}
return nil
}
// crcOK checks a whole frame, trailing CRC included: the CRC of the entire
// frame is zero when it is intact.
func crcOK(frame []byte) bool {
if len(frame) < 3 {
return false
}
body := frame[:len(frame)-2]
want := uint16(frame[len(frame)-2]) | uint16(frame[len(frame)-1])<<8
return crc16(body) == want
}
// frameGap is the silence that separates two Modbus RTU frames: 3.5 character
// times, which at 9600 baud 8N1 (10 bits per character) is 3.65 ms. Rounded up,
// because the cost of waiting is nothing and the cost of being early is a
// supply that treats our request as the tail of the previous one.
const frameGap = 4 * time.Millisecond
// replyWait is how long a reply may take. The manual promises under 5 ms at
// 9600 baud or better; this is generous by two orders of magnitude so a USB
// serial bridge that buffers cannot be mistaken for a supply that is not there.
const replyWait = 500 * time.Millisecond
// readFrame collects a reply until it stops arriving.
//
// A serial read that times out returns (0, nil) on Windows — a timeout is not
// an error on this transport — so a loop that trusts an error to end it never
// ends. Modbus RTU has no terminator either: a frame is over when the line has
// been quiet for 3.5 character times. Both facts point at the same shape, a
// deadline and a quiet-time.
func readFrame(conn io.Reader, d time.Duration) ([]byte, error) {
deadline := time.Now().Add(d)
buf := make([]byte, 0, 64)
tmp := make([]byte, 64)
lastByte := time.Time{}
for {
n, err := conn.Read(tmp)
if err != nil {
return buf, err
}
if n > 0 {
buf = append(buf, tmp[:n]...)
lastByte = time.Now()
continue
}
// Nothing this time: either the frame has ended, or it never started.
if len(buf) > 0 && time.Since(lastByte) >= frameGap {
return buf, nil
}
if time.Now().After(deadline) {
if len(buf) > 0 {
return buf, nil // partial — let the parser say what is wrong with it
}
return nil, fmt.Errorf("no reply after %s", d)
}
}
}
+180
View File
@@ -0,0 +1,180 @@
package psu
import (
"errors"
"strings"
"testing"
"time"
)
// The CRC is the one thing here that cannot be checked by inspection, and every
// frame depends on it. CRC-16/MODBUS has a published check value: the CRC of
// the ASCII digits "123456789" is 0x4B37. If this passes, the polynomial, the
// initial value, the reflection and the absence of a final xor are all right.
func TestCRCMatchesTheStandardCheckValue(t *testing.T) {
if got := crc16([]byte("123456789")); got != 0x4B37 {
t.Fatalf("crc16(\"123456789\") = 0x%04X, want 0x4B37 — this is not CRC-16/MODBUS", got)
}
}
// A frame including its own CRC checks to zero. That property is what crcOK
// relies on, so it is worth pinning separately from the check value.
func TestAFrameVerifiesItself(t *testing.T) {
for _, f := range [][]byte{
buildRead(1, regVolts, 2),
buildWrite(1, regOnOff, 1),
buildWrite(15, regOnOff, 0),
} {
if !crcOK(f) {
t.Errorf("% X does not verify against its own CRC", f)
}
// And a single flipped bit must be caught.
bad := append([]byte(nil), f...)
bad[2] ^= 0x01
if crcOK(bad) {
t.Errorf("% X passed the CRC with a corrupted byte", bad)
}
}
}
// The frame layout, byte for byte against the manual: address, function,
// register high/low, count or value high/low, then CRC low byte first.
func TestFrameLayout(t *testing.T) {
r := buildRead(1, 0x0010, 2)
if len(r) != 8 {
t.Fatalf("read frame is %d bytes, want 8", len(r))
}
want := []byte{0x01, 0x03, 0x00, 0x10, 0x00, 0x02}
for i := range want {
if r[i] != want[i] {
t.Fatalf("read frame % X, want % X…", r, want)
}
}
w := buildWrite(1, regOnOff, 1)
want = []byte{0x01, 0x06, 0x00, 0x01, 0x00, 0x01}
for i := range want {
if w[i] != want[i] {
t.Fatalf("write frame % X, want % X…", w, want)
}
}
// The CRC goes out low byte first — the manual is explicit, and getting it
// backwards makes every frame be ignored in silence.
c := crc16(w[:6])
if w[6] != byte(c&0xFF) || w[7] != byte(c>>8) {
t.Errorf("CRC bytes % X, want %02X %02X (low first)", w[6:], byte(c&0xFF), byte(c>>8))
}
}
func TestParseRead(t *testing.T) {
// Two registers: 13.80 V (1380 at 2 decimals) and 2.500 A (2500 at 3).
frame := appendCRC([]byte{0x01, 0x03, 0x04, 0x05, 0x64, 0x09, 0xC4})
got, err := parseRead(1, 2, frame)
if err != nil {
t.Fatalf("parseRead: %v", err)
}
if len(got) != 2 || got[0] != 1380 || got[1] != 2500 {
t.Fatalf("got %v, want [1380 2500]", got)
}
if v := float64(got[0]) / voltScale; v != 13.80 {
t.Errorf("voltage scaled to %v, want 13.8", v)
}
}
// A reply from another slave on the same bus must not be read as ours.
func TestParseRejectsAnotherSlave(t *testing.T) {
frame := appendCRC([]byte{0x02, 0x03, 0x02, 0x05, 0x64})
if _, err := parseRead(1, 1, frame); err == nil {
t.Error("a reply from address 2 was accepted as address 1")
}
}
func TestParseRejectsABadCRC(t *testing.T) {
frame := appendCRC([]byte{0x01, 0x03, 0x02, 0x05, 0x64})
frame[3] ^= 0xFF
if _, err := parseRead(1, 1, frame); err == nil || !strings.Contains(err.Error(), "CRC") {
t.Errorf("err = %v, want a CRC complaint", err)
}
}
// An exception reply is the supply refusing, not the line failing, and the two
// need different answers from the operator.
func TestParseReportsAnException(t *testing.T) {
frame := appendCRC([]byte{0x01, 0x83, 0x02})
_, err := parseRead(1, 1, frame)
var me modbusError
if !errors.As(err, &me) {
t.Fatalf("err = %v, want a modbusError", err)
}
if me.code != 2 || !strings.Contains(err.Error(), "illegal data address") {
t.Errorf("exception decoded as %v", err)
}
}
// The echo is the ONLY confirmation that the output actually switched. A reply
// echoing a different value means the supply did something else, and reporting
// that as success is how a radio ends up with no power and a green light.
func TestWriteEchoMustMatch(t *testing.T) {
ok := appendCRC([]byte{0x01, 0x06, 0x00, 0x01, 0x00, 0x01})
if err := parseWriteEcho(1, regOnOff, 1, ok); err != nil {
t.Fatalf("a correct echo was rejected: %v", err)
}
wrongVal := appendCRC([]byte{0x01, 0x06, 0x00, 0x01, 0x00, 0x00})
if err := parseWriteEcho(1, regOnOff, 1, wrongVal); err == nil {
t.Error("an echo of 0 was accepted for a command of 1 — the output never switched")
}
wrongReg := appendCRC([]byte{0x01, 0x06, 0x00, 0x30, 0x00, 0x01})
if err := parseWriteEcho(1, regOnOff, 1, wrongReg); err == nil {
t.Error("an echo for register 0x0030 was accepted for a write to 0x0001")
}
}
// quietPort delivers a frame in pieces, then goes quiet — a serial port that
// reports a timeout as (0, nil), which is what Windows does.
type quietPort struct {
chunks [][]byte
i int
}
func (p *quietPort) Read(b []byte) (int, error) {
if p.i >= len(p.chunks) {
time.Sleep(2 * time.Millisecond)
return 0, nil // timeout, not an error
}
n := copy(b, p.chunks[p.i])
p.i++
return n, nil
}
// A Modbus RTU frame has no terminator: it ends when the line falls quiet. The
// reader must assemble a dribbled frame and then stop on its own.
func TestReadFrameAssemblesUntilQuiet(t *testing.T) {
want := appendCRC([]byte{0x01, 0x03, 0x04, 0x05, 0x64, 0x09, 0xC4})
p := &quietPort{chunks: [][]byte{want[:2], want[2:5], want[5:]}}
got, err := readFrame(p, time.Second)
if err != nil {
t.Fatalf("readFrame: %v", err)
}
if len(got) != len(want) {
t.Fatalf("read % X, want % X", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("read % X, want % X", got, want)
}
}
}
// A supply that is switched off, or not on this port, must produce an error
// rather than a wait that never ends.
func TestReadFrameGivesUpOnSilence(t *testing.T) {
done := make(chan error, 1)
go func() { _, err := readFrame(&quietPort{}, 80*time.Millisecond); done <- err }()
select {
case err := <-done:
if err == nil {
t.Error("silence was reported as a frame")
}
case <-time.After(3 * time.Second):
t.Fatal("readFrame never returned")
}
}
+262
View File
@@ -0,0 +1,262 @@
package psu
import (
"fmt"
"log"
"strings"
"sync"
"time"
"go.bug.st/serial"
)
// Config is one supply's serial link.
type Config struct {
ComPort string
Baud int // 9600 unless the supply has been reconfigured
Address byte // Modbus slave address, 1…15 on this family
}
// Status is what the UI shows. Everything here is READ from the supply — the
// set points included, which the operator sets on the front panel and OpsLog
// only reports.
type Status struct {
Connected bool `json:"connected"`
On bool `json:"on"` // output enabled
Volts float64 `json:"volts"` // measured output
Amps float64 `json:"amps"` // measured output
Watts float64 `json:"watts"` // measured output
SetVolts float64 `json:"set_volts"` // the voltage the supply is set to
SetAmps float64 `json:"set_amps"` // the current limit it is set to
Protected uint16 `json:"protected"` // protection status word, non-zero = tripped
Error string `json:"error,omitempty"`
}
const pollEvery = 1500 * time.Millisecond
// Client owns the serial link to one supply.
type Client struct {
cfg Config
connMu sync.Mutex
conn serial.Port
ioMu sync.Mutex // serialises a request/reply exchange on the shared port
statusMu sync.Mutex
last Status
stopChan chan struct{}
stopOnce sync.Once
lastErr string
}
// New builds a client. Nothing is opened until Start.
func New(cfg Config) *Client {
if cfg.Baud <= 0 {
cfg.Baud = 9600
}
if cfg.Address == 0 {
cfg.Address = 1
}
return &Client{cfg: cfg, stopChan: make(chan struct{})}
}
// Start begins the poll loop. It returns immediately: the supply may be off, and
// a shack comes up in whatever order it comes up in.
func (c *Client) Start() error {
go c.loop()
return nil
}
// Stop closes the link.
func (c *Client) Stop() {
c.stopOnce.Do(func() { close(c.stopChan) })
c.closeConn()
}
// GetStatus returns the last poll's answer.
func (c *Client) GetStatus() Status {
c.statusMu.Lock()
defer c.statusMu.Unlock()
return c.last
}
// SetOutput switches the supply's output on or off — the one thing this driver
// writes. The supply's echo is checked, so a false return of "done" is not
// possible: either it confirmed the value or this is an error.
func (c *Client) SetOutput(on bool) error {
val := uint16(0)
if on {
val = 1
}
if err := c.writeRegister(regOnOff, val); err != nil {
return err
}
// Report it at once rather than waiting for the next poll: the operator
// pressed a button and is looking at it.
c.statusMu.Lock()
c.last.On = on
c.statusMu.Unlock()
log.Printf("psu: output %s", map[bool]string{true: "ON", false: "OFF"}[on])
return nil
}
func (c *Client) loop() {
t := time.NewTicker(pollEvery)
defer t.Stop()
for {
select {
case <-c.stopChan:
return
case <-t.C:
if err := c.poll(); err != nil {
c.noteFailure(err)
continue
}
}
}
}
// poll reads everything the UI shows, in as few exchanges as the register map
// allows: the measurements are contiguous (0x0010…0x0013), the set points are
// contiguous (0x0030, 0x0031), and the on/off and protection words sit together
// at 0x0001/0x0002.
func (c *Client) poll() error {
if err := c.ensureConn(); err != nil {
return err
}
st := Status{Connected: true}
state, err := c.readRegisters(regOnOff, 2)
if err != nil {
return err
}
st.On = state[0] != 0
st.Protected = state[1]
meas, err := c.readRegisters(regVolts, 4) // U, I, P high, P low
if err != nil {
return err
}
st.Volts = float64(meas[0]) / voltScale
st.Amps = float64(meas[1]) / ampScale
st.Watts = float64(uint32(meas[2])<<16|uint32(meas[3])) / wattScale
set, err := c.readRegisters(regSetVolts, 2)
if err != nil {
return err
}
st.SetVolts = float64(set[0]) / voltScale
st.SetAmps = float64(set[1]) / ampScale
c.statusMu.Lock()
c.last = st
c.statusMu.Unlock()
if c.lastErr != "" {
log.Printf("psu: %s answering again", c.cfg.ComPort)
c.lastErr = ""
}
return nil
}
func (c *Client) readRegisters(reg, count uint16) ([]uint16, error) {
frame, err := c.exchange(buildRead(c.cfg.Address, reg, count))
if err != nil {
return nil, err
}
return parseRead(c.cfg.Address, count, frame)
}
func (c *Client) writeRegister(reg, val uint16) error {
if err := c.ensureConn(); err != nil {
return err
}
frame, err := c.exchange(buildWrite(c.cfg.Address, reg, val))
if err != nil {
return err
}
return parseWriteEcho(c.cfg.Address, reg, val, frame)
}
// exchange sends one frame and reads one reply, holding the port for the whole
// round trip. Modbus RTU has no way to match a reply to a request, so two
// exchanges in flight at once would read each other's answers.
func (c *Client) exchange(req []byte) ([]byte, error) {
c.connMu.Lock()
conn := c.conn
c.connMu.Unlock()
if conn == nil {
return nil, fmt.Errorf("psu: not connected")
}
c.ioMu.Lock()
defer c.ioMu.Unlock()
// The silence before a frame is part of the protocol, not politeness: it is
// how the supply knows this is a new message and not the tail of the last.
time.Sleep(frameGap)
if _, err := conn.Write(req); err != nil {
c.closeConn()
return nil, err
}
frame, err := readFrame(conn, replyWait)
if err != nil {
c.closeConn()
return nil, err
}
return frame, nil
}
func (c *Client) ensureConn() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn != nil {
return nil
}
port := strings.TrimSpace(c.cfg.ComPort)
if port == "" {
return fmt.Errorf("psu: no serial port configured")
}
p, err := serial.Open(port, &serial.Mode{
BaudRate: c.cfg.Baud,
DataBits: 8,
Parity: serial.NoParity,
StopBits: serial.OneStopBit,
})
if err != nil {
return fmt.Errorf("psu: cannot open %s: %w", port, err)
}
// Short per-read timeout: readFrame decides when a frame has ended by the
// quiet between bytes, so each Read must come back promptly with whatever
// has arrived.
_ = p.SetReadTimeout(2 * time.Millisecond)
c.conn = p
log.Printf("psu: %s open at %d baud, Modbus address %d", port, c.cfg.Baud, c.cfg.Address)
return nil
}
func (c *Client) closeConn() {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn != nil {
_ = c.conn.Close()
c.conn = nil
}
}
// noteFailure records a poll failure and says so ONCE per distinct message.
//
// A supply that is switched off at the mains fails every poll, and a line per
// second and a half would be the whole log file — but saying nothing at all is
// how "it stopped working" arrives with no evidence.
func (c *Client) noteFailure(err error) {
msg := err.Error()
c.statusMu.Lock()
c.last = Status{Connected: false, Error: msg}
c.statusMu.Unlock()
if msg != c.lastErr {
c.lastErr = msg
log.Printf("psu: %v — retrying every %s, and this will not be logged again until it changes", err, pollEvery)
}
}