modbus

package module
v0.0.0-...-7b7b138 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2024 License: MIT Imports: 18 Imported by: 0

README

go modbus

modbus write in pure go, support rtu,ascii,tcp master library,also support tcp slave.

Supported formats
  • modbus Serial(RTU,ASCII) Client
  • modbus TCP Client
  • modbus TCP Server
Features
  • object pool design,reduce memory allocation
  • fast encode and decode
  • interface design
  • simple API and support raw data api
Installation

Use go get.

    go get github.com/JasonVanCode/modubsprotocal

Then import the package into your own code.

    import modbus "github.com/JasonVanCode/modubsprotocal"
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
Example

modbus RTU/ASCII client see example

package main

import (
	"fmt"
	"time"

	"github.com/goburrow/serial"

	modbus "github.com/JasonVanCode/modubsprotocal"
)

func main() {
	p := modbus.NewRTUClientProvider(modbus.WithEnableLogger(),
		modbus.WithSerialConfig(serial.Config{
			Address:  "/dev/ttyUSB0",
			BaudRate: 115200,
			DataBits: 8,
			StopBits: 1,
			Parity:   "N",
			Timeout:  modbus.SerialDefaultTimeout,
		}))

	client := modbus.NewClient(p)
	err := client.Connect()
	if err != nil {
		fmt.Println("connect failed, ", err)
		return
	}
	defer client.Close()

	fmt.Println("starting")
	for {
		_, err := client.ReadCoils(3, 0, 10)
		if err != nil {
			fmt.Println(err.Error())
		}

		//	fmt.Printf("ReadDiscreteInputs %#v\r\n", results)

		time.Sleep(time.Second * 2)
	}
}

modbus TCP client see example

package main

import (
	"fmt"
	"time"

	modbus "github.com/JasonVanCode/modubsprotocal"
)

func main() {
	p := modbus.NewTCPClientProvider("192.168.199.188:502", modbus.WithEnableLogger())
	client := modbus.NewClient(p)
	err := client.Connect()
	if err != nil {
		fmt.Println("connect failed, ", err)
		return
	}
	defer client.Close()

	fmt.Println("starting")
	for {
		_, err := client.ReadCoils(1, 0, 10)
		if err != nil {
			fmt.Println(err.Error())
		}

		//	fmt.Printf("ReadDiscreteInputs %#v\r\n", results)

		time.Sleep(time.Second * 2)
	}
}

modbus TCP server see example

package main

import (
	modbus "github.com/JasonVanCode/modubsprotocal"
)

func main() {
	srv := modbus.NewTCPServer()
	srv.LogMode(true)
	srv.AddNodes(
		modbus.NewNodeRegister(
			1,
			0, 10, 0, 10,
			0, 10, 0, 10),
		modbus.NewNodeRegister(
			2,
			0, 10, 0, 10,
			0, 10, 0, 10),
		modbus.NewNodeRegister(
			3,
			0, 10, 0, 10,
			0, 10, 0, 10))

	err := srv.ListenAndServe(":502")
	if err != nil {
		panic(err)
	}
}
References

Documentation

Overview

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

Index

Constants

View Source
const (
	// TCPDefaultTimeout TCP Default timeout
	TCPDefaultTimeout = 1 * time.Second
	// TCPDefaultAutoReconnect TCP Default auto reconnect count
	TCPDefaultAutoReconnect = 1
)
View Source
const (
	FuncReadMinSize       = 4 // 读操作 最小数据域个数
	FuncWriteMinSize      = 4 // 写操作 最小数据域个数
	FuncWriteMultiMinSize = 5 // 写多个操作 最小数据域个数
	FuncReadWriteMinSize  = 9 // 读写操作 最小数据域个数
	FuncMaskWriteMinSize  = 6 // 屏蔽写操作 最小数据域个数
)

handle pdu data filed limit size.

View Source
const (
	AddressBroadCast = 0
	AddressMin       = 1
	AddressMax       = 247
)

