gos7

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2026 License: BSD-3-Clause Imports: 12 Imported by: 0

README

gos7

Implementation of Siemens S7 protocol in golang

Overview

For years, numerous drivers/connectors, available in both commercial and open source domains, have supported the connection to S7 family PLC devices. GoS7 fills the gaps in the S7 protocol, implementing it with pure Go (also known as golang). There is a strong belief that low-level communication should be implemented with a low-level programming language that is close to binary and memory.

The minimum supported Go version is 1.13.

Functions

AG:

  • Read/Write Data Block (DB) (tested)
  • Read/Write Merkers(MB) (tested)
  • Read/Write IPI (EB) (tested)
  • Read/Write IPU (AB) (tested)
  • Read/Write Timer (TM) (tested)
  • Read/Write Counter (CT) (tested)
  • Multiple Read/Write Area (tested)
  • Batch Read/Write Areas (ReadAreas/WriteAreas) (tested)
  • Get Block Info (tested)

PG:

  • Hot start/Cold start / Stop PLC
  • Get CPU of PLC status (tested)
  • List available blocks in PLC (tested)
  • Set/Clear password for session
  • Get CPU protection and CPU Order code
  • Get CPU/CP Information (tested)
  • Read/Write clock for the PLC Helpers:
  • Get/set value for a byte array for types: value(bit/int/word/dword/uint...), real, time, counter

Supported communication

  • TCP
  • Serial (PPI, MPI) (under construction)

How to:

following is a simple usage to connect with PLC via TCP

const (
	tcpDevice = "127.0.0.1"
	rack      = 0
	slot      = 2
)
// TCPClient
handler := gos7.NewTCPClientHandler(tcpDevice, rack, slot)
handler.Timeout = 200 * time.Second
handler.IdleTimeout = 200 * time.Second
handler.Logger = log.New(os.Stdout, "tcp: ", log.LstdFlags)
// Connect manually so that multiple requests are handled in one connection session
handler.Connect()
defer handler.Close()
//init client
client := gos7.NewClient(handler)
address := 2710
start := 8
size := 2
buffer := make([]byte, 255)
value := 100
//AGWriteDB to address DB2710 with value 100, start from position 8 with size = 2 (for an integer)
var helper gos7.Helper
helper.SetValueAt(buffer, 0, value)  
err := client.AGWriteDB(address, start, size, buffer)
buf := make([]byte, 255)
//AGReadDB to address DB2710, start from position 8 with size = 2
err := client.AGReadDB(address, start, size, buf)
var s7 gos7.Helper
var result uint16
s7.GetValueAt(buf, 0, &result)	 

Batch Operations:

Batch operations allow reading/writing multiple areas in a single request, significantly improving performance by reducing network round trips.

// Batch read multiple data blocks
items := []gos7.S7DataItem{
    {Area: gos7.S7AreaDB, DBNumber: 1, Start: 0, Amount: 10, WordLen: gos7.S7WLByte, Data: make([]byte, 10)},
    {Area: gos7.S7AreaDB, DBNumber: 2, Start: 5, Amount: 20, WordLen: gos7.S7WLByte, Data: make([]byte, 20)},
    {Area: gos7.S7AreaMK, Start: 100, Amount: 8, WordLen: gos7.S7WLByte, Data: make([]byte, 8)},
}
err := client.ReadAreas(items)
// Data is now available in each item's Data field

// Batch write multiple data blocks
writeItems := []gos7.S7DataItem{
    {Area: gos7.S7AreaDB, DBNumber: 1, Start: 0, Amount: 10, WordLen: gos7.S7WLByte, Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}},
    {Area: gos7.S7AreaDB, DBNumber: 2, Start: 5, Amount: 4, WordLen: gos7.S7WLWord, Data: []byte{0x12, 0x34, 0x56, 0x78}},
}
err := client.WriteAreas(writeItems)

References

Simatic, Simatic S5, Simatic S7, S7-200, S7-300, S7-400, S7-1200, S7-1500 are registered Trademarks of Siemens

License

https://opensource.org/licenses/BSD-3-Clause

