Documentation
¶
Overview ¶
Package modbus provides a client for MODBUS TCP and RTU/ASCII.
Index ¶
- Constants
- 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) GetSlaveId() byte
- func (mb *ASCIIClientHandler) Send(aduRequest []byte) (aduResponse []byte, err error)
- func (mb *ASCIIClientHandler) Verify(aduRequest []byte, aduResponse []byte) (err error)
- type Client
- func ASCIIClient(address string) Client
- func NewClient(handler ClientHandler) Client
- func NewClient2(packager Packager, transporter Transporter) Client
- func NewClient3(packager Packager, transporter Transporter, options *ClientOptions) Client
- func RTUClient(address string) Client
- func RTUTCPClient(address string) Client
- func RTUTlsClient(address string, tlsConfig *TlsConfig) Client
- func TCPClient(address string) Client
- func TlsClient(address string, tlsConfig *TlsConfig) Client
- type ClientHandler
- type ClientOptions
- type ModbusError
- type Packager
- 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) GetSlaveId() byte
- func (mb *RTUClientHandler) Send(aduRequest []byte) (aduResponse []byte, err error)
- func (mb *RTUClientHandler) Verify(aduRequest []byte, aduResponse []byte) (err error)
- type RTUServer
- type RTUTCPClientHandler
- func (mb *RTUTCPClientHandler) Decode(adu []byte) (pdu *ProtocolDataUnit, err error)
- func (mb *RTUTCPClientHandler) Encode(pdu *ProtocolDataUnit) (adu []byte, err error)
- func (mb *RTUTCPClientHandler) GetSlaveId() byte
- func (mb *RTUTCPClientHandler) Send(aduRequest []byte) (aduResponse []byte, err error)
- func (mb *RTUTCPClientHandler) Verify(aduRequest []byte, aduResponse []byte) (err error)
- type RTUTCPServer
- type RTUTCPTransporter
- type RequestHandler
- type ResponseCache
- type RtuSerialTransporter
- type RxCallbackHandler
- 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) GetSlaveId() byte
- func (mb *TCPClientHandler) Send(aduRequest []byte) (aduResponse []byte, err error)
- func (mb *TCPClientHandler) Verify(aduRequest []byte, aduResponse []byte) (err error)
- type TCPServer
- type TcpTransporter
- type TlsConfig
- type Transporter
- type TxCallbackHandler
- type TxRxCallbackHandler
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 ¶
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
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 ¶
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 RTUTCPClient ¶ added in v0.1.6
RTUTCPClient creates an RTU-over-TCP client with the default handler and the given connect string.
func RTUTlsClient ¶ added in v0.1.7
RTUTlsClient creates a TLS-wrapped RTU-over-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 ¶
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 NewTcpPackager ¶
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) GetSlaveId ¶ added in v0.1.4
func (mb *RTUClientHandler) GetSlaveId() byte
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.
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
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 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
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
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
}
type RxCallbackHandler ¶ added in v0.1.5
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
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
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.
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 ¶
Transporter specifies the transport layer.