modbus

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: BSD-3-Clause Imports: 19 Imported by: ? 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

go modbus Build Status GoDoc

Fault-tolerant, fail-fast implementation of Modbus protocol in Go.

Supported functions

Bit access:

  • Read Discrete Inputs
  • Read Coils
  • Write Single Coil
  • Write Multiple Coils

16-bit access:

  • Read Input Registers
  • Read Holding Registers
  • Write Single Register
  • Write Multiple Registers
  • Read/Write Multiple Registers
  • Mask Write Register
  • Read FIFO Queue

Supported formats

  • TCP
  • Serial (RTU, ASCII)

Usage

Basic usage:

// Modbus TCP
client := modbus.TCPClient("localhost:502")
// Read input register 9
results, err := client.ReadInputRegisters(8, 1)

// Modbus RTU/ASCII
// Default configuration is 19200, 8, 1, even
client = modbus.RTUClient("/dev/ttyS0")
results, err = client.ReadCoils(2, 1)

Advanced usage:

// Modbus TCP
handler := modbus.NewTCPClientHandler("localhost:502")
handler.Timeout = 10 * time.Second
handler.SlaveId = 0xFF
handler.Logger = log.New(os.Stdout, "test: ", log.LstdFlags)
// Connect manually so that multiple requests are handled in one connection session
err := handler.Connect()
defer handler.Close()

client := modbus.NewClient(handler)
results, err := client.ReadDiscreteInputs(15, 2)
results, err = client.WriteMultipleRegisters(1, 2, []byte{0, 3, 0, 4})
results, err = client.WriteMultipleCoils(5, 10, []byte{4, 3})
// Modbus RTU/ASCII
handler := modbus.NewRTUClientHandler("/dev/ttyUSB0")
handler.BaudRate = 115200
handler.DataBits = 8
handler.Parity = "N"
handler.StopBits = 1
handler.SlaveId = 1
handler.Timeout = 5 * time.Second

err := handler.Connect()
defer handler.Close()

client := modbus.NewClient(handler)
results, err := client.ReadDiscreteInputs(15, 2)

References

Documentation

Overview

Package modbus provides a client for MODBUS TCP and RTU/ASCII.

Index

Constants