Copyright (c) 2018, robinson

Documentation

Index

Constants

View Source
const (
	// Area ID (exported) - 区域标识符
	S7AreaPE = s7areape // Process Inputs / 过程输入区 (I)
	S7AreaPA = s7areapa // Process Outputs / 过程输出区 (Q)
	S7AreaMK = s7areamk // Merkers / 标志位区 (M)
	S7AreaDB = s7areadb // Data Block / 数据块 (DB)
	S7AreaCT = s7areact // Counters / 计数器区 (C)
	S7AreaTM = s7areatm // Timers / 定时器区 (T)

	// Word Length (exported) - 数据类型长度
	S7WLBit     = s7wlbit     // Bit (inside a word) / 位
	S7WLByte    = s7wlbyte    // Byte (8 bit) / 字节
	S7WLChar    = s7wlChar    // Char / 字符
	S7WLWord    = s7wlword    // Word (16 bit) / 字
	S7WLInt     = s7wlint     // Int / 整数
	S7WLDWord   = s7wldword   // Double Word (32 bit) / 双字
	S7WLDInt    = s7wldint    // DInt / 双整数
	S7WLReal    = s7wlreal    // Real (32 bit float) / 浮点数
	S7WLCounter = s7wlcounter // Counter (16 bit) / 计数器
	S7WLTimer   = s7wltimer   // Timer (16 bit) / 定时器

	// PLC Status (exported) - PLC状态
	S7CpuStatusUnknown = s7CpuStatusUnknown // Unknown / 未知
	S7CpuStatusRun     = s7CpuStatusRun     // Running / 运行中
	S7CpuStatusStop    = s7CpuStatusStop    // Stopped / 停止

)

Exported area and word length constants for S7DataItem usage

Variables

This section is empty.

Functions

func CPUError

func CPUError(err uint) int

CPUError specific CPU error after response

func ErrorText

func ErrorText(err int) string

ErrorText return a string error text from error code integer

Types

type Client

