Documentation
¶
Overview ¶
Package modbus provides a client for MODBUS TCP and RTU/ASCII.
Index ¶
- Constants
- Variables
- type ASCIIClientHandler
- func (mb *ASCIIClientHandler) Decode(adu []byte) (pdu *ProtocolDataUnit, err error)
- func (mb *ASCIIClientHandler) Encode(pdu *ProtocolDataUnit) (adu []byte, err error)
- func (mb *ASCIIClientHandler) Send(ctx context.Context, aduRequest []byte) (aduResponse []byte, err error)
- func (mb *ASCIIClientHandler) Verify(aduRequest, aduResponse []byte) (err error)
- type Client
- type ClientHandler
- type ModbusError
- type Packager
- type Parity
- type ProtocolDataUnit
- type RTUClientHandler
- func (mb *RTUClientHandler) Decode(adu []byte) (pdu *ProtocolDataUnit, err error)
- func (mb *RTUClientHandler) Encode(pdu *ProtocolDataUnit) (adu []byte, err error)
- func (mb *RTUClientHandler) Send(ctx context.Context, aduRequest []byte) (aduResponse []byte, err error)
- func (mb *RTUClientHandler) Verify(aduRequest, aduResponse []byte) (err error)
- type StopBits
- type TCPClientHandler
- func (mb *TCPClientHandler) Close() error
- func (mb *TCPClientHandler) Connect() error
- func (mb *TCPClientHandler) Decode(adu []byte) (pdu *ProtocolDataUnit, err error)
- func (mb *TCPClientHandler) Encode(pdu *ProtocolDataUnit) (adu []byte, err error)
- func (mb *TCPClientHandler) Send(ctx context.Context, aduRequest []byte) (aduResponse []byte, err error)
- func (mb *TCPClientHandler) Verify(aduRequest, aduResponse []byte) (err error)
- type Transporter
Constants ¶
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 )
const ( ExceptionCodeIllegalFunction = 1 ExceptionCodeIllegalDataAddress = 2 ExceptionCodeIllegalDataValue = 3 ExceptionCodeServerDeviceFailure = 4 ExceptionCodeAcknowledge = 5 ExceptionCodeServerDeviceBusy = 6 ExceptionCodeMemoryParityError = 8 ExceptionCodeGatewayTargetDeviceFailedToRespond = 11 )
Variables ¶
var ( // ErrInvalidQuantity is returned when a quantity parameter is outside valid range. ErrInvalidQuantity = errors.New("modbus: invalid quantity") // ErrInvalidAddress is returned when an address parameter is outside valid range. ErrInvalidAddress = errors.New("modbus: invalid address") // ErrInvalidData is returned when data length or values are invalid. ErrInvalidData = errors.New("modbus: invalid data") // ErrTimeout is returned when an operation times out. ErrTimeout = errors.New("modbus: timeout") // ErrNotConnected is returned when attempting operations on a closed connection. ErrNotConnected = errors.New("modbus: not connected") // ErrInvalidResponse is returned when a response is malformed or unexpected. ErrInvalidResponse = errors.New("modbus: invalid response") // ErrShortFrame is returned when a received frame is too short. ErrShortFrame = errors.New("modbus: response frame too short") // ErrProtocolError is returned for protocol-level violations. ErrProtocolError = errors.New("modbus: protocol error") )
Common errors returned by the modbus package.
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
type Client ¶
type Client interface {
// ReadCoils reads from 1 to 2000 contiguous status of coils in a
// remote device and returns coil status.
ReadCoils(ctx context.Context, 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(ctx context.Context, 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(ctx context.Context, 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(ctx context.Context, 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(ctx context.Context, 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(ctx context.Context, address, quantity uint16) (results []byte, err error)
// WriteSingleRegister writes a single holding register in a remote
// device and returns register value.
WriteSingleRegister(ctx context.Context, 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(ctx context.Context, 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(ctx context.Context, 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(ctx context.Context, 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(ctx context.Context, address uint16) (results []byte, err error)
}
func ASCIIClient ¶
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 NewClientWithPackagerTransporter ¶ added in v0.3.0
func NewClientWithPackagerTransporter(packager Packager, transporter Transporter) Client
NewClientWithPackagerTransporter creates a new modbus client with separate packager and transporter. This is useful for advanced use cases where you want to use different implementations for the packager and transporter, such as in testing scenarios.
type ClientHandler ¶
type ClientHandler interface {
Packager
Transporter
}
ClientHandler is the interface that groups the Packager and Transporter methods.
type ModbusError ¶
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)
}
Packager specifies the communication layer.
type Parity ¶ added in v0.2.0
type Parity string
Parity represents the parity mode for serial communication.
type ProtocolDataUnit ¶
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) Send ¶
func (mb *RTUClientHandler) Send(ctx context.Context, aduRequest []byte) (aduResponse []byte, err error)
Send transmits an RTU request and receives the response. This implementation uses Read() in a loop with context checks between iterations, rather than io.ReadFull(). This approach:
- Prevents indefinite hangs when devices send incomplete responses
- Allows context cancellation to be detected between read operations
- Improves reliability on systems where serial port timeouts are not well-supported
Note: Individual Read() calls may still block if the underlying device/driver doesn't support read timeouts (e.g., PTYs in tests). However, context is checked between reads, providing better timeout behavior than the previous io.ReadFull() approach.
type StopBits ¶ added in v0.2.0
type StopBits int
StopBits represents the number of stop bits for serial communication.
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 (*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