modbus

package module
v0.0.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 7 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

sup-modbus

Go Reference Test License

sup-modbus provides supervised, serialized access to Modbus TCP, RTU, and ASCII devices. It is built on the sup resource primitive.

Modbus connections are stateful and must not be used concurrently. An Actor owns one connection per supervised execution and runs calls one at a time. When a transport operation fails, the actor releases the connection and returns the error so its supervisor can reconnect it. Modbus protocol exceptions are returned to the caller without discarding a healthy connection.

Installation

go get github.com/webermarci/sup-modbus

Quick start

package main

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/webermarci/sup"
	"github.com/webermarci/sup-modbus"
)

func main() {
	ctx, cancel := signal.NotifyContext(
		context.Background(),
		os.Interrupt,
		syscall.SIGTERM,
	)
	defer cancel()

	device := modbus.NewActor(
		"plc",
		modbus.TCP,
		"192.168.1.50:502",
		1,
		modbus.WithTimeout(2*time.Second),
	)

	supervisor := sup.NewSupervisor("root", sup.Transient).
		AddActors(device).
		SetRestartDelay(time.Second).
		SetRestartLimit(5, 10*time.Second)

	done := make(chan error, 1)
	go func() {
		done <- supervisor.Run(ctx)
	}()

	requestCtx, cancelRequest := context.WithTimeout(ctx, 3*time.Second)
	data, err := device.ReadHoldingRegisters(requestCtx, 100, 2)
	cancelRequest()
	if err != nil {
		panic(err)
	}
	fmt.Printf("Register data: %X\n", data)

	cancel()
	if err := <-done; err != nil {
		panic(err)
	}
}

Calls wait while the actor is acquiring or reacquiring its connection. Always give each call a context with an appropriate deadline. A canceled context also stops a call that is waiting behind another operation. The underlying goburrow/modbus I/O is bounded by WithTimeout once it has started.

Concurrent callers

All methods are safe to call concurrently. The actor serializes them against the same connection:

coils, err := device.ReadCoils(ctx, 0, 16)
registers, err := device.ReadHoldingRegisters(ctx, 100, 4)
_, err = device.WriteSingleCoil(ctx, 5, 0xFF00)

An accepted operation is never replayed after reconnection, which prevents a write from being applied twice when its outcome is uncertain.

Invalid quantities, coil values, and write payload sizes are rejected before the request reaches the connection. Use errors.Is(err, modbus.ErrInvalidArgument) to identify these caller errors.

Serial configuration

RTU and ASCII actors accept serial settings. RTU can additionally configure RS485 RTS timing and a quiet period between serialized requests:

device := modbus.NewActor(
	"meter",
	modbus.RTU,
	"/dev/ttyUSB0",
	1,
	modbus.WithSerialConfig(19200, 8, 1, "E"),
	modbus.WithRS485(2*time.Millisecond, 2*time.Millisecond),
	modbus.WithQuietTime(5*time.Millisecond),
)

Observability

Use WithOnStart, WithOnRequest, and WithOnResponse for logging and metrics. Callbacks execute synchronously as part of the actor's serialized lifecycle and should return promptly.

Documentation

Overview

Package modbus provides supervised, serialized access to Modbus TCP, RTU, and ASCII devices.

An Actor owns one Modbus connection for each execution attempt and runs requests against it one at a time. Concurrent callers are safe: the actor's resource primitive serializes their operations so a stateful connection is never used concurrently.

Getting started

Create an actor for the device, add it to a sup supervisor, and run the supervisor with the application's context:

device := modbus.NewActor(
	"plc",
	modbus.TCP,
	"192.168.1.50:502",
	1,
	modbus.WithTimeout(2*time.Second),
)

supervisor := sup.NewSupervisor("root", sup.Transient).
	AddActors(device).
	SetRestartDelay(time.Second)

go supervisor.Run(ctx)

Give every request a context, preferably with a deadline:

requestCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()

data, err := device.ReadHoldingRegisters(requestCtx, 100, 2)

Lifecycle and recovery

Each Actor.Run attempt creates and connects a fresh protocol handler. When the attempt ends, the handler is closed before a supervisor may start the actor again. Canceling the actor context is a clean shutdown and makes Run return nil.

A connection-level request failure is returned both to the caller and from Run. A transient supervisor can then reacquire a fresh connection according to its restart policy. Requests waiting for the actor remain pending across acquisition failures and restart delays until their own contexts end. Requests already accepted by an execution are never replayed, because a write may have taken effect even when its response was lost.

Calls and cancellation

All read and write methods block until their operation completes, the caller's context ends, or the active resource execution stops. Canceling a context removes a request that is still waiting for serialized access.

The underlying goburrow/modbus operations do not accept a context, so cancellation cannot interrupt transport I/O after it begins. WithTimeout bounds TCP connection establishment and in-flight transport I/O. Use a request deadline as well so callers do not wait indefinitely while the actor is unavailable.

Errors

Invalid quantities, coil values, and write payload sizes are rejected before resource handoff. These errors wrap ErrInvalidArgument and do not affect the connection.

Modbus exception responses are valid protocol responses. They are returned to the caller without stopping the actor. Other operation errors indicate transport loss or an unusable response and stop the current execution so supervision can decide whether to reconnect.

Serial transports

Use WithSerialConfig for RTU and ASCII serial parameters. WithRS485 enables RTU RS485 mode and configures independent RTS delays before and after sending. WithQuietTime adds a serialized delay after an RTU or ASCII request that leaves the connection usable.

Observability

WithOnStart runs after each successful connection, including supervised reconnections. WithOnRequest and WithOnResponse observe serialized operations. Callbacks run synchronously in the actor lifecycle and should return promptly.