type Client interface {
	/*************** AG API (Automatisationsgerät / Automation Device) ***************/
	// AGReadDB reads data block from PLC
	// AGReadDB 从PLC读取数据块
	AGReadDB(dbNumber int, start int, size int, buffer []byte) (err error)

	// AGWriteDB writes data block to PLC
	// AGWriteDB 向PLC写入数据块
	AGWriteDB(dbNumber int, start int, size int, buffer []byte) (err error)

	// AGReadMB reads Merkers (Memory Bits) from PLC
	// AGReadMB 从PLC读取标志位
	AGReadMB(start int, size int, buffer []byte) (err error)

	// AGWriteMB writes Merkers (Memory Bits) to PLC
	// AGWriteMB 向PLC写入标志位
	AGWriteMB(start int, size int, buffer []byte) (err error)

	// AGReadEB reads Process Inputs (E) from PLC
	// AGReadEB 从PLC读取输入过程映像
	AGReadEB(start int, size int, buffer []byte) (err error)

	// AGWriteEB writes Process Inputs (E) to PLC
	// AGWriteEB 向PLC写入输入过程映像
	AGWriteEB(start int, size int, buffer []byte) (err error)

	// AGReadAB reads Process Outputs (A) from PLC
	// AGReadAB 从PLC读取输出过程映像
	AGReadAB(start int, size int, buffer []byte) (err error)

	// AGWriteAB writes Process Outputs (A) to PLC
	// AGWriteAB 向PLC写入输出过程映像
	AGWriteAB(start int, size int, buffer []byte) (err error)

	// AGReadTM reads Timer values from PLC
	// AGReadTM 从PLC读取定时器值
	AGReadTM(start int, size int, buffer []byte) (err error)

	// AGWriteTM writes Timer values to PLC
	// AGWriteTM 向PLC写入定时器值
	AGWriteTM(start int, size int, buffer []byte) (err error)

	// AGReadCT reads Counter values from PLC
	// AGReadCT 从PLC读取计数器值
	AGReadCT(start int, size int, buffer []byte) (err error)

	// AGWriteCT writes Counter values to PLC
	// AGWriteCT 向PLC写入计数器值
	AGWriteCT(start int, size int, buffer []byte) (err error)

	// AGReadMulti reads multiple data items in a single request
	// AGReadMulti 在单个请求中读取多个数据项
	AGReadMulti(dataItems []S7DataItem, itemsCount int) (err error)

	// AGWriteMulti writes multiple data items in a single request
	// AGWriteMulti 在单个请求中写入多个数据项
	AGWriteMulti(dataItems []S7DataItem, itemsCount int) (err error)

	// DBFill fills a data block with a specific byte value
	// DBFill 使用指定字节值填充数据块
	DBFill(dbnumber int, fillchar int) error

	// DBGet reads an entire data block
	// DBGet 读取整个数据块
	DBGet(dbnumber int, usrdata []byte, size int) error

	// Read reads a variable using S7 syntax (e.g., "DB1.DBB0", "MB10")
	// Read 使用S7语法读取变量(例如 "DB1.DBB0", "MB10")
	Read(variable string, buffer []byte) (value any, err error)

	// GetAgBlockInfo retrieves block information from AG area
	// GetAgBlockInfo 从AG区域获取块信息
	GetAgBlockInfo(blocktype int, blocknum int) (info S7BlockInfo, err error)

	/*************** PG API (Programmiergerät / Programming Device) ***************/
	// PLCHotStart performs a hot start on the PLC CPU
	// PLCHotStart 对PLC CPU执行热启动
	PLCHotStart() error

	// PLCColdStart performs a cold start on the PLC CPU
	// PLCColdStart 对PLC CPU执行冷启动
	PLCColdStart() error

	// PLCStop stops the PLC CPU
	// PLCStop 停止PLC CPU
	PLCStop() error

	// PLCGetStatus returns the CPU status (running/stopped)
	// PLCGetStatus 返回CPU状态(运行/停止)
	PLCGetStatus() (status int, err error)

	// PGListBlocks lists all blocks in PLC
	// PGListBlocks 列出PLC中所有块
	PGListBlocks() (list S7BlocksList, err error)

	// SetSessionPassword sets the session password for PLC
	// SetSessionPassword 设置PLC会话密码
	SetSessionPassword(password string) error

	// ClearSessionPassword clears the session password
	// ClearSessionPassword 清除会话密码
	ClearSessionPassword() error

	// GetProtection returns CPU protection level information
	// GetProtection 返回CPU保护级别信息
	GetProtection() (protection S7Protection, err error)

	// GetOrderCode returns CPU order code information
	// GetOrderCode 返回CPU订货号信息
	GetOrderCode() (info S7OrderCode, err error)

	// GetCPUInfo returns CPU information
	// GetCPUInfo 返回CPU信息
	GetCPUInfo() (info S7CpuInfo, err error)

	// GetCPInfo returns CP (Communication Processor) information
	// GetCPInfo 返回CP(通信处理器)信息
	GetCPInfo() (info S7CpInfo, err error)

	// PGClockRead reads the PLC clock
	// PGClockRead 读取PLC时钟
	PGClockRead(datetime time.Time) error

	// PGClockWrite writes to the PLC clock
	// PGClockWrite 写入PLC时钟
	PGClockWrite() (dt time.Time, err error)

	/*************** Generic Area Operations ***************/
	// WriteArea writes to a generic memory area
	// WriteArea 向通用内存区域写入数据
	WriteArea(area int, dbnumber int, start int, amount int, wordlen int, buffer []byte) (err error)

	// ReadArea reads from a generic memory area
	// ReadArea 从通用内存区域读取数据
	ReadArea(area int, dbNumber int, start int, amount int, wordLen int, buffer []byte) (err error)

	// ReadAreas batch reads multiple data items with automatic batching
	// ReadAreas 批量读取多个数据项(自动分批处理)
	ReadAreas(items []S7DataItem) (err error)

	// WriteAreas batch writes multiple data items with automatic batching
	// WriteAreas 批量写入多个数据项(自动分批处理)
	WriteAreas(items []S7DataItem) (err error)
}

