Documentation
¶
Index ¶
- Constants
- func CPUError(err uint) int
- func ErrorText(err int) string
- type Client
- type ClientHandler
- type Helper
- func (s7 *Helper) GetBoolAt(b byte, pos uint) bool
- func (s7 *Helper) GetCharsAt(buffer []byte, pos int, Size int) string
- func (s7 *Helper) GetCounter(value uint16) int
- func (s7 *Helper) GetCounterAt(buffer []uint16, index int) int
- func (s7 *Helper) GetDTLAt(buffer []byte, pos int) time.Time
- func (s7 *Helper) GetDateAt(buffer []byte, pos int) time.Time
- func (s7 *Helper) GetDateTimeAt(Buffer []byte, Pos int) time.Time
- func (s7 *Helper) GetLDTAt(buffer []byte, pos int) time.Time
- func (s7 *Helper) GetLRealAt(buffer []byte, pos int) float64
- func (s7 *Helper) GetLTODAt(Buffer []byte, Pos int) time.Time
- func (s7 *Helper) GetRealAt(buffer []byte, pos int) float32
- func (s7 *Helper) GetS5TimeAt(buffer []byte, pos int) time.Duration
- func (s7 *Helper) GetStringAt(buffer []byte, pos int) string
- func (s7 *Helper) GetTODAt(buffer []byte, pos int) time.Time
- func (s7 *Helper) GetValueAt(buffer []byte, pos int, value any)
- func (s7 *Helper) GetWStringAt(buffer []byte, pos int) string
- func (s7 *Helper) SetBoolAt(b byte, bitPos uint, data bool) byte
- func (s7 *Helper) SetCharsAt(buffer []byte, pos int, value string)
- func (s7 *Helper) SetCounterAt(buffer []uint16, pos int, value int) []uint16
- func (s7 *Helper) SetDTLAt(buffer []byte, pos int, value time.Time) []byte
- func (s7 *Helper) SetDateAt(buffer []byte, pos int, value time.Time)
- func (s7 *Helper) SetDateTimeAt(buffer []byte, pos int, value time.Time)
- func (s7 *Helper) SetLDTAt(buffer []byte, pos int, value time.Time)
- func (s7 *Helper) SetLRealAt(Buffer []byte, Pos int, Value float64)
- func (s7 *Helper) SetLTODAt(buffer []byte, pos int, value time.Time)
- func (s7 *Helper) SetRealAt(buffer []byte, pos int, value float32)
- func (s7 *Helper) SetS5TimeAt(buffer []byte, pos int, value time.Duration) []byte
- func (s7 *Helper) SetStringAt(buffer []byte, pos int, maxLen int, value string) []byte
- func (s7 *Helper) SetTODAt(buffer []byte, pos int, value time.Time)
- func (s7 *Helper) SetValueAt(buffer []byte, pos int, data any)
- func (s7 *Helper) SetWStringAt(buffer []byte, pos int, maxLen int, value string) []byte
- func (s7 *Helper) ToCounter(value int) uint16
- type MockClientHandler
- type PDUProvider
- type Packager
- type ProtocolDataUnit
- type S7BlockInfo
- type S7BlocksList
- type S7CpInfo
- type S7CpuInfo
- type S7DataItem
- type S7Error
- type S7OrderCode
- type S7Protection
- type S7SZL
- type S7SZLList
- type SZLHeader
- type TCPClientHandler
- func (mb *TCPClientHandler) Close() error
- func (mb *TCPClientHandler) CloseForce() error
- func (h *TCPClientHandler) Connect() error
- func (h *TCPClientHandler) ConnectContext(ctx context.Context) error
- func (h *TCPClientHandler) GetPDULength() int
- func (mb *TCPClientHandler) IsClosed() bool
- func (mb *TCPClientHandler) IsHalfClosed() bool
- func (h *TCPClientHandler) LocalAddr() string
- func (mb *TCPClientHandler) Send(request []byte) (response []byte, err error)
- func (mb *TCPClientHandler) SendWithContext(ctx context.Context, request []byte) (response []byte, err error)
- func (mb *TCPClientHandler) State() closeState
- func (mb *TCPClientHandler) Verify(request []byte, response []byte) (err error)
- type Transporter
Constants ¶
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 ¶
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
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) GetCharsAt ¶
GetCharsAt Get Array of char (S7 ARRAY OF CHARS)
func (*Helper) GetCounter ¶
GetCounter Get S7 Counter
func (*Helper) GetCounterAt ¶
GetCounterAt Get S7 Counter at a index
func (*Helper) GetDateTimeAt ¶
GetDateTimeAt DateTime (S7 DATE_AND_TIME)
func (*Helper) GetLRealAt ¶
GetLRealAt 64 bit floating point number (S7 LReal) (Range of float64)
func (*Helper) GetS5TimeAt ¶
Get S5Time
func (*Helper) GetStringAt ¶
GetStringAt Get String
func (*Helper) GetValueAt ¶
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 ¶
GetWStringAt Get WString
func (*Helper) SetBoolAt ¶
SetBoolAt sets a boolean (bit) within a byte at bit position without changing the other bits it returns the resulted byte
func (*Helper) SetCharsAt ¶
SetCharsAt Get Array of char (S7 ARRAY OF CHARS)
func (*Helper) SetCounterAt ¶
SetCounterAt set a counter at a postion
func (*Helper) SetDateTimeAt ¶
SetDateTimeAt DateTime (S7 DATE_AND_TIME)
func (*Helper) SetLRealAt ¶
SetLRealAt 64 bit floating point number (S7 LReal) (Range of float64)
func (*Helper) SetS5TimeAt ¶
SetS5TimeAt Set S5Time
func (*Helper) SetStringAt ¶
SetStringAt Set String (S7 String)
func (*Helper) SetValueAt ¶
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 ¶
SetWStringAt Set String (WString)
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
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 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 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 S7SZLList ¶
S7SZLList of available SZL IDs : same as SZL but List items are big-endian adjusted
type SZLHeader ¶
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 ¶
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 进行取消操作
type Transporter ¶
Transporter specifies the transport layer.