proto address limit.

View Source
const (
	// Bits
	ReadBitsQuantityMin  = 1    // 0x0001
	ReadBitsQuantityMax  = 2000 // 0x07d0
	WriteBitsQuantityMin = 1    // 1
	WriteBitsQuantityMax = 1968 // 0x07b0
	// 16 Bits
	ReadRegQuantityMin             = 1   // 1
	ReadRegQuantityMax             = 125 // 0x007d
	WriteRegQuantityMin            = 1   // 1
	WriteRegQuantityMax            = 123 // 0x007b
	ReadWriteOnReadRegQuantityMin  = 1   // 1
	ReadWriteOnReadRegQuantityMax  = 125 // 0x007d
	ReadWriteOnWriteRegQuantityMin = 1   // 1
	ReadWriteOnWriteRegQuantityMax = 121 // 0x0079
)

proto register limit

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
	FuncCodeOtherReportSlaveID         = 17
)

Function Code

View Source
const (
	ExceptionCodeIllegalFunction                    = 1
	ExceptionCodeIllegalDataAddress                 = 2
	ExceptionCodeIllegalDataValue                   = 3
	ExceptionCodeServerDeviceFailure                = 4
	ExceptionCodeAcknowledge                        = 5
	ExceptionCodeServerDeviceBusy                   = 6
	ExceptionCodeNegativeAcknowledge                = 7
	ExceptionCodeMemoryParityError                  = 8
	ExceptionCodeGatewayPathUnavailable             = 10
	ExceptionCodeGatewayTargetDeviceFailedToRespond = 11
)

Exception Code

View Source
const (
	TCPDefaultReadTimeout  = 60 * time.Second
	TCPDefaultWriteTimeout = 1 * time.Second
)

TCP Default read & write timeout

View Source
const (
	DefaultConnectTimeout    = 15 * time.Second
	DefaultReconnectInterval = 1 * time.Minute
	DefaultKeepAliveInterval = 30 * time.Second
)

defined default value

View Source
const SerialDefaultTimeout = 1 * time.Second

SerialDefaultTimeout Serial Default timeout

Variables

This section is empty.

Functions

func CRC16

func CRC16(bs []byte) uint16

CRC16 Calculate Cyclical Redundancy Checking.

Types

type ASCIIClientProvider

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

ASCIIClientProvider implements ClientProvider interface.

func NewASCIIClientProvider

func NewASCIIClientProvider(opts ...ClientProviderOption) *ASCIIClientProvider

NewASCIIClientProvider allocates and initializes a ASCIIClientProvider. it will use default /dev/ttyS0 19200 8 1 N and timeout 1000.

func (*ASCIIClientProvider) Close

func (sf *ASCIIClientProvider) Close() (err error)

Close close current connection.

func (*ASCIIClientProvider) Connect

func (sf *ASCIIClientProvider) Connect() (err error)

Connect try to connect the remote server

func (ASCIIClientProvider) Debugf

func (sf ASCIIClientProvider) Debugf(format string, v ...interface{})

Debug Log DEBUG level message.

func (ASCIIClientProvider) Errorf

func (sf ASCIIClientProvider) Errorf(format string, v ...interface{})

Error Log ERROR level message.

func (*ASCIIClientProvider) IsConnected

func (sf *ASCIIClientProvider) IsConnected() (b bool)

IsConnected returns a bool signifying whether the client is connected or not.

func (*ASCIIClientProvider) LogMode

func (sf *ASCIIClientProvider) LogMode(enable bool)

LogMode set enable or disable log output when you has set logger.

func (*ASCIIClientProvider) Send

func (sf *ASCIIClientProvider) Send(slaveID byte, request ProtocolDataUnit) (ProtocolDataUnit, error)

Send request to the remote server,it implements on SendRawFrame.

func (*ASCIIClientProvider) SendPdu