Client is the main interface for S7 PLC communication Client 是S7 PLC通信的主接口 It provides methods for reading/writing data from/to PLC memory areas, as well as PLC control and system information functions. 它提供了从PLC内存区域读写数据的方法,以及PLC控制和系统信息功能。

func NewClient

func NewClient(handler ClientHandler) Client

NewClient creates a new S7 client with given backend handler. NewClient 创建一个新的 S7 客户端,使用给定的后端处理器

func NewClient2

func NewClient2(packager Packager, transporter Transporter) Client

NewClient2 creates a new S7 client with separate packager and transporter. NewClient2 创建一个新的 S7 客户端,使用独立的 packager 和 transporter

func TCPClient

func TCPClient(address string, rack int, slot int) Client

TCPClient creator for a TCP client with address, rack and slot, implement from interface client

func TCPClientWithConnectType

func TCPClientWithConnectType(address string, rack int, slot int, connectType int) Client

TCPClientWithConnectType creator for a TCP client with address, rack, slot and connect type, implement from interface client

type ClientHandler

type ClientHandler interface {
	Packager
	Transporter
}

ClientHandler is the interface that groups the Packager and Transporter methods. ClientHandler 接口组合了 Packager 和 Transporter 方法

type Helper

type Helper struct{}

Helper the helper to get/set value from/to byte array with difference types

func (*Helper) GetBoolAt

func (s7 *Helper) GetBoolAt(b byte, pos uint) bool

GetBoolAt gets a boolean (bit) from a byte at position

func (*Helper) GetCharsAt

func (s7 *Helper) GetCharsAt(buffer []byte, pos int, Size int) string

GetCharsAt Get Array of char (S7 ARRAY OF CHARS)

func (*Helper) GetCounter

func (s7 *Helper) GetCounter(value uint16) int

GetCounter Get S7 Counter

func (*Helper) GetCounterAt

func (s7 *Helper) GetCounterAt(buffer []uint16, index int) int

GetCounterAt Get S7 Counter at a index

func (*Helper) GetDTLAt

func (s7 *Helper) GetDTLAt(buffer []byte, pos int) time.Time

GetDTLAt DTL (S71200/1500 Date and Time)

func (*Helper) GetDateAt

func (s7 *Helper) GetDateAt(buffer []byte, pos int) time.Time

GetDateAt DATE (S7 DATE)

func (*Helper) GetDateTimeAt

func (s7 *Helper) GetDateTimeAt(Buffer []byte, Pos int) time.Time

GetDateTimeAt DateTime (S7 DATE_AND_TIME)

func (*Helper) GetLDTAt

func (s7 *Helper) GetLDTAt(buffer []byte, pos int) time.Time

GetLDTAt LDT (S7 1500 Long Date and Time)

func (*Helper) GetLRealAt

func (s7 *Helper) GetLRealAt(buffer []byte, pos int) float64

GetLRealAt 64 bit floating point number (S7 LReal) (Range of float64)

func (*Helper) GetLTODAt

func (s7 *Helper) GetLTODAt(Buffer []byte, Pos int) time.Time

GetLTODAt LTOD (S7 1500 LONG TIME_OF_DAY)

func (*Helper) GetRealAt

func (s7 *Helper) GetRealAt(buffer []byte, pos int) float32

GetRealAt 32 bit floating point number (S7 Real) (Range of float32)

func (*Helper) GetS5TimeAt

func (s7 *Helper) GetS5TimeAt(buffer []byte, pos int) time.Duration

Get S5Time

func (*Helper) GetStringAt

func (s7 *Helper) GetStringAt(buffer []byte, pos int) string

GetStringAt Get String

func (*Helper) GetTODAt

func (s7 *Helper) GetTODAt(buffer []byte, pos int) time.Time

GetTODAt TOD (S7 TIME_OF_DAY)

func (*Helper) GetValueAt

func (s7 *Helper) GetValueAt(buffer []byte, pos int, value any)

GetValueAt set a value at a position of a byte array, which based on builtin function: https://golang.org/pkg/encoding/binary/#Write Optimized: uses direct byte operations for common types to avoid bytes.Reader allocation.