View Source
const (
	// Bit access
	FuncCodeReadDiscreteInputs = 2
	FuncCodeReadCoils          = 1
	FuncCodeWriteSingleCoil    = 5
	FuncCodeWriteMultipleCoils = 15

	// 16-bit access
	FuncCodeReadInputRegisters         = 4
	FuncCodeReadHoldingRegisters       = 3
	FuncCodeWriteSingleRegister        = 6
	FuncCodeWriteMultipleRegisters     = 16
	FuncCodeReadWriteMultipleRegisters = 23
	FuncCodeMaskWriteRegister          = 22
	FuncCodeReadFIFOQueue              = 24
)
View Source
const (
	ExceptionCodeIllegalFunction                    = 1
	ExceptionCodeIllegalDataAddress                 = 2
	ExceptionCodeIllegalDataValue                   = 3
	ExceptionCodeServerDeviceFailure                = 4
	ExceptionCodeAcknowledge                        = 5
	ExceptionCodeServerDeviceBusy                   = 6
	ExceptionCodeMemoryParityError                  = 8
	ExceptionCodeGatewayPathUnavailable             = 10
	ExceptionCodeGatewayTargetDeviceFailedToRespond = 11
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ASCIIClientHandler

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

ASCIIClientHandler implements Packager and Transporter interface.

func NewASCIIClientHandler

func NewASCIIClientHandler(address string) *ASCIIClientHandler

NewASCIIClientHandler allocates and initializes a ASCIIClientHandler.

func (*ASCIIClientHandler) Decode

func (mb *ASCIIClientHandler) Decode(adu []byte) (pdu *ProtocolDataUnit, err error)

Decode extracts PDU from ASCII frame and verify LRC.

func (*ASCIIClientHandler) Encode

func (mb *ASCIIClientHandler) Encode(pdu *ProtocolDataUnit) (adu []byte, err error)

Encode encodes PDU in a ASCII frame:

Start           : 1 char
Address         : 2 chars
Function        : 2 chars
Data            : 0 up to 2x252 chars
LRC             : 2 chars
End             : 2 chars

func (*ASCIIClientHandler) GetSlaveId added in v0.1.4

func (mb *ASCIIClientHandler) GetSlaveId() byte

func (*ASCIIClientHandler) Send

func (mb *ASCIIClientHandler) Send(aduRequest []byte) (aduResponse []byte, err error)

func (*ASCIIClientHandler) Verify

func (mb *ASCIIClientHandler) Verify(aduRequest []byte, aduResponse []byte) (err error)

Verify verifies response length, frame boundary and slave id.

type Client

type Client interface {

	// ReadCoils reads from 1 to 2000 contiguous status of coils in a
	// remote device and returns coil status.
	ReadCoils(address, quantity uint16) (results []byte, err error)
	// ReadDiscreteInputs reads from 1 to 2000 contiguous status of
	// discrete inputs in a remote device and returns input status.
	ReadDiscreteInputs(address, quantity uint16) (results []byte, err error)
	// WriteSingleCoil write a single output to either ON or OFF in a
	// remote device and returns output value.
	WriteSingleCoil(address, value uint16) (results []byte, err error)
	// WriteMultipleCoils forces each coil in a sequence of coils to either
	// ON or OFF in a remote device and returns quantity of outputs.
	WriteMultipleCoils(address, quantity uint16, value []byte) (results []byte, err error)

	// ReadInputRegisters reads from 1 to 125 contiguous input registers in
	// a remote device and returns input registers.
	ReadInputRegisters(address, quantity uint16) (results []byte, err error)
	// ReadHoldingRegisters reads the contents of a contiguous block of
	// holding registers in a remote device and returns register value.
	ReadHoldingRegisters(address, quantity uint16) (results []byte, err error)
	// WriteSingleRegister writes a single holding register in a remote
	// device and returns register value.
	WriteSingleRegister(address, value uint16) (results []byte, err error)
	// WriteMultipleRegisters writes a block of contiguous registers
	// (1 to 123 registers) in a remote device and returns quantity of
	// registers.
	WriteMultipleRegisters(address, quantity uint16, value []byte) (results []byte, err error)
	// ReadWriteMultipleRegisters performs a combination of one read
	// operation and one write operation. It returns read registers value.
	ReadWriteMultipleRegisters(readAddress, readQuantity, writeAddress, writeQuantity uint16, value []byte) (results []byte, err error)
	// MaskWriteRegister modify the contents of a specified holding
	// register using a combination of an AND mask, an OR mask, and the
	// register's current contents. The function returns
	// AND-mask and OR-mask.
	MaskWriteRegister(address, andMask, orMask uint16) (results []byte, err error)
	//ReadFIFOQueue reads the contents of a First-In-First-Out (FIFO) queue
	// of register in a remote device and returns FIFO value register.
	ReadFIFOQueue(address uint16) (results []byte, err error)
}

func ASCIIClient

func ASCIIClient(address string) Client

ASCIIClient creates ASCII client with default handler and given connect string.

func NewClient

func NewClient(handler ClientHandler) Client

NewClient creates a new modbus client with given backend handler.

func NewClient2

func NewClient2(packager Packager, transporter Transporter) Client

NewClient2 creates a new modbus client with given backend packager and transporter.

func NewClient3 added in v0.1.4

func NewClient3(packager Packager, transporter Transporter, options *ClientOptions) Client

func RTUClient

func RTUClient(address string) Client

RTUClient creates RTU client with default handler and given connect string.

func RTUTCPClient added in v0.1.6

func RTUTCPClient(address string) Client

RTUTCPClient creates an RTU-over-TCP client with the default handler and the given connect string.

func RTUTlsClient added in v0.1.7

func RTUTlsClient(address string, tlsConfig *TlsConfig) Client

RTUTlsClient creates a TLS-wrapped RTU-over-TCP client with the default handler and the given connect string plus TLS configuration.

func TCPClient

func TCPClient(address string) Client

TCPClient creates TCP client with default handler and given connect string.

func TlsClient added in v0.1.7

func TlsClient(address string, tlsConfig *TlsConfig) Client

TlsClient creates a TLS-wrapped TCP client with the default handler and the given connect string plus TLS configuration.

type ClientHandler

type ClientHandler interface {
	Packager
	Transporter
}

ClientHandler is the interface that groups the Packager and Transporter methods.

type ClientOptions added in v0.1.4

type ClientOptions struct {
	TxRxCallbackHandler TxRxCallbackHandler
	TxCallbackHandler   TxCallbackHandler
	RxCallbackHandler   RxCallbackHandler
}

type ModbusError

type ModbusError struct {
	FunctionCode  byte
	ExceptionCode byte
}

ModbusError implements error interface.

func (*ModbusError) Error

func (e *ModbusError) Error() string

Error converts known modbus exception code to error message.

type Packager

type Packager interface {
	Encode(pdu *ProtocolDataUnit) (adu []byte, err error)
	Decode(adu []byte) (pdu *ProtocolDataUnit, err error)
	Verify(aduRequest []byte, aduResponse []byte) (err error)
	GetSlaveId() byte
}

Packager specifies the communication layer.

func NewRtuPackager

func NewRtuPackager(slaveId byte) Packager

func NewTcpPackager

func NewTcpPackager(slaveId byte) Packager

type ProtocolDataUnit

type ProtocolDataUnit struct {
	FunctionCode byte
	Data         []byte
}

ProtocolDataUnit (PDU) is independent of underlying communication layers.

type RTUClientHandler

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

RTUClientHandler implements Packager and Transporter interface.

func NewRTUClientHandler

func NewRTUClientHandler(address string) *RTUClientHandler

NewRTUClientHandler allocates and initializes a RTUClientHandler.

func (*RTUClientHandler) Decode

func (mb *RTUClientHandler) Decode(adu []byte) (pdu *ProtocolDataUnit, err error)

Decode extracts PDU from RTU frame and verify CRC.

func (*RTUClientHandler) Encode

func (mb *RTUClientHandler) Encode(pdu *ProtocolDataUnit) (adu []byte, err error)

Encode encodes PDU in a RTU frame:

Slave Address   : 1 byte
Function        : 1 byte
Data            : 0 up to 252 bytes
CRC             : 2 byte

func (*RTUClientHandler) GetSlaveId added in v0.1.4

func (mb *RTUClientHandler) GetSlaveId() byte

func (*RTUClientHandler) Send

func (mb *RTUClientHandler) Send(aduRequest []byte) (aduResponse []byte, err error)

func (*RTUClientHandler) Verify

func (mb *RTUClientHandler) Verify(aduRequest []byte, aduResponse []byte) (err error)

Verify verifies response length and slave id.

type RTUServer added in v0.2.0

type RTUServer struct {
	// Serial port configuration (Address, BaudRate, ...). Its Timeout field
	// is the read/write timeout of the port: it bounds the inter-frame gap
	// detection for function codes whose request length cannot be predicted
	// and lets frame-error recovery make progress. Zero blocks forever.
	serial.Config
	// contains filtered or unexported fields
}

RTUServer implements a modbus-rtu server on a serial port. A single serve goroutine reads request frames, dispatches them to Handler and writes the responses, so the handler is never called concurrently.

Frames received with an invalid CRC are discarded without a response, as required by the MODBUS specification; broadcast requests (slave address 0) are executed but never answered.

func NewRTUServer added in v0.2.0

func NewRTUServer(address string, handler RequestHandler) *RTUServer

NewRTUServer allocates and initializes a RTUServer with the default serial timeout.

func (*RTUServer) ListenAndServe added in v0.2.0

func (s *RTUServer) ListenAndServe(ctx context.Context) error

ListenAndServe opens the serial port and serves requests until ctx is cancelled or the port fails. The port is closed on cancellation so a blocked read returns.

type RTUTCPClientHandler added in v0.1.6

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

RTUTCPClientHandler implements Packager and Transporter interface. It transports raw RTU frames (slave id + PDU + CRC) transparently over TCP, i.e. the wire format is identical to serial RTU but carried on a TCP socket without the Modbus TCP MBAP header.

The Packager side is fully reused from rtuPackager (CRC encode/decode/verify). The Transporter side reuses tcpTransporter for connection management and overrides Send to read RTU-framed responses.

func NewRTUTCPClientHandler added in v0.1.6

func NewRTUTCPClientHandler(address string) *RTUTCPClientHandler

NewRTUTCPClientHandler allocates and initializes a RTUTCPClientHandler.

func NewRTUTlsClientHandler added in v0.1.7

func NewRTUTlsClientHandler(address string, tlsConfig *TlsConfig) *RTUTCPClientHandler

NewRTUTlsClientHandler allocates and initializes a RTUTCPClientHandler configured to dial over TLS using the supplied TlsConfig. It reuses the RTUTCPClientHandler type (and therefore the embedded tcpTransporter's TLS path) and only sets the TLS field.

func (*RTUTCPClientHandler) Decode added in v0.1.6

func (mb *RTUTCPClientHandler) Decode(adu []byte) (pdu *ProtocolDataUnit, err error)

Decode extracts PDU from RTU frame and verify CRC.

func (*RTUTCPClientHandler) Encode added in v0.1.6

func (mb *RTUTCPClientHandler) Encode(pdu *ProtocolDataUnit) (adu []byte, err error)

Encode encodes PDU in a RTU frame:

Slave Address   : 1 byte
Function        : 1 byte
Data            : 0 up to 252 bytes
CRC             : 2 byte

func (*RTUTCPClientHandler) GetSlaveId added in v0.1.6

func (mb *RTUTCPClientHandler) GetSlaveId() byte

func (*RTUTCPClientHandler) Send added in v0.1.6

func (mb *RTUTCPClientHandler) Send(aduRequest []byte) (aduResponse []byte, err error)

Send sends a raw RTU frame over TCP and reads the RTU-framed response.

Unlike tcpTransporter.Send (which parses the MBAP length field to decide how many bytes to read), this reads the minimum RTU frame first and then reads the remainder based on the function code via calculateResponseLength. This mirrors rtuSerialTransporter.Send but drops the serial inter-frame timing (calculateDelay/time.Sleep), which is not required over TCP.

func (*RTUTCPClientHandler) Verify added in v0.1.6

func (mb *RTUTCPClientHandler) Verify(aduRequest []byte, aduResponse []byte) (err error)

Verify verifies response length and slave id.

type RTUTCPServer added in v0.2.0

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

RTUTCPServer implements a modbus-rtu server listening on TCP: the wire format is identical to serial RTU (slave address + PDU + CRC) but carried on TCP sockets without the modbus-tcp MBAP header, mirroring the client side RTUTCPClientHandler.

It shares the accept loop, connection accounting and graceful shutdown with TCPServer via tcpServerCore; only the per-connection framing differs. There is no broadcast semantics over TCP: requests with slave address 0 are answered like any other address.

func NewRTUTCPServer added in v0.2.0

func NewRTUTCPServer(address string, handler RequestHandler) *RTUTCPServer

NewRTUTCPServer allocates and initializes a RTUTCPServer with the default TCP timeouts.

func (*RTUTCPServer) ListenAndServe added in v0.2.0

func (s *RTUTCPServer) ListenAndServe(ctx context.Context) error

ListenAndServe listens on Address and serves client connections until ctx is cancelled or the listener fails: the listener and all client connections are closed so the serve goroutines exit, and ListenAndServe waits for them before returning ctx.Err.

type RTUTCPTransporter added in v0.1.6

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

RTUTCPTransporter is the exported form of rtuTCPTransporter, mirroring the TcpTransporter / RtuSerialTransporter exported wrappers.

func (*RTUTCPTransporter) Send added in v0.1.6

func (mb *RTUTCPTransporter) Send(aduRequest []byte) (aduResponse []byte, err error)

Send sends a raw RTU frame over TCP and reads the RTU-framed response.

Unlike tcpTransporter.Send (which parses the MBAP length field to decide how many bytes to read), this reads the minimum RTU frame first and then reads the remainder based on the function code via calculateResponseLength. This mirrors rtuSerialTransporter.Send but drops the serial inter-frame timing (calculateDelay/time.Sleep), which is not required over TCP.

type RequestHandler added in v0.2.0

type RequestHandler func(slaveId byte, pdu *ProtocolDataUnit) (payload []byte, err *ModbusError)

RequestHandler handles a decoded modbus request PDU. It is called from the serve goroutine(s) of a server.

slaveId is the slave address (RTU frame address field) or the unit identifier (modbus-tcp MBAP header) taken from the request, so one handler can serve multiple slave addresses.

Returning (payload, nil) produces a normal response whose PDU is {FunctionCode: request function code, Data: payload}. Returning a non-nil *ModbusError makes the server answer with an exception response (function code | 0x80 followed by the exception code).

type ResponseCache added in v0.2.1

type ResponseCache struct {
	// MaxEntries bounds the number of cached responses; entries are evicted
	// least-recently-used first. It must be positive for the cache to store
	// anything.
	MaxEntries int
	// Timeout is how long a cached response stays valid before the request
	// is executed again. Zero means entries never expire.
	Timeout time.Duration
	// contains filtered or unexported fields
}

ResponseCache stores the responses of read requests so that a repeated request is answered without running the Handler again. Entries are keyed by the slave address (or unit identifier) followed by the full request PDU: only exact matches hit. Write requests are never cached, and neither are exception responses (their cause may be transient).

A cache is safe for concurrent use by several serve goroutines.

type RtuSerialTransporter

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

func (*RtuSerialTransporter) Send

func (mb *RtuSerialTransporter) Send(aduRequest []byte) (aduResponse []byte, err error)

type RxCallbackHandler added in v0.1.5

type RxCallbackHandler func(slaveId byte, functionCode byte, data []byte, err error)

type TCPClientHandler

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

TCPClientHandler implements Packager and Transporter interface.

func NewTCPClientHandler

func NewTCPClientHandler(address string) *TCPClientHandler

NewTCPClientHandler allocates a new TCPClientHandler.

func NewTlsClientHandler added in v0.1.7

func NewTlsClientHandler(address string, tlsConfig *TlsConfig) *TCPClientHandler

NewTlsClientHandler allocates a TCPClientHandler configured to dial over TLS using the supplied TlsConfig. It reuses the TCPClientHandler type and only sets the TLS field, so all packager/transporter behaviour is shared with the plain-TCP path.

func (*TCPClientHandler) Close

func (mb *TCPClientHandler) Close() error

Close closes current connection.

func (*TCPClientHandler) Connect

func (mb *TCPClientHandler) Connect() error

Connect establishes a new connection to the address in Address. Connect and Close are exported so that multiple requests can be done with one session

func (*TCPClientHandler) Decode

func (mb *TCPClientHandler) Decode(adu []byte) (pdu *ProtocolDataUnit, err error)

Decode extracts PDU from TCP frame:

Transaction identifier: 2 bytes
Protocol identifier: 2 bytes
Length: 2 bytes
Unit identifier: 1 byte

func (*TCPClientHandler) Encode

func (mb *TCPClientHandler) Encode(pdu *ProtocolDataUnit) (adu []byte, err error)

Encode adds modbus application protocol header:

Transaction identifier: 2 bytes
Protocol identifier: 2 bytes
Length: 2 bytes
Unit identifier: 1 byte
Function code: 1 byte
Data: n bytes

func (*TCPClientHandler) GetSlaveId added in v0.1.4

func (mb *TCPClientHandler) GetSlaveId() byte

func (*TCPClientHandler) Send

func (mb *TCPClientHandler) Send(aduRequest []byte) (aduResponse []byte, err error)

Send sends data to server and ensures response length is greater than header length.

func (*TCPClientHandler) Verify

func (mb *TCPClientHandler) Verify(aduRequest []byte, aduResponse []byte) (err error)

Verify confirms transaction, protocol and unit id.

type TCPServer added in v0.2.0

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

TCPServer implements a modbus-tcp server. Each client connection is served by its own goroutine; all goroutines share Handler (serialized with a mutex) and the callbacks.

Responses echo the transaction, protocol and unit identifiers of the request, so several requests of one client may be in flight.

func NewTCPServer added in v0.2.0

func NewTCPServer(address string, handler RequestHandler) *TCPServer

NewTCPServer allocates and initializes a TCPServer with the default TCP timeouts.

func (*TCPServer) ListenAndServe added in v0.2.0

func (s *TCPServer) ListenAndServe(ctx context.Context) error

ListenAndServe listens on Address and serves client connections until ctx is cancelled or the listener fails: the listener and all client connections are closed so the serve goroutines exit, and ListenAndServe waits for them before returning ctx.Err.

type TcpTransporter

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

func (*TcpTransporter) Close

func (mb *TcpTransporter) Close() error

Close closes current connection.

func (*TcpTransporter) Connect

func (mb *TcpTransporter) Connect() error

Connect establishes a new connection to the address in Address. Connect and Close are exported so that multiple requests can be done with one session

func (*TcpTransporter) Send

func (mb *TcpTransporter) Send(aduRequest []byte) (aduResponse []byte, err error)

Send sends data to server and ensures response length is greater than header length.

type TlsConfig added in v0.1.7

type TlsConfig struct {
	MinVersion          string `json:"minVersion"`
	MaxVersion          string `json:"maxVersion"`
	InsecureSkipVerify  bool   `json:"insecureSkipVerify"`
	OverWriteServerName string `json:"overWriteServerName"`
	ServerCert          string `json:"serverCert"`
	ClientCert          string `json:"clientCert"`
	ClientKey           string `json:"clientKey"`
}

TlsConfig holds configuration options for TLS connections in the Modbus package. It allows specifying the minimum and maximum TLS versions, whether to skip certificate verification, an optional server name override, and the PEM-encoded server and client certificates and keys.

ServerCert/ClientCert/ClientKey is the PEM text of the certificate/key (i.e. the verbatim content of the corresponding PEM file). No base64 wrapping is applied by the caller; the strings are parsed directly with x509.AppendCertsFromPEM / tls.X509KeyPair.

type Transporter

type Transporter interface {
	Send(aduRequest []byte) (aduResponse []byte, err error)
}

Transporter specifies the transport layer.

type TxCallbackHandler added in v0.1.4

type TxCallbackHandler func(slaveId byte, functionCode byte, data []byte, err error)

type TxRxCallbackHandler added in v0.1.5

type TxRxCallbackHandler func(slaveId byte, functionCode byte, txData []byte, rxData []byte, err error)

Directories

Path Synopsis
commw32 command
Port of commw32.c To generate go types: go tool cgo commw32.go
Port of commw32.c To generate go types: go tool cgo commw32.go

Jump to

Keyboard shortcuts

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