hsms

package
v1.14.0 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package hsms provides a High-Speed SECS Message Services (HSMS) implementation for communication with semiconductor manufacturing equipment according to the SEMI E37 standard.

This package offers functionalities for establishing/decoding HSMS control and data message and defining generic interface for HSMS session. It also provides generic connection state manager for handling HSMS state transition.

Message Types: The package defines constants representing different types of HSMS messages, categorized by their function:

  • DataMsgType: Data message containing SECS-II data.
  • SelectReqType, SelectRspType: Session establishment messages.
  • DeselectReqType, DeselectRspType: Session termination messages.
  • LinkTestReqType, LinkTestRspType: Link testing messages.
  • RejectReqType: Reject message for errors or rejections.
  • SeparateReqType: Separate request message for graceful disconnect.

HSMSMessage Interface: The HSMSMessage interface extends the SECS2Message interface and provides methods for:

  • Accessing message attributes (type, session ID, system bytes, header).
  • Converting between HSMS message types (control and data messages).
  • Serializing messages to bytes for transmission (`ToBytes()`).
  • Managing message lifecycle and resource release (`Free()`).
  • Creating deep copies of messages (`Clone()`).

Stream/Function Quote Customization: The package provides functions to customize the quoting of stream and function codes in SML (SECS Message Language) representations of HSMS messages:

  • UseStreamFunctionNoQuote: No quotes around stream and function codes.
  • UseStreamFunctionSingleQuote: Single quotes (') around stream and function codes.
  • UseStreamFunctionDoubleQuote: Double quotes (") around stream and function codes.

Index

Constants

View Source
const (
	// SelectStatusSuccess indicates that communication is successfully established.
	SelectStatusSuccess = 0
	// SelectStatusActived indicates that communication is already actived.
	SelectStatusActived = 1
	// SelectStatusNotReady indicates that communication is not ready.
	SelectStatusNotReady = 2
	// SelectStatusAlreadyUsed indicates that TCP/IP port is exhausted, another connection already established.
	SelectStatusAlreadyUsed = 3

	// SelectStatusEntityUnknown indicates that entity(session) is not supported.
	// this status only relevant for HSMS-GS.
	SelectStatusEntityUnknown = 4
	// SelectStatusEntityAlreadyUsed indicates that entity(session) is already used by others.
	SelectStatusEntityAlreadyUsed = 5
	// SelectStatusEntitActived indicates that entity(session) is already actived.
	SelectStatusEntitActived = 6

	// DeselectStatusSuccess indicates that communication is successfully ended.
	DeselectStatusSuccess = 0
	// DeselectStatusNotEstablished indicates that HSMS communication has not yet been
	// established with a select, or has already been ended with a previous deselect.
	DeselectStatusNotEstablished = 1
	// DeselectStatusBusy indicates that the session is still in use by the responding entity
	// and so it cannot yet relinquish it gracefully.
	DeselectStatusBusy = 2
)
View Source
const (
	RejectSTypeNotSupported  = 1 // received message's sType is not supported,
	RejectPTypeNotSupported  = 2 // received message's pType is not supported,
	RejectTransactionNotOpen = 3 // transaction is not open, i.e. response message was received without request,
	RejectNotSelected        = 4 // data message is received in non-selected state,
)

Reject code contstants defining reason codes of Reject.req control message.

View Source
const (
	WaitBitFalse = uint8(0)
	WaitBitTrue  = uint8(1)
)

WaitBit byte constants representing if wait-bit is set.

View Source
const (
	// HeaderSize is the size of the HSMS message header in bytes.
	HeaderSize = 10
	// LengthFieldSize is the size of the message length field in bytes.
	LengthFieldSize = 4
	// MinHSMSSize is the minimum size of an HSMS message (length field + header).
	MinHSMSSize = LengthFieldSize + HeaderSize
	// MaxListDepth is the maximum allowed nesting depth for SECS-II list items.
	MaxListDepth = 64
)
View Source
const (
	UndefiniedMsgType = -1 // Undefeind stream session type
	DataMsgType       = 0  // Data message containing SECS-II data
	SelectReqType     = 1  // Select request control message
	SelectRspType     = 2  // Select response control message
	DeselectReqType   = 3  // Deselect request control message
	DeselectRspType   = 4  // Deselect response control message
	LinkTestReqType   = 5  // Linktest request control message
	LinkTestRspType   = 6  // Linktest response control message
	RejectReqType     = 7  // Reject request control message
	SeparateReqType   = 9  // Separate request control message
)

Type constants representing the different types of HSMS messages. These constants categorize messages based on their primary function and role in the HSMS protocol.

View Source
const DefaultMessageBufferSize = 128 * 1024 // 64KB default size
View Source
const MaxStreamCode = 127

MaxStreamCode is the maximum valid stream code value (0-127).

Variables

View Source
var (
	// ErrInvalidHeaderLength indicates that an invalid header length was provided.
	// The header length should be 10 bytes.
	ErrInvalidHeaderLength = errors.New("invalid header length, should be 10 bytes")

	// ErrInvalidPType indicates that an invalid PType was provided.
	// The PType should be 0 for SECS-II message.
	ErrInvalidPType = errors.New("invalid PType, should be 0 for SECS-II message")

	// ErrInvalidDataMsgSType indicates that an invalid SType was provided.
	// The SType should be 0 for data message.
	ErrInvalidDataMsgSType = errors.New("invalid SType for data message, should be 0")
	// ErrInvalidControlMsgSType indicates that an invalid SType was provided.
	// The SType should be 0 for data message.
	ErrInvalidControlMsgSType = errors.New("invalid SType for control message, should be in range of [1, 9]")

	// ErrInvalidRejectMsg indicates that the message is not a valid reject control message.
	//
	// Added in v1.8.0
	ErrInvalidRejectMsg = errors.New("the message is not a reject control message")
	// ErrInvalidRejectReason indicates that an invalid reject reason was provided.
	//
	// Added in v1.8.0
	ErrInvalidRejectReason = errors.New("invalid reject reason, should be in range of [1, 4]")

	// ErrInvalidStreamCode indicates that an invalid stream code was provided.
	// Valid stream codes are in the range of 0 to 127.
	ErrInvalidStreamCode = errors.New("invalid stream code, should be in range of [0, 127]")

	// ErrInvalidWaitBit indicates that an invalid wait bit value was provided.
	// The wait bit should be either 0 or 1.
	ErrInvalidWaitBit = errors.New("invalid wait bit, should be 0 or 1")

	// ErrInvalidSystemBytes indicates that invalid system bytes were provided.
	// System bytes should be a 4-byte array.
	ErrInvalidSystemBytes = errors.New("invalid system bytes, length is not 4")
)
View Source
var (
	// ErrConnConfigNil indicates that a nil ConnectionConfig was provided.
	ErrConnConfigNil = errors.New("connection config is nil")

	// ErrSessionNil indicates that a nil Session was encountered.
	ErrSessionNil = errors.New("session is nil")

	// ErrConnClosed indicates that the connection is closed.
	ErrConnClosed = errors.New("connection closed")

	// ErrSendMsgTimeout indicates that sending a message timed out.
	//
	// Added in v1.8.0
	ErrSendMsgTimeout = errors.New("send message timeout")

	// ErrSelectFailed indicates that the session selection failed.
	ErrSelectFailed = errors.New("select failed")

	// ErrInvalidReqMsg indicates that the message is not a valid request/primary message.
	ErrInvalidReqMsg = errors.New("message is not a valid request/primary message")

	// ErrInvalidRspMsg indicates that the message is not a valid response/secondary message.
	ErrInvalidRspMsg = errors.New("message is not a valid response/secondary message")

	// ErrNotDataMsg indicates that the message is not a data message.
	ErrNotDataMsg = errors.New("message is not a data message")

	// ErrNotControlMsg indicates that the message is not a control message.
	ErrNotControlMsg = errors.New("message is not a control message")
)
View Source
var (
	// ErrInvalidTransition is returned when an attempt is made to transition the connection
	// state to an invalid state.
	ErrInvalidTransition = errors.New("invalid state transition")

	// ErrNotSelectedState indicates that the current connection state is not the selected state.
	ErrNotSelectedState = errors.New("current state is not the selected state")
)
View Source
var (
	// ErrRejectSTypeNotSupported indicates that the remote entity rejected the message
	// because the SType is not supported.
	// This corresponds to reject reason code 1 in SEMI E37.
	//
	// Added in v1.10.0
	ErrRejectSTypeNotSupported = errors.New("reject: SType not supported")

	// ErrRejectPTypeNotSupported indicates that the remote entity rejected the message
	// because the PType is not supported.
	// This corresponds to reject reason code 2 in SEMI E37.
	//
	// Added in v1.10.0
	ErrRejectPTypeNotSupported = errors.New("reject: PType not supported")

	// ErrRejectTransactionNotOpen indicates that the remote entity rejected the message
	// because the transaction is not open (i.e., a response was received without a corresponding request).
	// This corresponds to reject reason code 3 in SEMI E37.
	//
	// Added in v1.10.0
	ErrRejectTransactionNotOpen = errors.New("reject: transaction not open")

	// ErrRejectNotSelected indicates that the remote entity rejected the message
	// because the connection is not in the selected state.
	// This corresponds to reject reason code 4 in SEMI E37.
	//
	// Added in v1.10.0
	ErrRejectNotSelected = errors.New("reject: entity not selected")
)
View Source
var (
	// ErrT3Timeout indicates that a T3 timeout has occurred.
	// This occurs when a reply message is not received within the T3 timeout period after sending a primary message.
	ErrT3Timeout = errors.New("T3 timeout")

	// ErrT5Timeout indicates that a T5 timeout has occurred.
	// This occurs when the connect separation time (T5) has elapsed.
	ErrT5Timeout = errors.New("T5 timeout")

	// ErrT6Timeout indicates that a T6 timeout has occurred.
	// This occurs when a reply to a control message is not received within the T6 timeout period.
	ErrT6Timeout = errors.New("T6 timeout")

	// ErrT7Timeout indicates that a T7 timeout has occurred.
	// This occurs when the equipment fails to transition to the Selected state within the T7 timeout period.
	ErrT7Timeout = errors.New("T7 timeout")

	// ErrT8Timeout indicates that a T8 timeout has occurred.
	// This occurs when the inter-character timeout (T8) has elapsed during message transmission.
	ErrT8Timeout = errors.New("T8 timeout")
)
View Source
var (
	// ErrUnrecognizedDeviceID indicates that an unrecognized Device ID was received in a message.
	// This error is typically sent in response to an S9F1 message.
	//
	// Added in v1.9.0
	ErrUnrecognizedDeviceID = errors.New("unrecognized device id")

	// ErrUnrecognizedStreamType indicates that an unrecognized Stream Type was received in a message.
	// This error is typically sent in response to an S9F3 message.
	//
	// Added in v1.9.0
	ErrUnrecognizedStreamType = errors.New("unrecognized stream type")

	// ErrUnrecognizedFunctionType indicates that an unrecognized Function Type wasreceived in a message.
	// This error is typically sent in response to an S9F5 message.
	//
	// Added in v1.9.0
	ErrUnrecognizedFunctionType = errors.New("unrecognized function type")

	// ErrIllegalData indicates that the data is illegal for the Function Type.
	// This error is typically sent in response to an S9F7 message.
	//
	// Added in v1.9.0
	ErrIllegalData = errors.New("illegal data")

	// ErrTransactionTimeout indicates that the equipment failed to process a message
	// from the host within the timeout period.
	// This error is typically sent in response to an S9F9 message.
	//
	// Added in v1.9.0
	ErrTransactionTimeout = errors.New("transaction timeout")

	// ErrDataTooLong indicates that the length of the data in a message exceeds
	// the maximum message length that the equipment can process.
	// This error is typically sent in response to an S9F11 message.
	//
	// Added in v1.9.0
	ErrDataTooLong = errors.New("data too long")

	// ErrConversationTimeout indicates that the host failed to respond to a message
	// within the timeout period.
	// This error is typically sent in response to an S9F13 message.
	//
	// Added in v1.9.0
	ErrConversationTimeout = errors.New("conversation timeout")
)

Functions

func DecodeSECS2Item added in v1.6.0

func DecodeSECS2Item(data []byte) (secs2.Item, error)

DecodeSECS2Item decodes an SECS-II item from the given byte slice.

data is the byte array containing the encoded SECS-II item.

It returns the decoded SECS-II item and an error if any occurred during decoding.

func GenerateMsgID

func GenerateMsgID() uint32

GenerateMsgID returns a unique message ID as a uint32.

func GenerateMsgSystemBytes

func GenerateMsgSystemBytes() []byte

GenerateMsgSystemBytes returns a unique 4-byte slice representing the system bytes for a message.

func GetMessageBuffer added in v1.8.0

func GetMessageBuffer(msgLen uint32) []byte

GetMessageBuffer retrieves a buffer from the pool or creates a new one. The returned buffer has the exact length of msgLen. Caller owns the buffer until it's returned with PutMessageBuffer.

Added in v1.8.0

func GetRejectReasonCode added in v1.8.0

func GetRejectReasonCode(recvMsg HSMSMessage) (int, error)

GetRejectReasonCode extracts the reason code from a Reject.req message.

func IsUsePool

func IsUsePool() bool

IsUsePool returns true if HSMS data message and SECS-II item pooling is enabled, false otherwise.

func MsgHexString added in v1.9.0

func MsgHexString(datas ...[]byte) string

MsgHexString returns a hex string representation of the provided byte slices. It outputs byte by byte in hex format, separated by a space.

func MsgInfo

func MsgInfo(msg HSMSMessage, keyValues ...any) []any

MsgInfo returns a structued message information without SML string.

func MsgInfoSML

func MsgInfoSML(msg HSMSMessage, keyValues ...any) []any

MsgInfoSML returns a structued message information with SML string.

func PutMessageBuffer added in v1.8.0

func PutMessageBuffer(buf []byte)

PutMessageBuffer returns a buffer to the pool for reuse. Only buffers with default capacity are pooled. The buffer is reset to zero length before pooling.

Added in v1.8.0

func StreamFunctionQuote

func StreamFunctionQuote() string

StreamFunctionQuote returns the current quoting character used for stream and function codes in SML. It returns an empty string if no quotes are used, a single quote (') if single quotes are used, or a double quote (") if double quotes are used.

func ToSystemBytes

func ToSystemBytes(id uint32) []byte

ToSystemBytes converts id to 4-byte slice system bytes.

func UsePool

func UsePool(val bool)

UsePool enables or disables the use of pools for HSMS data messages and SECS-II items. Pooling can help reduce memory allocations by reusing objects.

By default, pooling is enabled (usePool = true).

This function also controls the pooling behavior of SECS-II items using secs2.UsePool(val).

func UseStreamFunctionDoubleQuote

func UseStreamFunctionDoubleQuote()

UseStreamFunctionDoubleQuote sets the quoting style for stream and function codes in SML to use double quotes ("). This affects both the generation of SML strings and the parsing of SML strings.

func UseStreamFunctionNoQuote

func UseStreamFunctionNoQuote()

UseStreamFunctionNoQuote sets the quoting style for stream and function codes in SML to use no quotes. This affects both the generation of SML strings (ToSML methods) and the parsing of SML strings.

func UseStreamFunctionSingleQuote

func UseStreamFunctionSingleQuote()

UseStreamFunctionSingleQuote sets the quoting style for stream and function codes in SML to use single quotes ('). This affects both the generation of SML strings and the parsing of SML strings.

Types

type AtomicOpState added in v1.7.2

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

func (*AtomicOpState) Get added in v1.7.2

func (st *AtomicOpState) Get() OpState

Get returns the current state of the AtomicOpState.

func (*AtomicOpState) IsClosed added in v1.7.2

func (st *AtomicOpState) IsClosed() bool

func (*AtomicOpState) IsClosing added in v1.7.2

func (st *AtomicOpState) IsClosing() bool

func (*AtomicOpState) IsOpened added in v1.7.2

func (st *AtomicOpState) IsOpened() bool

func (*AtomicOpState) IsOpening added in v1.7.2

func (st *AtomicOpState) IsOpening() bool

func (*AtomicOpState) Set added in v1.7.2

func (st *AtomicOpState) Set(state OpState)

Set sets the state of the AtomicOpState to the given state.

func (*AtomicOpState) String added in v1.7.2

func (st *AtomicOpState) String() string

func (*AtomicOpState) ToClosed added in v1.7.2

func (st *AtomicOpState) ToClosed() bool

func (*AtomicOpState) ToClosing added in v1.7.2

func (st *AtomicOpState) ToClosing() bool

func (*AtomicOpState) ToOpened added in v1.7.2

func (st *AtomicOpState) ToOpened() bool

func (*AtomicOpState) ToOpening added in v1.7.2

func (st *AtomicOpState) ToOpening() bool

type BaseSession

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

BaseSession implements common methods for HSMS-SS and HSMS-GS session.

func NewBaseSession added in v1.2.0

func NewBaseSession(
	idFunc func() uint16,
	sendMessageFunc func(msg HSMSMessage) (HSMSMessage, error),
	sendMessageAsyncFunc func(msg HSMSMessage) error,
) *BaseSession

NewBaseSession creates a new BaseSession with the specified ID generator function and message sending functions.

func (*BaseSession) RegisterIDFunc added in v1.2.0

func (s *BaseSession) RegisterIDFunc(f func() uint16)

func (*BaseSession) RegisterSendMessageAsyncFunc added in v1.2.0

func (s *BaseSession) RegisterSendMessageAsyncFunc(f func(msg HSMSMessage) error)

func (*BaseSession) RegisterSendMessageFunc added in v1.2.0

func (s *BaseSession) RegisterSendMessageFunc(f func(msg HSMSMessage) (HSMSMessage, error))

func (*BaseSession) ReplyDataMessage

func (s *BaseSession) ReplyDataMessage(primaryMsg *DataMessage, dataItem secs2.Item) error

ReplyDataMessage sends a reply to a previously received data message. It takes the original primary DataMessage and the data item for the reply as arguments. It returns an error if any occurred during sending the reply.

It is a wrapper method to reply data message with the corresponding function code of primary message.

func (*BaseSession) SendDataMessage

func (s *BaseSession) SendDataMessage(stream byte, function byte, replyExpected bool, dataItem secs2.Item) (*DataMessage, error)

SendDataMessage sends an HSMS data message with the specified stream, function, and data item. It waits for a reply if replyExpected is true. It returns the received reply DataMessage if replyExpected is true, nil otherwise, and and an error if any occurred during sending or receiving.

func (*BaseSession) SendDataMessageAsync added in v1.2.0

func (s *BaseSession) SendDataMessageAsync(stream byte, function byte, replyExpected bool, dataItem secs2.Item) error

SendDataMessageAsync sends an HSMS data message asynchronously.

It sends the message and returns immediately after sending, and let user specified data message handler to receive reply if any.

func (*BaseSession) SendSECS2Message

func (s *BaseSession) SendSECS2Message(msg secs2.SECS2Message) (*DataMessage, error)

SendSECS2Message sends a SECS-II message and waits for its reply. It returns the received reply message (as a DataMessage) and an error if any occurred during sending or receiving.

func (*BaseSession) SendSECS2MessageAsync added in v1.2.0

func (s *BaseSession) SendSECS2MessageAsync(msg secs2.SECS2Message) error

SendSECS2MessageAsync sends a SECS-II message asynchronously. It sends the message and returns immediately after sending, and let user specified data message handler to receive reply if any.

type ConnState

type ConnState uint32

ConnState represents the various stages of an HSMS connection.

const (
	// NotConnectedState indicates that the TCP/IP connection is not established.
	// This state is used when the connection is not yet established or has been closed.
	NotConnectedState ConnState = iota

	// ConnectingState indicates that the TCP/IP connection is in the process of being established.
	// This state is not a final state, but rather a transitional state.
	//   - For the active connection, this state is used when trying to connect to the remote server.
	//   - For the passive connection, this state is used when listening for incoming connections and waiting for a client to connect.
	ConnectingState

	// NotSelectedState indicates that the HSMS connection is established, but not yet ready for data exchange.
	NotSelectedState

	// SelectedState indicates that the HSMS connection is established and ready for data exchange.
	SelectedState
)

HSMS connection states representing the various stages of an HSMS connection.

func (ConnState) IsConnecting added in v1.7.2

func (cs ConnState) IsConnecting() bool

IsConnecting returns if the current state is connecting.

func (ConnState) IsNotConnected

func (cs ConnState) IsNotConnected() bool

IsNotConnected returns if the current state is not connected.

func (ConnState) IsNotSelected

func (cs ConnState) IsNotSelected() bool

IsNotSelected returns if the current state is not selected.

func (ConnState) IsSelected

func (cs ConnState) IsSelected() bool

IsSelected returns if the current state is selected.

func (ConnState) String

func (cs ConnState) String() string

String returns string representation of the current state.

type ConnStateChangeHandler

type ConnStateChangeHandler func(conn Connection, prevState ConnState, newState ConnState)

ConnStateChangeHandler is a function type that represents a handler for connection state changes. It is invoked when the state of an HSMS connection changes.

Note: the handler will be invoked in a blocking mode. Take care with long-running implementations.

The handler function receives two arguments:

  • prevState: The previous connection state.
  • newState: The current connection state.

type ConnStateMgr

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

ConnStateMgr manages the connection state of an HSMS connection.

It provides methods for managing state transitions and notifying listeners of state changes. The state transitions are thread safety in concurrent environments.

func NewConnStateMgr

func NewConnStateMgr(ctx context.Context, conn Connection, handlers ...ConnStateChangeHandler) *ConnStateMgr

NewConnStateMgr creates a new ConnStateMgr instance, initializing it to the NotConnectedState.

It accepts optional ConnStateChangeHandler functions that will be invoked when the connection state changes.

func (*ConnStateMgr) AddHandler

func (cs *ConnStateMgr) AddHandler(handlers ...ConnStateChangeHandler)

AddHandler adds one or more ConnStateChangeHandler functions to be invoked on state changes.

The handler is responsible for processing the state change and taking appropriate action.

  • Ths handler should keep as light as possible to avoid blocking the channel.
  • The handler should only call async state change methods to avoid deadlock.

func (*ConnStateMgr) DesiredState added in v1.7.2

func (cs *ConnStateMgr) DesiredState() ConnState

func (*ConnStateMgr) IsConnecting added in v1.7.3

func (cs *ConnStateMgr) IsConnecting() bool

IsConnecting returns if the current state is connecting.

func (*ConnStateMgr) IsNotConnected

func (cs *ConnStateMgr) IsNotConnected() bool

IsNotConnected returns if the current state is not connected.

func (*ConnStateMgr) IsNotSelected

func (cs *ConnStateMgr) IsNotSelected() bool

IsNotSelected returns if the current state is not selected.

func (*ConnStateMgr) IsSelected

func (cs *ConnStateMgr) IsSelected() bool

IsSelected returns if the current state is selected.

func (*ConnStateMgr) Start added in v1.7.2

func (cs *ConnStateMgr) Start()

func (*ConnStateMgr) State

func (cs *ConnStateMgr) State() ConnState

State returns the current connection state.

func (*ConnStateMgr) Stop added in v1.7.2

func (cs *ConnStateMgr) Stop()

func (*ConnStateMgr) ToConnecting added in v1.7.2

func (cs *ConnStateMgr) ToConnecting() error

ToConnecting transitions the connection state to ConnectingState. This transition is allowed from NotConnectedState and indicates that the connection is being established.

func (*ConnStateMgr) ToConnectingAsync added in v1.7.2

func (cs *ConnStateMgr) ToConnectingAsync()

ToConnectingAsync transitions connection state to ConnectingState asynchronously.

It will notify a goroutine and transite state in the back asynchronously.

If the state is the same as the current state, the function is a no-op.

func (*ConnStateMgr) ToNotConnected

func (cs *ConnStateMgr) ToNotConnected()

ToNotConnected transitions the connection state to NotConnectedState. This transition is allowed from any state and represents a disconnection or a reset of the connection.

func (*ConnStateMgr) ToNotConnectedAsync

func (cs *ConnStateMgr) ToNotConnectedAsync()

ToNotConnectedAsync transitions connection state to NotConnectedState asynchronously.

It will notify a goroutine and transite state in the back asynchronously.

If the state is the same as the current state, the function is a no-op.

func (*ConnStateMgr) ToNotSelected

func (cs *ConnStateMgr) ToNotSelected() error

ToNotSelected transitions the connection state to NotSelectedState.

This transition is only allowed from the NotConnected/Connecting (HSMS-SS and HSMS-GS) or SelectedState (HSMS-GS only). If the state is already NotSelectedState, the function is a no-op.

Returns nil on success, or ErrInvalidTransition if fails.

func (*ConnStateMgr) ToNotSelectedAsync

func (cs *ConnStateMgr) ToNotSelectedAsync()

ToNotSelectedAsync transitions connection state to NotSelectedState asynchronously.

It will notify a goroutine and transite state in the back asynchronously.

If the state is the same as the current state, the function is a no-op.

func (*ConnStateMgr) ToSelected

func (cs *ConnStateMgr) ToSelected() error

ToSelected transitions the connection state to SelectedState.

This transition is only allowed from the NotSelectedState and indicates that the HSMS session is established and ready for data exchange. If the state is already SelectedState, the function is a no-op.

Returns nil on success, or ErrInvalidTransition if the current state is not NotSelectedState.

func (*ConnStateMgr) ToSelectedAsync

func (cs *ConnStateMgr) ToSelectedAsync()

ToSelectedAsync transitions connection state to SelectedState asynchronously.

It will notify a goroutine and transite state in the back asynchronously.

If the state is the same as the current state, the function is a no-op.

func (*ConnStateMgr) WaitState

func (cs *ConnStateMgr) WaitState(ctx context.Context, state ConnState) error

WaitState waits for the connection state to reach the specified state or until the context is done. It returns nil if the desired state is reached, or an error if the context is canceled or times out.

type Connection

type Connection interface {
	// Open establishes the HSMS connection.
	// If waitOpened is true, it blocks until the connection is fully established or an error occurs.
	// If waitOpened is false, it returns immediately after initiating the connection process.
	Open(waitOpened bool) error

	// Close closes the HSMS connection.
	Close() error

	// AddSession creates and adds a new session to the connection with the specified session ID.
	// It returns the newly created Session.
	AddSession(sessionID uint16) Session

	// GetLogger returns the logger associated with the HSMS connection.
	GetLogger() logger.Logger

	// IsSingleSession returns true if the connection is an HSMS-SS (Single Session) connection, false otherwise.
	IsSingleSession() bool

	// IsGeneralSession returns true if the connection is an HSMS-GS (General Session) connection, false otherwise.
	IsGeneralSession() bool

	// IsSECS1 returns true if the connection is a SECS-I connection, false otherwise.
	IsSECS1() bool
}

Connection defines the interface for a HSMS connection.

type ControlMessage

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

ControlMessage represents a HSMS control message.

It implements the HSMSMessage and secs2.SECS2Message interfaces.

func NewDeselectReq

func NewDeselectReq(sessionID uint16, systemBytes []byte) *ControlMessage

NewDeselectReq creates HSMS Deselect.req control message. systemBytes should have length of 4.

func NewDeselectRsp

func NewDeselectRsp(deselectReq HSMSMessage, deselectStatus byte) (*ControlMessage, error)

NewDeselectRsp creates HSMS Deselect.rsp control message from Deselect.req message. deselectStatus 0 means that the connection is successfully ended, 1 means that communication is not yet established, 2 means that communication is busy and cannot yet be relinquished, 3-255 are reserved failure reason codes.

func NewLinktestReq

func NewLinktestReq(systemBytes []byte) *ControlMessage

NewLinktestReq creates HSMS Linktest.req control message. systemBytes should have length of 4.

func NewLinktestRsp

func NewLinktestRsp(linktestReq HSMSMessage) (*ControlMessage, error)

NewLinktestRsp creates HSMS Linktest.rsp control message from Linktest.req message.

func NewRejectReq

func NewRejectReq(recvMsg HSMSMessage, reasonCode byte) *ControlMessage

NewRejectReq creates HSMS Reject.req control message.

recvMsg should be the HSMS message being rejected.

reasonCode should be non-zero,

  • 1 means that received message's sType is not supported,
  • 2 means that received message's pType is not supported,
  • 3 means that transaction is not open, i.e. response message was received without request,
  • 4 means that data message is received in non-selected state,
  • 5-255 are reserved reason codes.

func NewRejectReqRaw

func NewRejectReqRaw(sessionID uint16, pType, sType byte, systemBytes []byte, reasonCode byte) *ControlMessage

NewRejectReqRaw creates HSMS Reject.req control message.

sessionID, pType, sType, and systemBytes should be same as the HSMS message being rejected. systemBytes should have length of 4.

reasonCode should be non-zero,

  • 1 means that received message's sType is not supported,
  • 2 means that received message's pType is not supported,
  • 3 means that transaction is not open, i.e. response message was received without request,
  • 4 means that data message is received in non-selected state,
  • 5-255 are reserved reason codes.

func NewSelectReq

func NewSelectReq(sessionID uint16, systemBytes []byte) *ControlMessage

NewSelectReq creates HSMS Select.req control message. systemBytes should have length of 4.

func NewSelectRsp

func NewSelectRsp(selectReq HSMSMessage, selectStatus byte) (*ControlMessage, error)

NewSelectRsp creates HSMS Select.rsp control message from Select.req message. selectStatus 0 means that communication is successfully established, 1 means that communication is already actived, 2 means that communication is not ready, 3 means that connection that TCP/IP port is exhausted (for HSMS-SS passive mode), 4-255 are reserved failure reason codes.

func NewSeparateReq

func NewSeparateReq(sessionID uint16, systemBytes []byte) *ControlMessage

NewSeparateReq creates HSMS Separate.req control message. systemBytes should have length of 4.

func (*ControlMessage) Clone

func (msg *ControlMessage) Clone() HSMSMessage

Clone creates a deep copy of the message, allowing modifications to the clone without affecting the original message.

It implements the Clone method of the HSMSMessage interface.

func (*ControlMessage) Error added in v1.8.0

func (msg *ControlMessage) Error() error

Error returns the error associated with the control message.

It implements the Error method of the HSMSMessage interface.

func (*ControlMessage) Free

func (msg *ControlMessage) Free()

Free takes no action for control message. It is a no-op method, as control messages do not require resource cleanup like data messages do.

It implements the Free() method of the HSMSMessage interface.

func (*ControlMessage) FunctionCode

func (msg *ControlMessage) FunctionCode() uint8

FunctionCode returns the header[3] for the control message, it's defined by different control message type.

It implements the FunctionCode method of the secs2.SECS2Message interface.

func (*ControlMessage) Header

func (msg *ControlMessage) Header() []byte

Header returns the 10-byte control message header

It implements the Header method of the HSMSMessage interface.

func (*ControlMessage) ID

func (msg *ControlMessage) ID() uint32

ID returns a numeric representation of the system bytes (message ID).

It implements the ID method of the HSMSMessage interface.

func (*ControlMessage) IsControlMessage

func (msg *ControlMessage) IsControlMessage() bool

IsControlMessage returns true, indicating that the message is a control message.

It implements the IsControlMessage method of the HSMSMessage interface.

func (*ControlMessage) IsDataMessage

func (msg *ControlMessage) IsDataMessage() bool

IsDataMessage returns false, indicating that the message is not a data message.

It implements the IsDataMessage() method of the HSMSMessage interface.

func (*ControlMessage) Item

func (msg *ControlMessage) Item() secs2.Item

Item returns empty SECS-II data item for control message.

It implements the Item method of the secs2.SECS2Message interface.

func (*ControlMessage) MarshalBinary added in v1.7.0

func (msg *ControlMessage) MarshalBinary() ([]byte, error)

MarshalBinary serializes the control message into its byte representation for transmission.

It implements the MarshalBinary method of the encoding.BinaryMarshaler interface.

func (*ControlMessage) SessionID

func (msg *ControlMessage) SessionID() uint16

SessionID returns the session id of the control message.

It implements the SessionID() method of the HSMSMessage interface.

func (*ControlMessage) SetError added in v1.8.0

func (msg *ControlMessage) SetError(err error)

SetError sets the error of the control message. It is used to indicate an error condition in the message.

It implements the SetError method of the HSMSMessage interface.

func (*ControlMessage) SetHeader added in v1.1.1

func (msg *ControlMessage) SetHeader(header []byte) error

SetHeader sets the header of the control message. It will return error if the header is invalid.

It implements the SetHeader method of the HSMSMessage interface.

func (*ControlMessage) SetID added in v1.7.3

func (msg *ControlMessage) SetID(id uint32)

SetID sets the system bytes (message ID) of the control message. It will convert the id to 4-byte big-endian representation and set it in the header.

It implements the SetID method of the HSMSMessage interface.

func (*ControlMessage) SetSessionID added in v1.1.1

func (msg *ControlMessage) SetSessionID(sessionID uint16)

SetSessionID sets the session id of the control message. It will convert the sessionID to 2-byte big-endian representation and set it in the header.

It implements the SetSessionID method of the HSMSMessage interface.

func (*ControlMessage) SetSystemBytes added in v1.1.1

func (msg *ControlMessage) SetSystemBytes(systemBytes []byte) error

SetSystemBytes sets system bytes to the control message. It will return error if the systemBytes is not 4 bytes.

It implements the SetSystemBytes method of the HSMSMessage interface.

func (*ControlMessage) StreamCode

func (msg *ControlMessage) StreamCode() uint8

StreamCode returns the stream code for the control message.

It implements the StreamCode method of the secs2.SECS2Message interface.

func (*ControlMessage) SystemBytes

func (msg *ControlMessage) SystemBytes() []byte

SystemBytes returns the 4-byte system bytes (message ID).

It implements the SystemBytes method of the HSMSMessage interface.

func (*ControlMessage) ToBytes

func (msg *ControlMessage) ToBytes() []byte

ToBytes returns the HSMS byte representation of the control message.

It implements the ToBytes method of the HSMSMessage interface.

func (*ControlMessage) ToControlMessage

func (msg *ControlMessage) ToControlMessage() (*ControlMessage, bool)

ToControlMessage converts the message to an control message. Since the message is already a ControlMessage, it returns a pointer to itself and true.

It implements the ToControlMessage method of the HSMSMessage interface.

func (*ControlMessage) ToDataMessage

func (msg *ControlMessage) ToDataMessage() (*DataMessage, bool)

ToDataMessage attempts to convert the message to an data message. Since a ControlMessage cannot be converted to a DataMessage, it always returns nil and false.

It implements the ToDataMessage method of the HSMSMessage interface.

func (*ControlMessage) Type

func (msg *ControlMessage) Type() int

Type returns the message type of the control message.

It implements the Type method of the HSMSMessage interface.

func (*ControlMessage) UnmarshalBinary added in v1.7.0

func (msg *ControlMessage) UnmarshalBinary(data []byte) error

UnmarshalBinary deserializes the byte data into the HSMS control message.

It implements the UnmarshalBinary method of encoding.BinaryUnmarshaler interface.

func (*ControlMessage) WaitBit

func (msg *ControlMessage) WaitBit() bool

WaitBit returnes the boolean representation to indicates WBit is set

It implements the WaitBit method of the secs2.SECS2Message interface.

type DataMessage

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

DataMessage represents a HSMS data message.

It implements the HSMSMessage and secs2.SECS2Message interfaces.

func NewDataMessage

func NewDataMessage(stream byte, function byte, replyExpected bool, sessionID uint16, systemBytes []byte, dataItem secs2.Item) (*DataMessage, error)

NewDataMessage creates a new SECS-II message.

The message can't be converted to HSMS format until session id, system bytes and wait bit is set (if it had value of optional).

Input argument specifications

stream is a stream code of this message and should be in range of [0, 127].

function is a function code of this message and should be in range of [0, 255].

replyExpected specify if the primary message should excpect a reply message. it sets W-Bit to 1 if true, 0 else. replyExpected cannot true when the function code is a even number(reply message).

sessionID is the session id in HSMS message, it should be in range of [0, 65535].

systemBytes should have 4 bytes.

dataItem is the contents of this message.

func NewDataMessageFromRawItem added in v1.6.0

func NewDataMessageFromRawItem(stream byte, function byte, replyExpected bool, sessionID uint16, systemBytes []byte, data []byte) (*DataMessage, error)

NewDataMessageFromRawItem creates a new SECS-II message from SECS-II raw binary data.

This function is similar to NewDataMessage, but it accepts raw binary data for the SECS-II message instead of SECS-II item.

Please refer to NewDataMessage for more information.

func NewErrorDataMessage added in v1.8.0

func NewErrorDataMessage(stream byte, function byte, sessionID uint16, systemBytes []byte, err error) *DataMessage

NewErrorDataMessage creates a new SECS-II message with an error.

This function is used to create a data message that indicates an error condition. It sets the wait bit to false, indicating that no reply is expected. The session ID and system bytes are provided, and the error is set in the message. The function code should be set to a value that indicates an error condition, typically an odd number to indicate a primary message.

func (*DataMessage) Clone

func (msg *DataMessage) Clone() HSMSMessage

Clone returns a duplicated Message

It implements the Clone method of the HSMSMessage interface.

func (*DataMessage) Error added in v1.8.0

func (msg *DataMessage) Error() error

Error returns the error of the data message.

It implements the Error method of the HSMSMessage interface.

func (*DataMessage) Free

func (msg *DataMessage) Free()

Free releases the message and its associated resources back to the pool. After calling Free, the message should not be accessed again.

It implements the Free method of the HSMSMessage interface.

func (*DataMessage) FunctionCode

func (msg *DataMessage) FunctionCode() uint8

FunctionCode returns the function code of the data message.

It implements the FunctionCode method of the secs2.SECS2Message interface.

func (*DataMessage) Header

func (msg *DataMessage) Header() []byte

Header returns the 10-byte HSMS message header.

It implements the Header method of the HSMSMessage interface.

func (*DataMessage) ID

func (msg *DataMessage) ID() uint32

ID returns a numeric representation of the system bytes (message ID).

It implements the ID method of the HSMSMessage interface.

func (*DataMessage) IsControlMessage

func (msg *DataMessage) IsControlMessage() bool

IsControlMessage returns false, indicating that the message is not a control message. It implements the IsControlMessage method of the HSMSMessage interface.

func (*DataMessage) IsDataMessage

func (msg *DataMessage) IsDataMessage() bool

IsDataMessage returns true, indicating that the message is a data message.

It implements the IsDataMessage method of the HSMSMessage interface.

func (*DataMessage) Item

func (msg *DataMessage) Item() secs2.Item

Item returnes the SECS-II data item in data message.

It implements the Item method of the secs2.SECS2Message interface.

func (*DataMessage) MarshalBinary added in v1.7.0

func (msg *DataMessage) MarshalBinary() ([]byte, error)

MarshalBinary serializes the data message into its byte representation for transmission.

It implements the MarshalBinary method of the encoding.BinaryMarshaler interface.

func (*DataMessage) SMLHeader

func (msg *DataMessage) SMLHeader() string

SMLHeader returns the message header of the data message, e.g. "S6F11 W".

This method only exists on DataMessage, and it is used to generate the SML header

func (*DataMessage) SessionID

func (msg *DataMessage) SessionID() uint16

SessionID returns the session id of the data message. If the session id was not set, it will return -1.

It implements the SessionID method of the HSMSMessage interface.

func (*DataMessage) SetError added in v1.8.0

func (msg *DataMessage) SetError(err error)

SetError sets the error of the data message. It is used to indicate an error condition in the message.

It implements the SetError method of the HSMSMessage interface.

func (*DataMessage) SetFunctionCode added in v1.12.0

func (msg *DataMessage) SetFunctionCode(function uint8)

SetFunctionCode sets the function code of the data message.

Added in v1.12.0

func (*DataMessage) SetHeader added in v1.1.1

func (msg *DataMessage) SetHeader(header []byte) error

SetHeader sets the header of the data message. It will return error if the header is invalid.

It implements the SetHeader method of the HSMSMessage interface.

func (*DataMessage) SetID added in v1.7.3

func (msg *DataMessage) SetID(id uint32)

SetID sets the system bytes of the data message.

It implements the SetID method of the HSMSMessage interface.

func (*DataMessage) SetSessionID added in v1.1.0

func (msg *DataMessage) SetSessionID(sessionID uint16)

SetSessionID sets the session id of the data message.

It implements the SetSessionID method of the HSMSMessage interface.

func (*DataMessage) SetStreamCode added in v1.12.0

func (msg *DataMessage) SetStreamCode(stream uint8) error

SetStreamCode sets the stream code of the data message. It will return error if the stream code is invalid.

Added in v1.12.0

func (*DataMessage) SetSystemBytes

func (msg *DataMessage) SetSystemBytes(systemBytes []byte) error

SetSystemBytes sets system bytes to the data message. It will return error if the systemBytes is not 4 bytes.

It implements the SetSystemBytes method of the HSMSMessage interface.

func (*DataMessage) SetWaitBit added in v1.12.0

func (msg *DataMessage) SetWaitBit(wait bool)

SetWaitBit sets the wait bit of the data message.

Added in v1.12.0

func (*DataMessage) StreamCode

func (msg *DataMessage) StreamCode() uint8

StreamCode returns the stream code of the data message.

It implements the StreamCode method of the secs2.SECS2Message interface.

func (*DataMessage) SystemBytes

func (msg *DataMessage) SystemBytes() []byte

SystemBytes returns the system bytes of the data message. If the system bytes was not set, it will return []byte{0, 0, 0, 0}.

It implements the SystemBytes method of the HSMSMessage interface.

func (*DataMessage) ToBytes

func (msg *DataMessage) ToBytes() []byte

ToBytes returns the HSMS byte representation of the data message.

It will return empty byte slice if the message can't be represented as HSMS format, i.e. wait bit is optional.

It implements the ToBytes method of the HSMSMessage interface.

func (*DataMessage) ToControlMessage

func (msg *DataMessage) ToControlMessage() (*ControlMessage, bool)

ToControlMessage attempts to convert the message to an HSMS control message. Since a DataMessage cannot be converted to a ControlMessage, it always returns nil and false.

It implements the ToControlMessage method of the HSMSMessage interface.

func (*DataMessage) ToDataMessage

func (msg *DataMessage) ToDataMessage() (*DataMessage, bool)

ToDataMessage converts the message to an data message. Since the message is already a DataMessage, it returns a pointer to itself and true.

It implements the ToDataMessage method of the HSMSMessage interface.

func (*DataMessage) ToSML

func (msg *DataMessage) ToSML() string

ToSML returns SML representation of data message.

It implements the ToSML method of the secs2.SECS2Message interface.

func (*DataMessage) Type

func (msg *DataMessage) Type() int

Type returns the message type of the data message.

It implements the Type method of the HSMSMessage interface.

func (*DataMessage) UnmarshalBinary added in v1.7.0

func (msg *DataMessage) UnmarshalBinary(data []byte) error

UnmarshalBinary deserializes the byte data into the HSMS data message.

It implements the UnmarshalBinary method of the encoding.BinaryUnmarshaler interface.

func (*DataMessage) WaitBit

func (msg *DataMessage) WaitBit() bool

WaitBit returnes the boolean representation to indicates WBit is set

It implements the WaitBit method of the secs2.SECS2Message interface.

type DataMessageHandler

type DataMessageHandler func(*DataMessage, Session)

DataMessageHandler is a function type that represents a handler for processing received HSMS data messages.

The handler function receives two arguments:

  • msg: The received DataMessage.
  • session: The Session associated with the received message.

type HSMSMessage

type HSMSMessage interface {
	encoding.BinaryMarshaler
	encoding.BinaryUnmarshaler
	secs2.SECS2Message

	// Type returns the HSMS message type, which can be one of the following constants:
	//  - hsms.DataMsgType
	//  - hsms.SelectReqType
	//  - hsms.SelectRspType
	//  - hsms.DeselectReqType
	//  - hsms.DeselectRspType
	//  - hsms.LinkTestReqType
	//  - hsms.LinkTestRspType
	//  - hsms.RejectReqType
	//  - hsms.SeparateReqType
	Type() int

	// SessionID returns the session ID for the HSMS message.
	SessionID() uint16

	// SetSessionID sets the session ID for the HSMS message.
	SetSessionID(sessionID uint16)

	// ID returns a numeric representation of the system bytes (message ID).
	ID() uint32

	// SetID sets the system bytes (message ID) for the HSMS message.
	SetID(id uint32)

	// SystemBytes returns the 4-byte system bytes (message ID).
	SystemBytes() []byte

	// SetSystemBytes sets the system bytes (message ID) for the HSMS message.
	// The systemBytes should have length of 4.
	//
	// It will return error if the systemBytes is invalid.
	SetSystemBytes(systemBytes []byte) error

	// Error returns the error associated with the HSMS message.
	Error() error

	// SetError sets the error for the HSMS message.
	// It is used to indicate an error condition in the message.
	SetError(err error)

	// Header returns the 10-byte HSMS message header.
	Header() []byte

	// SetHeader sets the header of the HSMS message.
	//
	// It will return error if the header is invalid.
	SetHeader(header []byte) error

	// ToBytes serializes the HSMS message into its byte representation for transmission.
	ToBytes() []byte

	// IsControlMessage returns if the message is control message.
	IsControlMessage() bool
	// ToControlMessage converts the message to an HSMS control message if applicable.
	// It returns a pointer to the ControlMessage and a boolean indicating if the conversion was successful.
	ToControlMessage() (*ControlMessage, bool)

	// IsDataMessage returns if the message is data message.
	IsDataMessage() bool
	// ToDataMessage converts the message to an HSMS data message if applicable.
	// It returns a pointer to the DataMessage and a boolean indicating if the conversion was successful.
	ToDataMessage() (*DataMessage, bool)

	// Free releases the message and its associated resources back to the pool.
	// After calling Free, the message should not be accessed again.
	Free()

	// Clone creates a deep copy of the message, allowing modifications to the clone without affecting the original message.
	Clone() HSMSMessage
}

HSMSMessage represents a message in the HSMS (High-Speed SECS Message Services) protocol. It extends the SECS2Message interface to include HSMS-specific attributes and functionalities.

HSMS messages are categorized into:

  • Data Message: Used for exchanging SECS-II data between the host and equipment.
  • Control Message: Used for managing the HSMS connection itself (e.g., session control, link testing).

This interface provides methods for accessing common HSMS message attributes and converting the message into its specific data or control message representation.

func DecodeHSMSMessage added in v1.6.0

func DecodeHSMSMessage(data []byte) (HSMSMessage, error)

DecodeHSMSMessage decodes an HSMS message from the given byte slice.

data is the byte array containing the encoded HSMS message including the message length, header, and data.

It returns the decoded HSMSMessage and an error if any occurred during decoding.

func DecodeMessage

func DecodeMessage(msgLen uint32, input []byte) (HSMSMessage, error)

DecodeMessage decodes an HSMS message from the given byte slice.

msgLen specifies the total length of the message in bytes, including the header and data. input is the byte array containing the encoded HSMS message.

It returns the decoded HSMSMessage and an error if any occurred during decoding. This function uses a sync.Pool to reuse hsmsDecoder objects for efficiency.

func NewControlMessage

func NewControlMessage(header []byte, replyExpected bool) HSMSMessage

NewControlMessage creates HSMS control message from header bytes. The header should have appropriate values as specified in HSMS specification.

type OpState added in v1.7.2

type OpState uint32
const (
	ClosedState OpState = iota
	ClosingState
	OpeningState
	OpenedState
)

type Session

type Session interface {
	// RegisterIDFunc registers a function to generate a unique ID for this session.
	RegisterIDFunc(f func() uint16)

	// RegisterSendMessageFunc registers a function to send an HSMS message and wait for its reply.
	RegisterSendMessageFunc(f func(msg HSMSMessage) (HSMSMessage, error))

	// RegisterSendMessageAsyncFunc registers a function to send an HSMS message asynchronously.
	RegisterSendMessageAsyncFunc(f func(msg HSMSMessage) error)

	// ID returns the session ID for this session.
	ID() uint16

	// SendMessage sends an HSMSMessage and waits for its reply.
	//
	// It returns the received reply message and an error if any occurred during sending or receiving.
	SendMessage(msg HSMSMessage) (HSMSMessage, error)

	// SendMessageAsync sends an HSMSMessage asynchronously.
	//
	// It sends the message  and returns immediately after sending,
	// and let user specified data message handler to receive reply if any.
	SendMessageAsync(msg HSMSMessage) error

	// SendMessageSync sends an HSMSMessage synchronously.
	//
	// It sends the message and blocks until it's sent to the connection's underlying transport layer.
	// It returns an error if any occurred during sending.
	//
	// Note: it does not wait for a reply.
	//
	// Added in v1.8.0
	SendMessageSync(msg HSMSMessage) error

	// SendSECS2Message sends a SECS-II message and waits for its reply.
	//
	// It returns the received reply message (as a DataMessage) and an error if any occurred during sending or receiving.
	SendSECS2Message(msg secs2.SECS2Message) (*DataMessage, error)

	// SendSECS2MessageAsync sends a SECS-II message asynchronously.
	//
	// It sends the message and returns immediately after sending,
	// and let user specified data message handler to receive reply if any.
	SendSECS2MessageAsync(msg secs2.SECS2Message) error

	// SendDataMessage sends an HSMS data message with the specified stream, function, and data item.
	//
	// It waits for a reply if replyExpected is true.
	// It returns the received reply DataMessage if replyExpected is true, nil otherwise,
	// and and an error if any occurred during sending or receiving.
	SendDataMessage(stream byte, function byte, replyExpected bool, dataItem secs2.Item) (*DataMessage, error)

	// SendDataMessageAsync sends an HSMS data message asynchronously.
	//
	// It sends the message and returns immediately after sending,
	// and let user specified data message handler to receive reply if any.
	SendDataMessageAsync(stream byte, function byte, replyExpected bool, dataItem secs2.Item) error

	// ReplyDataMessage sends a reply to a previously received data message.
	//
	// It takes the original primary DataMessage and the data item for the reply as arguments.
	// It returns an error if any occurred during sending the reply.
	//
	// It is a wrapper method to reply data message with the corresponding function code of primary message.
	ReplyDataMessage(primaryMsg *DataMessage, dataItem secs2.Item) error

	// AddConnStateChangeHandler adds one or more ConnStateChangeHandler functions to be invoked when the connection state changes.
	AddConnStateChangeHandler(handlers ...ConnStateChangeHandler)

	// AddDataMessageHandler adds one or more DataMessageHandler functions to be invoked when a data message is received.
	//
	// It is used to handle data messages asynchronously.
	// The handlers are invoked in the order they are added.
	AddDataMessageHandler(handlers ...DataMessageHandler)
}

Session defines the interface of an HSMS session within an HSMS connection. It provides methods for sending and receiving messages, handling data messages, and managing connection state change handlers.

type TaskCancelFunc

type TaskCancelFunc func()

TaskCancelFunc represents a function that will be called when a goroutine managed by the TaskManager exits or is canceled. It can be used to perform cleanup actions or release resources associated with the goroutine.

type TaskDataMsgFunc

type TaskDataMsgFunc func(msg *DataMessage, handler DataMessageHandler) bool

TaskDataMsgFunc represents a function that processes an HSMS data message and its associated handler within a goroutine managed by the TaskManager. It should return true to continue processing messages, or false to stop the goroutine.

type TaskFunc

type TaskFunc func() bool

TaskFunc represents a function that performs a task within a goroutine managed by the TaskManager. It should return true to continue running the task, or false to stop the goroutine.

type TaskManager

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

TaskManager manages the lifecycle of goroutines (tasks) within an HSMS application. It provides a structured way to start, stop, and wait for goroutines, ensuring proper cancellation and resource cleanup.

The TaskManager uses a context.Context to manage the lifecycle of the goroutines. When the context is canceled, all running goroutines are signaled to stop. The TaskManager also uses a sync.WaitGroup to wait for all goroutines to terminate before returning from the Wait() method.

Example Usage:

// Create a new TaskManager and use ctx as the parent context
taskMgr := hsms.NewTaskManager(ctx, logger)

// Start a goroutine
taskMgr.Start("myTask", func() bool {
    // ... task logic ...
    return true // Return true to continue running, false to stop
})

// ... other operations ...

// Stop all goroutines
taskMgr.Stop()

// Wait for all goroutines to terminate
taskMgr.Wait()

func NewTaskManager

func NewTaskManager(ctx context.Context, l logger.Logger) *TaskManager

NewTaskManager creates a new TaskManager with the given context as the parent context and logger.

func (*TaskManager) Start

func (mgr *TaskManager) Start(name string, taskFunc TaskFunc) error

Start starts a new goroutine with the given name and task function.

The taskFunc should return true to continue running, or false to stop the goroutine.

func (*TaskManager) StartInterval

func (mgr *TaskManager) StartInterval(name string, taskFunc TaskFunc, interval time.Duration, runNow bool) (*time.Ticker, error)

StartInterval starts a new goroutine that executes the given task function at the specified interval. If runNow is true, the task function is executed immediately before starting the interval. The function returns a *time.Ticker that can be used to stop the interval.

func (*TaskManager) StartReceiver

func (mgr *TaskManager) StartReceiver(name string, taskFunc TaskRecvFunc, taskCancelFunc TaskCancelFunc) error

StartReceiver starts a new goroutine with the given name, task function, and a cancel function.

The taskFunc should return true to continue running, or false to stop the goroutine.

The taskCancelFunc will be called when the goroutine exits or is canceled. StartReceiver starts a new goroutine with the given name, task function, and a cancel function.

func (*TaskManager) StartRecvDataMsg

func (mgr *TaskManager) StartRecvDataMsg(name string, taskFunc DataMessageHandler, session Session, inputChan chan *DataMessage) error

StartRecvDataMsg starts a new goroutine that receives HSMS data messages from the given channel.

The task function (DataMessageHandler) will be called for each received message.

func (*TaskManager) StartSender

func (mgr *TaskManager) StartSender(name string, taskFunc TaskMsgFunc, taskCancelFunc TaskCancelFunc, inputChan chan HSMSMessage) error

StartSender starts a new goroutine that receives HSMS messages from the given channel.

The taskFunc should return true to continue receiving messages, or false to stop the goroutine.

func (*TaskManager) Stop

func (mgr *TaskManager) Stop()

Stop signals all running goroutines.

func (*TaskManager) StopInterval added in v1.3.0

func (mgr *TaskManager) StopInterval(name string) error

StopInterval stops the interval task with the given name.

It returns an error if the task is not found or if the task is not a *time.Ticker.

func (*TaskManager) TaskCount

func (mgr *TaskManager) TaskCount() int

TaskCount returns the number of currently running goroutines.

func (*TaskManager) Wait

func (mgr *TaskManager) Wait()

Wait waits for all goroutines to terminate.

type TaskMsgFunc

type TaskMsgFunc func(msg HSMSMessage) bool

TaskMsgFunc represents a function that processes an HSMS message within a goroutine managed by the TaskManager. It should return true to continue processing messages, or false to stop the goroutine.

type TaskRecvFunc

type TaskRecvFunc func(msgLenBuf []byte) bool

TaskRecvFunc represents a function that performs a receive task within a goroutine managed by the TaskManager. It should return true to continue running the task, or false to stop the goroutine.

Jump to

Keyboard shortcuts

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