func (*Helper) GetWStringAt

func (s7 *Helper) GetWStringAt(buffer []byte, pos int) string

GetWStringAt Get WString

func (*Helper) SetBoolAt

func (s7 *Helper) SetBoolAt(b byte, bitPos uint, data bool) byte

SetBoolAt sets a boolean (bit) within a byte at bit position without changing the other bits it returns the resulted byte

func (*Helper) SetCharsAt

func (s7 *Helper) SetCharsAt(buffer []byte, pos int, value string)

SetCharsAt Get Array of char (S7 ARRAY OF CHARS)

func (*Helper) SetCounterAt

func (s7 *Helper) SetCounterAt(buffer []uint16, pos int, value int) []uint16

SetCounterAt set a counter at a postion

func (*Helper) SetDTLAt

func (s7 *Helper) SetDTLAt(buffer []byte, pos int, value time.Time) []byte

SetDTLAt DTL (S71200/1500 Date and Time)

func (*Helper) SetDateAt

func (s7 *Helper) SetDateAt(buffer []byte, pos int, value time.Time)

SetDateAt DATE (S7 DATE)

func (*Helper) SetDateTimeAt

func (s7 *Helper) SetDateTimeAt(buffer []byte, pos int, value time.Time)

SetDateTimeAt DateTime (S7 DATE_AND_TIME)

func (*Helper) SetLDTAt

func (s7 *Helper) SetLDTAt(buffer []byte, pos int, value time.Time)

SetLDTAt LDT (S7 1500 Long Date and Time)

func (*Helper) SetLRealAt

func (s7 *Helper) SetLRealAt(Buffer []byte, Pos int, Value float64)

SetLRealAt 64 bit floating point number (S7 LReal) (Range of float64)

func (*Helper) SetLTODAt

func (s7 *Helper) SetLTODAt(buffer []byte, pos int, value time.Time)

SetLTODAt LTOD (S7 1500 LONG TIME_OF_DAY)

func (*Helper) SetRealAt

func (s7 *Helper) SetRealAt(buffer []byte, pos int, value float32)

SetRealAt 32 bit floating point number (S7 Real) (Range of float32)

func (*Helper) SetS5TimeAt

func (s7 *Helper) SetS5TimeAt(buffer []byte, pos int, value time.Duration) []byte

SetS5TimeAt Set S5Time

func (*Helper) SetStringAt

func (s7 *Helper) SetStringAt(buffer []byte, pos int, maxLen int, value string) []byte

SetStringAt Set String (S7 String)

func (*Helper) SetTODAt

func (s7 *Helper) SetTODAt(buffer []byte, pos int, value time.Time)

SetTODAt TOD (S7 TIME_OF_DAY)

func (*Helper) SetValueAt

func (s7 *Helper) SetValueAt(buffer []byte, pos int, data any)

SetValueAt set a value at a position of a byte array, which based on builtin function: https://golang.org/pkg/encoding/binary/#Read Optimized: uses direct byte operations for common types to avoid bytes.Buffer allocation.

func (*Helper) SetWStringAt

func (s7 *Helper) SetWStringAt(buffer []byte, pos int, maxLen int, value string) []byte

SetWStringAt Set String (WString)

func (*Helper) ToCounter

func (s7 *Helper) ToCounter(value int) uint16

ToCounter convert value to s7

type MockClientHandler

type MockClientHandler struct {
	PDULength int
	// contains filtered or unexported fields
}

MockClientHandler implements both Packager and Transporter interfaces to simulate a PLC connection without requiring actual hardware. It maintains an in-memory data store that responds to S7 protocol requests.

MockClientHandler 实现了 Packager 和 Transporter 接口, 用于在没有真实 PLC 硬件的情况下模拟 PLC 连接。 它维护一个内存数据存储,用于响应 S7 协议请求。

func NewMockClientHandler

func NewMockClientHandler() *MockClientHandler

NewMockClientHandler creates a new mock PLC handler with default PDU length. NewMockClientHandler 创建一个新的模拟 PLC 处理器,使用默认 PDU 长度。