See the README for a complete application example.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidArgument = errors.New("modbus: invalid argument")

ErrInvalidArgument identifies a request rejected before it reaches the Modbus connection.

Functions

This section is empty.

Types

type Actor added in v0.0.5

type Actor struct {
	// contains filtered or unexported fields
}

Actor owns a Modbus connection and serializes all access to it. Connection failures stop the current execution so a sup Supervisor can reconnect it.

func NewActor added in v0.0.5

func NewActor(id string, protocol Protocol, address string, slaveID byte, opts ...ActorOption) *Actor

NewActor creates a supervised Modbus resource actor.

func (*Actor) ID added in v0.0.10

func (a *Actor) ID() string

ID returns the actor identifier.

func (*Actor) MaskWriteRegister added in v0.0.5

func (a *Actor) MaskWriteRegister(ctx context.Context, address, andMask, orMask uint16) ([]byte, error)

MaskWriteRegister modifies one holding register using AND and OR masks.

func (*Actor) ReadCoils added in v0.0.5

func (a *Actor) ReadCoils(ctx context.Context, address, quantity uint16) ([]byte, error)

ReadCoils reads the state of one or more coils.

func (*Actor) ReadDiscreteInputs added in v0.0.5

func (a *Actor) ReadDiscreteInputs(ctx context.Context, address, quantity uint16) ([]byte, error)

ReadDiscreteInputs reads the state of one or more discrete inputs.

func (*Actor) ReadFIFOQueue added in v0.0.5

func (a *Actor) ReadFIFOQueue(ctx context.Context, address uint16) ([]byte, error)

ReadFIFOQueue reads a FIFO queue from its pointer address.

func (*Actor) ReadHoldingRegisters added in v0.0.5

func (a *Actor) ReadHoldingRegisters(ctx context.Context, address, quantity uint16) ([]byte, error)

ReadHoldingRegisters reads one or more holding registers.

Example
device := modbus.NewActor(
	"plc",
	modbus.TCP,
	"192.168.1.50:502",
	1,
	modbus.WithTimeout(2*time.Second),
)
_ = sup.NewSupervisor("root", sup.Transient).AddActors(device)

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_, _ = device.ReadHoldingRegisters(ctx, 100, 2)

func (*Actor) ReadInputRegisters added in v0.0.5

func (a *Actor) ReadInputRegisters(ctx context.Context, address, quantity uint16) ([]byte, error)

ReadInputRegisters reads one or more input registers.

func (*Actor) ReadWriteMultipleRegisters added in v0.0.5

func (a *Actor) ReadWriteMultipleRegisters(
	ctx context.Context,
	readAddress, readQuantity, writeAddress, writeQuantity uint16,
	value []byte,
) ([]byte, error)

ReadWriteMultipleRegisters writes registers and reads registers in one transaction.

func (*Actor) Run added in v0.0.5

func (a *Actor) Run(ctx context.Context) error

Run acquires the connection and serves serialized operations until the context is canceled or a connection-level operation fails.

func (*Actor) WriteMultipleCoils added in v0.0.5

func (a *Actor) WriteMultipleCoils(ctx context.Context, address, quantity uint16, value []byte) ([]byte, error)

WriteMultipleCoils writes one or more packed coil values.

func (*Actor) WriteMultipleRegisters added in v0.0.5

func (a *Actor) WriteMultipleRegisters(ctx context.Context, address, quantity uint16, value []byte) ([]byte, error)

WriteMultipleRegisters writes one or more holding registers.

func (*Actor) WriteSingleCoil added in v0.0.5

func (a *Actor) WriteSingleCoil(ctx context.Context, address, value uint16) ([]byte, error)

WriteSingleCoil writes one coil.

func (*Actor) WriteSingleRegister added in v0.0.5

func (a *Actor) WriteSingleRegister(ctx context.Context, address, value uint16) ([]byte, error)

WriteSingleRegister writes one holding register.

type ActorOption added in v0.0.5

type ActorOption func(*actorConfig)

ActorOption configures an Actor before it starts.

func WithOnRequest added in v0.0.8

func WithOnRequest(handler func(functionCode, slaveID byte, address, quantity uint16)) ActorOption

WithOnRequest sets a callback invoked before a Modbus request is executed.

func WithOnResponse added in v0.0.8

func WithOnResponse(handler func(functionCode, slaveID byte, response []byte, err error, duration time.Duration)) ActorOption

WithOnResponse sets a callback invoked after a Modbus request completes.

func WithOnStart added in v0.0.8

func WithOnStart(handler func(protocol Protocol, address string, slaveID byte)) ActorOption

WithOnStart sets a callback invoked after a connection is established.

func WithQuietTime added in v0.0.10

func WithQuietTime(delay time.Duration) ActorOption

WithQuietTime sets the delay after each RTU or ASCII request that leaves the connection usable.

func WithRS485 added in v0.0.10

func WithRS485(delayBeforeSend, delayAfterSend time.Duration) ActorOption

WithRS485 enables RS485 and configures its RTS delays.

func WithSerialConfig

func WithSerialConfig(baud, dataBits, stopBits int, parity string) ActorOption

WithSerialConfig configures serial communication for RTU and ASCII.

func WithTimeout

func WithTimeout(timeout time.Duration) ActorOption

WithTimeout sets the timeout for Modbus requests.

type Protocol added in v0.0.10

type Protocol uint8

Protocol identifies a supported Modbus transport.

const (
	// TCP uses Modbus TCP over a network connection.
	TCP Protocol = iota
	// RTU uses Modbus RTU over a serial connection.
	RTU
	// ASCII uses Modbus ASCII over a serial connection.
	ASCII
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址