func (sf *ASCIIClientProvider) SendPdu(slaveID byte, pduRequest []byte) ([]byte, error)

SendPdu send pdu request to the remote server.

func (*ASCIIClientProvider) SendRawFrame

func (sf *ASCIIClientProvider) SendRawFrame(aduRequest []byte) (aduResponse []byte, err error)

SendRawFrame send Adu frame.

type Client

type Client interface {
	ClientProvider

	// ReadCoils reads from 1 to 2000 contiguous status of coils in a
	// remote device and returns coil status.
	ReadCoils(slaveID byte, 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(slaveID byte, address, quantity uint16) (results []byte, err error)

	// WriteSingleCoil write a single output to either ON or OFF in a
	// remote device and returns success or failed.
	WriteSingleCoil(slaveID byte, address uint16, isOn bool) error
	// WriteMultipleCoils forces each coil in a sequence of coils to either
	// ON or OFF in a remote device and returns success or failed.
	WriteMultipleCoils(slaveID byte, address, quantity uint16, value []byte) error

	// ReadInputRegistersBytes reads from 1 to 125 contiguous input registers in
	// a remote device and returns input registers.
	ReadInputRegistersBytes(slaveID byte, address, quantity uint16) (results []byte, err error)
	// ReadInputRegisters reads from 1 to 125 contiguous input registers in
	// a remote device and returns input registers.
	ReadInputRegisters(slaveID byte, address, quantity uint16) (results []uint16, err error)

	// ReadHoldingRegistersBytes reads the contents of a contiguous block of
	// holding registers in a remote device and returns register value.
	ReadHoldingRegistersBytes(slaveID byte, 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(slaveID byte, address, quantity uint16) (results []uint16, err error)

	// WriteSingleRegister writes a single holding register in a remote
	// device and returns success or failed.
	WriteSingleRegister(slaveID byte, address, value uint16) error
	// WriteMultipleRegistersBytes writes a block of contiguous registers
	// (1 to 123 registers) in a remote device and returns success or failed.
	WriteMultipleRegistersBytes(slaveID byte, address, quantity uint16, value []byte) error
	// WriteMultipleRegisters writes a block of contiguous registers
	// (1 to 123 registers) in a remote device and returns success or failed.
	WriteMultipleRegisters(slaveID byte, address, quantity uint16, value []uint16) error

	// ReadWriteMultipleRegistersBytes performs a combination of one read
	// operation and one write operation. It returns read registers value.
	ReadWriteMultipleRegistersBytes(slaveID byte, readAddress, readQuantity,
		writeAddress, writeQuantity 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(slaveID byte, readAddress, readQuantity,
		writeAddress, writeQuantity uint16, value []byte) (results []uint16, 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 success or failed.
	MaskWriteRegister(slaveID byte, address, andMask, orMask uint16) 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(slaveID byte, address uint16) (results []byte, err error)
}

Client interface.

func NewClient

func NewClient(p ClientProvider, opts ...Option) Client

NewClient creates a new modbus client with given backend handler. default proto address limit is 1~247 AddressMax you can change with custom option. // when your device have address upon addressMax

type ClientProvider

type ClientProvider interface {
	// Connect try to connect the remote server
	Connect() error
	// IsConnected returns a bool signifying whether
	// the client is connected or not.
	IsConnected() bool
	// LogMode set enable or diable log output when you has set logger
	LogMode(enable bool)
	// Close disconnect the remote server
	Close() error
	// Send request to the remote server,it implements on SendRawFrame
	Send(slaveID byte, request ProtocolDataUnit) (ProtocolDataUnit, error)
	// SendPdu send pdu request to the remote server
	SendPdu(slaveID byte, pduRequest []byte) (pduResponse []byte, err error)
	// SendRawFrame send raw frame to the remote server
	SendRawFrame(aduRequest []byte) (aduResponse []byte, err error)
	// contains filtered or unexported methods
}

ClientProvider is the interface implements underlying methods.

type ClientProviderOption

type ClientProviderOption func(ClientProvider)

ClientProviderOption client provider option for user.

func WithEnableLogger

func WithEnableLogger() ClientProviderOption

WithEnableLogger enable log output when you has set logger.

func WithLogProvider

func WithLogProvider(provider LogProvider) ClientProviderOption

WithLogProvider set logger provider.

func WithSerialConfig

func WithSerialConfig(config serial.Config) ClientProviderOption

WithSerialConfig set serial config, only valid on serial.

func WithTCPTimeout

func WithTCPTimeout(t time.Duration) ClientProviderOption

WithTCPTimeout set tcp Connect & Read timeout, only valid on TCP.

type ExceptionError

type ExceptionError struct {
	ExceptionCode byte
}

ExceptionError implements error interface.

func (*ExceptionError) Error

func (e *ExceptionError) Error() string

Error converts known modbus exception code to error message.

type FunctionHandler

type FunctionHandler func(reg *NodeRegister, data []byte) ([]byte, error)

FunctionHandler 功能码对应的函数回调. data 仅pdu数据域 不含功能码, return pdu 数据域,不含功能码.

type LRC

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

LRC lrc sum.

func (*LRC) Push

func (sf *LRC) Push(data ...byte) *LRC

Push data in sum.

func (*LRC) Reset

func (sf *LRC) Reset() *LRC

Reset rest lrc sum.

func (*LRC) Value

func (sf *LRC) Value() byte

Value got lrc value.

type LogProvider

type LogProvider interface {
	Errorf(format string, v ...interface{})
	Debugf(format string, v ...interface{})
}

LogProvider RFC5424 log message levels only Debug and Error

type NodeRegister

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

NodeRegister 节点寄存器

func NewNodeRegister

func NewNodeRegister(slaveID byte,
	coilsAddrStart, coilsQuantity,
	discreteAddrStart, discreteQuantity,
	inputAddrStart, inputQuantity,
	holdingAddrStart, holdingQuantity uint16) *NodeRegister

NewNodeRegister 创建一个modbus子节点寄存器列表

func (*NodeRegister) CoilsAddrParam

func (sf *NodeRegister) CoilsAddrParam() (start, quantity uint16)

CoilsAddrParam 读coil起始地址与数量

func (*NodeRegister) DiscreteParam

func (sf *NodeRegister) DiscreteParam() (start, quantity uint16)

DiscreteParam 读discrete起始地址与数量

func (*NodeRegister) HoldingAddrParam

func (sf *NodeRegister) HoldingAddrParam() (start, quantity uint16)

HoldingAddrParam 读holding起始地址与数量

func (*NodeRegister) InputAddrParam

func (sf *NodeRegister) InputAddrParam() (start, quantity uint16)

InputAddrParam 读input起始地址与数量

func (*NodeRegister) MaskWriteHolding

func (sf *NodeRegister) MaskWriteHolding(address, andMask, orMask uint16) error

MaskWriteHolding 屏蔽写保持寄存器 (val & andMask) | (orMask & ^andMask)

func (*NodeRegister) ReadCoils

func (sf *NodeRegister) ReadCoils(address, quality uint16) ([]byte, error)

ReadCoils 读线圈,返回值

func (*NodeRegister) ReadDiscretes

func (sf *NodeRegister) ReadDiscretes(address, quality uint16) ([]byte, error)

ReadDiscretes 读离散量

func (*NodeRegister) ReadHoldings

func (sf *NodeRegister) ReadHoldings(address, quality uint16) ([]uint16, error)

ReadHoldings 读保持寄存器,仅返回寄存器值

func (*NodeRegister) ReadHoldingsBytes

func (sf *NodeRegister) ReadHoldingsBytes(address, quality uint16) ([]byte, error)

ReadHoldingsBytes 读保持寄存器,仅返回寄存器值

func (*NodeRegister) ReadInputs

func (sf *NodeRegister) ReadInputs(address, quality uint16) ([]uint16, error)

ReadInputs 读输入寄存器

func (*NodeRegister) ReadInputsBytes

func (sf *NodeRegister) ReadInputsBytes(address, quality uint16) ([]byte, error)

ReadInputsBytes 读输入寄存器

func (*NodeRegister) ReadSingleCoil

func (sf *NodeRegister) ReadSingleCoil(address uint16) (bool, error)

ReadSingleCoil 读单个线圈

func (*NodeRegister) ReadSingleDiscrete

func (sf *NodeRegister) ReadSingleDiscrete(address uint16) (bool, error)

ReadSingleDiscrete 读单个离散量

func (*NodeRegister) SetSlaveID

func (sf *NodeRegister) SetSlaveID(id byte) *NodeRegister

SetSlaveID 更改从站地址

func (*NodeRegister) SlaveID

func (sf *NodeRegister) SlaveID() byte

SlaveID 获取从站地址

func (*NodeRegister) WriteCoils

func (sf *NodeRegister) WriteCoils(address, quality uint16, valBuf []byte) error

WriteCoils 写线圈

func (*NodeRegister) WriteDiscretes

func (sf *NodeRegister) WriteDiscretes(address, quality uint16, valBuf []byte) error

WriteDiscretes 写离散量

func (*NodeRegister) WriteHoldings

func (sf *NodeRegister) WriteHoldings(address uint16, valBuf []uint16) error

WriteHoldings 写保持寄存器

func (*NodeRegister) WriteHoldingsBytes

func (sf *NodeRegister) WriteHoldingsBytes(address, quality uint16, valBuf []byte) error

WriteHoldingsBytes 写保持寄存器

func (*NodeRegister) WriteInputs

func (sf *NodeRegister) WriteInputs(address uint16, valBuf []uint16) error

WriteInputs 写输入寄存器

func (*NodeRegister) WriteInputsBytes

func (sf *NodeRegister) WriteInputsBytes(address, quality uint16, regBuf []byte) error

WriteInputsBytes 写输入寄存器

func (*NodeRegister) WriteSingleCoil

func (sf *NodeRegister) WriteSingleCoil(address uint16, val bool) error

WriteSingleCoil 写单个线圈

func (*NodeRegister) WriteSingleDiscrete

func (sf *NodeRegister) WriteSingleDiscrete(address uint16, val bool) error

WriteSingleDiscrete 写单个离散量

type OnConnectHandler

type OnConnectHandler func(c *TCPServerSpecial) error

OnConnectHandler when connected it will be call

type OnConnectionLostHandler

type OnConnectionLostHandler func(c *TCPServerSpecial)

OnConnectionLostHandler when Connection lost it will be call

type OnKeepAliveHandler

type OnKeepAliveHandler func(c *TCPServerSpecial)

OnKeepAliveHandler keep alive function

type Option

type Option func(c *client)

Option custom option

func WithAddressMax

func WithAddressMax(v byte) Option

WithAddressMax set custom address max value, default AddressMax

func WithAddressMin

func WithAddressMin(v byte) Option

WithAddressMin set custom address max value, default AddressMin

type ProtocolDataUnit

type ProtocolDataUnit struct {
	FuncCode byte
	Data     []byte
}

ProtocolDataUnit (PDU) is independent of underlying communication layers.

type RTUClientProvider

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

RTUClientProvider implements ClientProvider interface.

func NewRTUClientProvider

func NewRTUClientProvider(opts ...ClientProviderOption) *RTUClientProvider

NewRTUClientProvider allocates and initializes a RTUClientProvider. it will use default /dev/ttyS0 19200 8 1 N and timeout 1000

func (*RTUClientProvider) Close

func (sf *RTUClientProvider) Close() (err error)

Close close current connection.

func (*RTUClientProvider) Connect

func (sf *RTUClientProvider) Connect() (err error)

Connect try to connect the remote server

func (RTUClientProvider) Debugf

func (sf RTUClientProvider) Debugf(format string, v ...interface{})

Debug Log DEBUG level message.

func (RTUClientProvider) Errorf

func (sf RTUClientProvider) Errorf(format string, v ...interface{})

Error Log ERROR level message.

func (*RTUClientProvider) IsConnected

func (sf *RTUClientProvider) IsConnected() (b bool)

IsConnected returns a bool signifying whether the client is connected or not.

func (*RTUClientProvider) LogMode

func (sf *RTUClientProvider) LogMode(enable bool)

LogMode set enable or disable log output when you has set logger.

func (*RTUClientProvider) Send

func (sf *RTUClientProvider) Send(slaveID byte, request ProtocolDataUnit) (ProtocolDataUnit, error)

Send request to the remote server, it implements on SendRawFrame

func (*RTUClientProvider) SendPdu

func (sf *RTUClientProvider) SendPdu(slaveID byte, pduRequest []byte) ([]byte, error)

SendPdu send pdu request to the remote server

func (*RTUClientProvider) SendRawFrame

func (sf *RTUClientProvider) SendRawFrame(aduRequest []byte) (aduResponse []byte, err error)

SendRawFrame send Adu frame

type ServerSession

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

ServerSession tcp server session

func (ServerSession) AddNodes

func (sf ServerSession) AddNodes(nodes ...*NodeRegister)

AddNodes 增加节点.

func (ServerSession) Debugf

func (sf ServerSession) Debugf(format string, v ...interface{})

Debug Log DEBUG level message.

func (ServerSession) DeleteAllNode

func (sf ServerSession) DeleteAllNode()

DeleteAllNode 删除所有节点.

func (ServerSession) DeleteNode

func (sf ServerSession) DeleteNode(slaveID byte)

DeleteNode 删除一个节点.

func (ServerSession) Errorf

func (sf ServerSession) Errorf(format string, v ...interface{})

Error Log ERROR level message.

func (ServerSession) GetNode

func (sf ServerSession) GetNode(slaveID byte) (*NodeRegister, error)

GetNode 获取一个节点.

func (ServerSession) GetNodeList

func (sf ServerSession) GetNodeList() []*NodeRegister

GetNodeList 获取节点列表.

func (*ServerSession) LogMode

func (sf *ServerSession) LogMode(enable bool)

LogMode set enable or disable log output when you has set logger.

func (ServerSession) Range

func (sf ServerSession) Range(f func(slaveID byte, node *NodeRegister) bool)

Range 扫描节点 same as sync map range.

func (ServerSession) RegisterFunctionHandler

func (sf ServerSession) RegisterFunctionHandler(funcCode uint8, function FunctionHandler)

RegisterFunctionHandler 注册回调函数.

type TCPClientProvider

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

TCPClientProvider implements ClientProvider interface.

func NewTCPClientProvider

func NewTCPClientProvider(address string, opts ...ClientProviderOption) *TCPClientProvider

NewTCPClientProvider allocates a new TCPClientProvider.

func (*TCPClientProvider) Close

func (sf *TCPClientProvider) Close() (err error)

Close closes current connection.

func (*TCPClientProvider) Connect

func (sf *TCPClientProvider) 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 (TCPClientProvider) Debugf

func (sf TCPClientProvider) Debugf(format string, v ...interface{})

Debug Log DEBUG level message.

func (TCPClientProvider) Errorf

func (sf TCPClientProvider) Errorf(format string, v ...interface{})

Error Log ERROR level message.

func (*TCPClientProvider) IsConnected

func (sf *TCPClientProvider) IsConnected() bool

IsConnected returns a bool signifying whether the client is connected or not.

func (*TCPClientProvider) LogMode

func (sf *TCPClientProvider) LogMode(enable bool)

LogMode set enable or disable log output when you has set logger.

func (*TCPClientProvider) Send

func (sf *TCPClientProvider) Send(slaveID byte, request ProtocolDataUnit) (ProtocolDataUnit, error)

Send the request to tcp and get the response

func (*TCPClientProvider) SendPdu

func (sf *TCPClientProvider) SendPdu(slaveID byte, pduRequest []byte) ([]byte, error)

SendPdu send pdu request to the remote server

func (*TCPClientProvider) SendRawFrame

func (sf *TCPClientProvider) SendRawFrame(aduRequest []byte) (aduResponse []byte, err error)

SendRawFrame send raw adu request frame

type TCPServer

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

TCPServer modbus tcp server

func NewTCPServer

func NewTCPServer() *TCPServer

NewTCPServer the modbus server listening on "address:port".

func (TCPServer) AddNodes

func (sf TCPServer) AddNodes(nodes ...*NodeRegister)

AddNodes 增加节点.

func (*TCPServer) Close

func (sf *TCPServer) Close() error

Close close the server until all server close then return

func (TCPServer) Debugf

func (sf TCPServer) Debugf(format string, v ...interface{})

Debug Log DEBUG level message.

func (TCPServer) DeleteAllNode

func (sf TCPServer) DeleteAllNode()

DeleteAllNode 删除所有节点.

func (TCPServer) DeleteNode

func (sf TCPServer) DeleteNode(slaveID byte)

DeleteNode 删除一个节点.

func (TCPServer) Errorf

func (sf TCPServer) Errorf(format string, v ...interface{})

Error Log ERROR level message.

func (TCPServer) GetNode

func (sf TCPServer) GetNode(slaveID byte) (*NodeRegister, error)

GetNode 获取一个节点.

func (TCPServer) GetNodeList

func (sf TCPServer) GetNodeList() []*NodeRegister

GetNodeList 获取节点列表.

func (*TCPServer) ListenAndServe

func (sf *TCPServer) ListenAndServe(addr string) error

ListenAndServe listen and server

func (*TCPServer) LogMode

func (sf *TCPServer) LogMode(enable bool)

LogMode set enable or disable log output when you has set logger.

func (TCPServer) Range

func (sf TCPServer) Range(f func(slaveID byte, node *NodeRegister) bool)

Range 扫描节点 same as sync map range.

func (TCPServer) RegisterFunctionHandler

func (sf TCPServer) RegisterFunctionHandler(funcCode uint8, function FunctionHandler)

RegisterFunctionHandler 注册回调函数.

func (*TCPServer) SetReadTimeout

func (sf *TCPServer) SetReadTimeout(t time.Duration) *TCPServer

SetReadTimeout set read timeout

func (*TCPServer) SetWriteTimeout

func (sf *TCPServer) SetWriteTimeout(t time.Duration) *TCPServer

SetWriteTimeout set write timeout

type TCPServerSpecial

type TCPServerSpecial struct {
	ServerSession

	TLSConfig *tls.Config
	// contains filtered or unexported fields
}

TCPServerSpecial modbus tcp server special

func NewTCPServerSpecial

func NewTCPServerSpecial() *TCPServerSpecial

NewTCPServerSpecial new tcp server special, default enable auto reconnect

func (TCPServerSpecial) AddNodes

func (sf TCPServerSpecial) AddNodes(nodes ...*NodeRegister)

AddNodes 增加节点.

func (*TCPServerSpecial) AddRemoteServer

func (sf *TCPServerSpecial) AddRemoteServer(server string) error

AddRemoteServer adds a broker URI to the list of brokers to be used. The format should be scheme://host:port Default values for hostname is "127.0.0.1", for schema is "tcp://". An example broker URI would look like: tcp://foobar.com:502

func (*TCPServerSpecial) Close

func (sf *TCPServerSpecial) Close() error

Close close the server

func (TCPServerSpecial) Debugf

func (sf TCPServerSpecial) Debugf(format string, v ...interface{})

Debug Log DEBUG level message.

func (TCPServerSpecial) DeleteAllNode

func (sf TCPServerSpecial) DeleteAllNode()

DeleteAllNode 删除所有节点.

func (TCPServerSpecial) DeleteNode

func (sf TCPServerSpecial) DeleteNode(slaveID byte)

DeleteNode 删除一个节点.

func (*TCPServerSpecial) EnableAutoReconnect

func (sf *TCPServerSpecial) EnableAutoReconnect(b bool) *TCPServerSpecial

EnableAutoReconnect enable auto reconnect

func (TCPServerSpecial) Errorf

func (sf TCPServerSpecial) Errorf(format string, v ...interface{})

Error Log ERROR level message.

func (TCPServerSpecial) GetNode

func (sf TCPServerSpecial) GetNode(slaveID byte) (*NodeRegister, error)

GetNode 获取一个节点.

func (TCPServerSpecial) GetNodeList

func (sf TCPServerSpecial) GetNodeList() []*NodeRegister

GetNodeList 获取节点列表.

func (*TCPServerSpecial) IsClosed

func (sf *TCPServerSpecial) IsClosed() bool

IsClosed check server is closed

func (*TCPServerSpecial) IsConnected

func (sf *TCPServerSpecial) IsConnected() bool

IsConnected check connect is online

func (*TCPServerSpecial) LogMode

func (sf *TCPServerSpecial) LogMode(enable bool)

LogMode set enable or disable log output when you has set logger.

func (TCPServerSpecial) Range

func (sf TCPServerSpecial) Range(f func(slaveID byte, node *NodeRegister) bool)

Range 扫描节点 same as sync map range.

func (TCPServerSpecial) RegisterFunctionHandler

func (sf TCPServerSpecial) RegisterFunctionHandler(funcCode uint8, function FunctionHandler)

RegisterFunctionHandler 注册回调函数.

func (*TCPServerSpecial) SetConnectTimeout

func (sf *TCPServerSpecial) SetConnectTimeout(t time.Duration) *TCPServerSpecial

SetConnectTimeout set tcp connect the host timeout

func (*TCPServerSpecial) SetConnectionLostHandler

func (sf *TCPServerSpecial) SetConnectionLostHandler(f OnConnectionLostHandler) *TCPServerSpecial

SetConnectionLostHandler set connection lost handler

func (*TCPServerSpecial) SetKeepAlive

func (sf *TCPServerSpecial) SetKeepAlive(enable bool, t time.Duration, f OnKeepAliveHandler) *TCPServerSpecial

SetKeepAlive set keep alive enable, alive time and handler

func (*TCPServerSpecial) SetOnConnectHandler

func (sf *TCPServerSpecial) SetOnConnectHandler(f OnConnectHandler) *TCPServerSpecial

SetOnConnectHandler set on connect handler

func (*TCPServerSpecial) SetReadTimeout

func (sf *TCPServerSpecial) SetReadTimeout(t time.Duration) *TCPServerSpecial

SetReadTimeout set read timeout

func (*TCPServerSpecial) SetReconnectInterval

func (sf *TCPServerSpecial) SetReconnectInterval(t time.Duration) *TCPServerSpecial

SetReconnectInterval set tcp reconnect the host interval when connect failed after try

func (*TCPServerSpecial) SetTLSConfig

func (sf *TCPServerSpecial) SetTLSConfig(t *tls.Config) *TCPServerSpecial

SetTLSConfig set tls config

func (*TCPServerSpecial) SetWriteTimeout

func (sf *TCPServerSpecial) SetWriteTimeout(t time.Duration) *TCPServerSpecial

SetWriteTimeout set write timeout

func (*TCPServerSpecial) Start

func (sf *TCPServerSpecial) Start() error

Start start the server,and return quickly,if it nil,the server will connecting background,other failed

func (*TCPServerSpecial) UnderlyingConn

func (sf *TCPServerSpecial) UnderlyingConn() net.Conn

UnderlyingConn got underlying tcp conn

Jump to

Keyboard shortcuts

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