func (*MockClientHandler) GetPDULength

func (m *MockClientHandler) GetPDULength() int

GetPDULength implements the PDUProvider interface

func (*MockClientHandler) Send

func (m *MockClientHandler) Send(request []byte) (response []byte, err error)

Send implements the Transporter interface. It parses the S7 request telegram and returns a properly formatted response.

func (*MockClientHandler) Verify

func (m *MockClientHandler) Verify(request []byte, response []byte) error

Verify implements the Packager interface

type PDUProvider

type PDUProvider interface {
	GetPDULength() int
}

PDUProvider is an optional interface that provides the negotiated PDU length. Implementations that are not *TCPClientHandler should implement this interface to allow the client to determine PDU boundaries.

PDUProvider 是一个可选接口,提供协商后的 PDU 长度。 非 *TCPClientHandler 的实现应实现此接口,以允许客户端确定 PDU 边界。

type Packager

type Packager interface {
	//reserve for future use
	Verify(request []byte, response []byte) (err error)
}

Packager specifies the communication layer.

type ProtocolDataUnit

type ProtocolDataUnit struct {
	Data []byte
}

ProtocolDataUnit (PDU) is independent of underlying communication layers.

func NewProtocolDataUnit

func NewProtocolDataUnit(data []byte) ProtocolDataUnit

NewProtocolDataUnit ProtocolDataUnit Constructor

type S7BlockInfo

type S7BlockInfo struct {
	BlkType   int
	BlkNumber int
	BlkLang   int
	BlkFlags  int
	MC7Size   int // The real size in bytes
	LoadSize  int
	LocalData int
	SBBLength int
	CheckSum  int
	Version   int
	// Chars info
	CodeDate string
	IntfDate string
	Author   string
	Family   string
	Header   string
}

S7BlockInfo Managed Block Info

type S7BlocksList

type S7BlocksList struct {
	OBList  []int
	FBList  []int
	FCList  []int
	SFBList []int
	SFCList []int
	DBList  []int
	SDBList []int
}

S7BlocksList Block List

type S7CpInfo

type S7CpInfo struct {
	MaxPduLength   int
	MaxConnections int
	MaxMpiRate     int
	MaxBusRate     int
}

S7CpInfo cp info

type S7CpuInfo

type S7CpuInfo struct {
	ModuleTypeName string
	SerialNumber   string
	ASName         string
	Copyright      string
	ModuleName     string
}

S7CpuInfo CPU Info

type S7DataItem

type S7DataItem struct {
	Area     int
	WordLen  int
	DBNumber int
	Start    int
	Bit      int
	Amount   int
	Data     []byte
	Error    string
}

S7DataItem represents a single data item for multiple read/write operations S7DataItem 表示多读写操作中的单个数据项 Fields:

Area - Memory area type (s7areadb/s7areamk/s7areape/s7areapa/s7areact/s7areatm)
Area - 内存区域类型
WordLen - Data type (s7wlbit/s7wlbyte/s7wlword/s7wldword/s7wlreal/s7wlcounter/s7wltimer)
WordLen - 数据类型
DBNumber - Data block number (only for DB area)
DBNumber - 数据块编号(仅用于DB区域)
Start - Start address within the area
Start - 区域内的起始地址
Bit - Bit position (only for bit operations)
Bit - 位位置(仅用于位操作)
Amount - Number of elements to read/write
Amount - 要读写的元素数量
Data - Data buffer for input/output
Data - 输入/输出数据缓冲区
Error - Error message if operation fails
Error - 操作失败时的错误信息

type S7Error

type S7Error struct {
	High byte
	Low  byte
}

S7Error implements error interface.

func (*S7Error) Error

func (e *S7Error) Error() string

Error converts known s7 exception code to error message.

type S7OrderCode

type S7OrderCode struct {
	Code string // such as "6ES7 151-8AB01-0AB0"
	V1   byte   // Version 1st digit
	V2   byte   // Version 2nd digit
	V3   byte   // Version 3th digit
}

S7OrderCode Order Code + Version

type S7Protection

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

