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 ¶
- Variables
- type Actor
- func (a *Actor) ID() string
- func (a *Actor) MaskWriteRegister(ctx context.Context, address, andMask, orMask uint16) ([]byte, error)
- func (a *Actor) ReadCoils(ctx context.Context, address, quantity uint16) ([]byte, error)
- func (a *Actor) ReadDiscreteInputs(ctx context.Context, address, quantity uint16) ([]byte, error)
- func (a *Actor) ReadFIFOQueue(ctx context.Context, address uint16) ([]byte, error)
- func (a *Actor) ReadHoldingRegisters(ctx context.Context, address, quantity uint16) ([]byte, error)
- func (a *Actor) ReadInputRegisters(ctx context.Context, address, quantity uint16) ([]byte, error)
- func (a *Actor) ReadWriteMultipleRegisters(ctx context.Context, ...) ([]byte, error)
- func (a *Actor) Run(ctx context.Context) error
- func (a *Actor) WriteMultipleCoils(ctx context.Context, address, quantity uint16, value []byte) ([]byte, error)
- func (a *Actor) WriteMultipleRegisters(ctx context.Context, address, quantity uint16, value []byte) ([]byte, error)
- func (a *Actor) WriteSingleCoil(ctx context.Context, address, value uint16) ([]byte, error)
- func (a *Actor) WriteSingleRegister(ctx context.Context, address, value uint16) ([]byte, error)
- type ActorOption
- func WithOnRequest(handler func(functionCode, slaveID byte, address, quantity uint16)) ActorOption
- func WithOnResponse(...) ActorOption
- func WithOnStart(handler func(protocol Protocol, address string, slaveID byte)) ActorOption
- func WithQuietTime(delay time.Duration) ActorOption
- func WithRS485(delayBeforeSend, delayAfterSend time.Duration) ActorOption
- func WithSerialConfig(baud, dataBits, stopBits int, parity string) ActorOption
- func WithTimeout(timeout time.Duration) ActorOption
- type Protocol
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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) 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) ReadDiscreteInputs ¶ added in v0.0.5
ReadDiscreteInputs reads the state of one or more discrete inputs.
func (*Actor) ReadFIFOQueue ¶ added in v0.0.5
ReadFIFOQueue reads a FIFO queue from its pointer address.
func (*Actor) ReadHoldingRegisters ¶ added in v0.0.5
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
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
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
WriteSingleCoil writes one coil.
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.