S7Protection See §33.19 of "System Software for S7-300/400 System and Standard Functions"

type S7SZL

type S7SZL struct {
	Header SZLHeader
	Data   []byte
}

S7SZL constains header and data

type S7SZLList

type S7SZLList struct {
	Header SZLHeader
	Data   []uint16
}

S7SZLList of available SZL IDs : same as SZL but List items are big-endian adjusted

type SZLHeader

type SZLHeader struct {
	LengthHeader       uint16
	NumberOfDataRecord uint16
}

SZLHeader See §33.1 of "System Software for S7-300/400 System and Standard Functions" and see SFC51 description too

type TCPClientHandler

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

TCPClientHandler implements Packager and Transporter interface.

func NewTCPClientHandler

func NewTCPClientHandler(address string, rack int, slot int) *TCPClientHandler

NewTCPClientHandler allocates a new TCPClientHandler.

func NewTCPClientHandlerWithConnectType

func NewTCPClientHandlerWithConnectType(address string, rack int, slot int, connectType int) *TCPClientHandler

NewTCPClientHandlerWithConnectType allocates a new TCPClientHandler with connection type.

func (*TCPClientHandler) Close

func (mb *TCPClientHandler) Close() error

Close closes the current connection with graceful handling of TCP half-close state. If CloseTimeout > 0 (default is 5 seconds), it will wait up to that duration for the peer to close their side. If the peer does not close within the timeout, the connection will be forcefully closed.

For immediate forceful close without waiting, use CloseForce().

func (*TCPClientHandler) CloseForce added in v0.0.3

func (mb *TCPClientHandler) CloseForce() error

CloseForce closes the connection immediately without waiting for the peer to close. This bypasses graceful shutdown and forcibly terminates the connection. Use this when immediate termination is required, such as during emergency shutdown. Unlike Close(), this method ignores CloseTimeout and does not wait for peer acknowledgment.

func (*TCPClientHandler) Connect

func (h *TCPClientHandler) Connect() error

Connect establishes a new connection to the PLC. Connect 建立到 PLC 的新连接

func (*TCPClientHandler) ConnectContext

func (h *TCPClientHandler) ConnectContext(ctx context.Context) error

ConnectContext establishes a new connection with context support for cancellation. This allows callers to cancel in-flight TCP dials via context (e.g., during graceful shutdown). ConnectContext 建立一个新连接,支持通过 context 进行取消操作 这允许调用者通过 context 取消正在进行的 TCP 连接(例如在优雅关闭期间)

func (*TCPClientHandler) GetPDULength

func (h *TCPClientHandler) GetPDULength() int

GetPDULength implements the PDUProvider interface GetPDULength 实现 PDUProvider 接口

func (*TCPClientHandler) IsClosed added in v0.0.3

func (mb *TCPClientHandler) IsClosed() bool

IsClosed returns true if the connection is fully closed.

func (*TCPClientHandler) IsHalfClosed added in v0.0.3

func (mb *TCPClientHandler) IsHalfClosed() bool

IsHalfClosed returns true if the connection is in half-closed state. A half-closed connection has had its write side closed (FIN sent) but may still receive data from the peer.

func (*TCPClientHandler) LocalAddr

func (h *TCPClientHandler) LocalAddr() string

func (*TCPClientHandler) Send

func (mb *TCPClientHandler) Send(request []byte) (response []byte, err error)

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

func (*TCPClientHandler) SendWithContext

func (mb *TCPClientHandler) SendWithContext(ctx context.Context, request []byte) (response []byte, err error)

SendWithContext sends data to server with context support for cancellation. SendWithContext 发送数据到服务器,支持通过 context 进行取消操作

func (*TCPClientHandler) State added in v0.0.3

func (mb *TCPClientHandler) State() closeState

State returns the current close state of the connection.

func (*TCPClientHandler) Verify

func (mb *TCPClientHandler) Verify(request []byte, response []byte) (err error)

reserve for future use, need to verify the request and response

type Transporter

type Transporter interface {
	Send(request []byte) (response []byte, err error)
}

Transporter specifies the transport layer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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