gosmpp

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2024 License: Apache-2.0 Imports: 15 Imported by: 11

README

gosmpp

Go Report Card Coverage Status godoc

SMPP (3.4) Client Library in pure Go.

This library is well tested with SMSC simulators:

Installation

go get -u github.com/linxGnu/gosmpp

Usage

Highlight
  • From v0.1.4, gosmpp is written in event-based style and fully-manage your smpp session, connection, error, rebinding, etc. You only need to implement some hooks:
		trans, err := gosmpp.NewSession(
		gosmpp.TRXConnector(gosmpp.NonTLSDialer, auth),
		gosmpp.Settings{
			EnquireLink: 5 * time.Second,

			ReadTimeout: 10 * time.Second,

			OnSubmitError: func(_ pdu.PDU, err error) {
				log.Fatal("SubmitPDU error:", err)
			},

			OnReceivingError: func(err error) {
				fmt.Println("Receiving PDU/Network error:", err)
			},

			OnRebindingError: func(err error) {
				fmt.Println("Rebinding but error:", err)
			},

			OnPDU: handlePDU(),

			OnClosed: func(state gosmpp.State) {
				fmt.Println(state)
			},
		}, 5*time.Second)
		if err != nil {
		  log.Println(err)
		}
		defer func() {
		  _ = trans.Close()
		}()
Version (0.1.4.RC+)
Old version (0.1.3 and previous)

Full example could be found: gist

Supported PDUs

  • bind_transmitter
  • bind_transmitter_resp
  • bind_receiver
  • bind_receiver_resp
  • bind_transceiver
  • bind_transceiver_resp
  • outbind
  • unbind
  • unbind_resp
  • submit_sm
  • submit_sm_resp
  • submit_sm_multi
  • submit_sm_multi_resp
  • data_sm
  • data_sm_resp
  • deliver_sm
  • deliver_sm_resp
  • query_sm
  • query_sm_resp
  • cancel_sm
  • cancel_sm_resp
  • replace_sm
  • replace_sm_resp
  • enquire_link
  • enquire_link_resp
  • alert_notification
  • generic_nack

Documentation

Index

Constants

View Source
const (
	Alive int32 = iota
	Closed
)

Variables

View Source
var (
	ErrWindowSizeEqualZero                   = errors.New("request window size cannot be 0")
	ErrExpireCheckTimerNotSet                = errors.New("ExpireCheckTimer cannot be 0 if PduExpireTimeOut is set")
	ErrStoreAccessTimeOutEqualZero           = errors.New("StoreAccessTimeOut window size cannot be 0")
	ErrWindowSizeNotAvailableOnReceiverBinds = errors.New("window size not available on receiver binds")
)
View Source
var (
	// ErrConnectionClosing indicates transmitter is closing. Can not send any PDU.
	ErrConnectionClosing = errors.New("connection is closing, can not send PDU to SMSC")
	ErrWindowsFull       = errors.New("window full")
)
View Source
var (
	ErrWindowNotConfigured = errors.New("window settings not configured")
)
View Source
var (
	// NonTLSDialer is non-tls connection dialer.
	NonTLSDialer = func(addr string) (net.Conn, error) {
		return net.Dial("tcp", addr)
	}
)

Functions

func WithAddressRange added in v0.2.0

func WithAddressRange(addressRange pdu.AddressRange) connectorOption

Types

type AllPDUCallback added in v0.1.10

type AllPDUCallback func(pdu pdu.PDU) (responsePdu pdu.PDU, closeBind bool)

AllPDUCallback handles all received PDU.

This pdu is NOT responded to automatically, manual response/handling is needed and the bind can be closed by retuning true on closeBind.

type Auth added in v0.1.4

type Auth struct {
	// SMSC is SMSC address.
	SMSC       string
	SystemID   string
	Password   string
	SystemType string
}

Auth represents basic authentication to SMSC.

type BindError added in v0.1.6

type BindError struct {
	CommandStatus data.CommandStatusType
}

func (BindError) Error added in v0.1.6

func (err BindError) Error() string

type ClosedCallback added in v0.1.4

type ClosedCallback func(State)

ClosedCallback notifies closed event due to State.

type Connection

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

Connection wraps over net.Conn with buffered data reader.

func NewConnection added in v0.1.4

func NewConnection(conn net.Conn) (c *Connection)

NewConnection returns a Connection.

func (*Connection) Close added in v0.1.4

func (c *Connection) Close() error

Close closes the connection. Any blocked Read or Write operations will be unblocked and return errors.

func (*Connection) LocalAddr added in v0.1.4

func (c *Connection) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*Connection) Read added in v0.1.4

func (c *Connection) Read(b []byte) (n int, err error)

Read reads data from the connection. Read can be made to time out and return an Error with Timeout() == true after a fixed time limit; see SetDeadline and SetReadDeadline.

func (*Connection) RemoteAddr added in v0.1.4

func (c *Connection) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*Connection) SetDeadline added in v0.1.4

func (c *Connection) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

A deadline is an absolute time after which I/O operations fail with a timeout (see type Error) instead of blocking. The deadline applies to all future and pending I/O, not just the immediately following call to Read or Write. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.

An idle timeout can be implemented by repeatedly extending the deadline after successful Read or Write calls.

A zero value for t means I/O operations will not time out.

Note that if a TCP connection has keep-alive turned on, which is the default unless overridden by Dialer.KeepAlive or ListenConfig.KeepAlive, then a keep-alive failure may also return a timeout error. On Unix systems a keep-alive failure on I/O can be detected using errors.Is(err, syscall.ETIMEDOUT).

func (*Connection) SetReadDeadline added in v0.1.4

func (c *Connection) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out.

func (*Connection) SetReadTimeout added in v0.1.4

func (c *Connection) SetReadTimeout(t time.Duration) error

SetReadTimeout is equivalent to ReadDeadline(now + timeout)

func (*Connection) SetWriteDeadline added in v0.1.4

func (c *Connection) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for future Write calls and any currently-blocked Write call. Even if write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means Write will not time out.

func (*Connection) SetWriteTimeout added in v0.1.4

func (c *Connection) SetWriteTimeout(t time.Duration) error

SetWriteTimeout is equivalent to WriteDeadline(now + timeout)

func (*Connection) Write added in v0.1.4

func (c *Connection) Write(b []byte) (n int, err error)

Write writes data to the connection. Write can be made to time out and return an Error with Timeout() == true after a fixed time limit; see SetDeadline and SetWriteDeadline.

func (*Connection) WritePDU added in v0.1.4

func (c *Connection) WritePDU(p pdu.PDU) (n int, err error)

WritePDU data to the connection.

type Connector added in v0.1.4

type Connector interface {
	Connect() (conn *Connection, err error)
	GetBindType() pdu.BindingType
}

Connector is connection factory interface.

func RXConnector added in v0.1.4

func RXConnector(dialer Dialer, auth Auth, opts ...connectorOption) Connector

RXConnector returns a Receiver (RX) connector.

func TRXConnector added in v0.1.4

func TRXConnector(dialer Dialer, auth Auth, opts ...connectorOption) Connector

TRXConnector returns a Transceiver (TRX) connector.

func TXConnector added in v0.1.4

func TXConnector(dialer Dialer, auth Auth) Connector

TXConnector returns a Transmitter (TX) connector.

type DefaultStore added in v0.3.0

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

func NewDefaultStore added in v0.3.0

func NewDefaultStore() DefaultStore

func (DefaultStore) Clear added in v0.3.0

func (s DefaultStore) Clear(ctx context.Context) error

func (DefaultStore) Delete added in v0.3.0

func (s DefaultStore) Delete(ctx context.Context, sequenceNumber int32) error

func (DefaultStore) Get added in v0.3.0

func (s DefaultStore) Get(ctx context.Context, sequenceNumber int32) (Request, bool)

func (DefaultStore) Length added in v0.3.0

func (s DefaultStore) Length(ctx context.Context) (int, error)

func (DefaultStore) List added in v0.3.0

func (s DefaultStore) List(ctx context.Context) []Request

func (DefaultStore) Set added in v0.3.0

func (s DefaultStore) Set(ctx context.Context, request Request) error

type Dialer added in v0.1.4

type Dialer func(addr string) (net.Conn, error)

Dialer is connection dialer.

type ErrorCallback added in v0.1.4

type ErrorCallback func(error)

ErrorCallback notifies happened error while reading PDU.

type PDUCallback added in v0.1.4

type PDUCallback func(pdu pdu.PDU, responded bool)

PDUCallback handles received PDU.

type PDUErrorCallback added in v0.1.4

type PDUErrorCallback func(pdu pdu.PDU, err error)

PDUErrorCallback notifies fail-to-submit PDU with along error.

type RebindCallback added in v0.1.10

type RebindCallback func()

RebindCallback notifies rebind event due to State.

type Receiver

type Receiver interface {
	io.Closer
	SystemID() string
}

Receiver interface.

type Request added in v0.3.0

type Request struct {
	pdu.PDU
	TimeSent time.Time
}

Request represent a request tracked by the RequestStore

type RequestStore added in v0.3.0

type RequestStore interface {
	Set(ctx context.Context, request Request) error
	Get(ctx context.Context, sequenceNumber int32) (Request, bool)
	List(ctx context.Context) []Request
	Delete(ctx context.Context, sequenceNumber int32) error
	Clear(ctx context.Context) error
	Length(ctx context.Context) (int, error)
}

RequestStore interface used for WindowedRequestTracking

type Response added in v0.3.0

type Response struct {
	pdu.PDU
	OriginalRequest Request
}

Response represents a response from a Request in the RequestStore

type Session

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

Session represents session for TX, RX, TRX.

func NewSession added in v0.1.4

func NewSession(c Connector, settings Settings, rebindingInterval time.Duration, opts ...SessionOption) (session *Session, err error)

NewSession creates new session for TX, RX, TRX.

Session will `non-stop`, automatically rebind (create new and authenticate connection with SMSC) when unexpected error happened.

`rebindingInterval` indicates duration that Session has to wait before rebinding again.

Setting `rebindingInterval <= 0` will disable `auto-rebind` functionality.

func (*Session) Close

func (s *Session) Close() (err error)

Close session.

func (*Session) GetWindowSize added in v0.3.0

func (s *Session) GetWindowSize() (int, error)

func (*Session) Receiver added in v0.1.4

func (s *Session) Receiver() Receiver

Receiver returns bound Receiver.

func (*Session) Transceiver added in v0.1.4

func (s *Session) Transceiver() Transceiver

Transceiver returns bound Transceiver.

func (*Session) Transmitter added in v0.1.4

func (s *Session) Transmitter() Transmitter

Transmitter returns bound Transmitter.

type SessionOption added in v0.3.0

type SessionOption func(session *Session)

func WithRequestStore added in v0.3.0

func WithRequestStore(store RequestStore) SessionOption

type Settings added in v0.1.4

type Settings struct {
	// ReadTimeout is timeout for reading PDU from SMSC.
	// Underlying net.Conn will be stricted with ReadDeadline(now + timeout).
	// This setting is very important to detect connection failure.
	//
	// Must: ReadTimeout > max(0, EnquireLink)
	ReadTimeout time.Duration

	// WriteTimeout is timeout for submitting PDU.
	WriteTimeout time.Duration

	// EnquireLink periodically sends EnquireLink to SMSC.
	// The duration must not be smaller than 1 minute.
	//
	// Zero duration disables auto enquire link.
	EnquireLink time.Duration

	// OnPDU handles received PDU from SMSC.
	//
	// `Responded` flag indicates this pdu is responded automatically,
	// no manual respond needed.
	//
	// Will be ignored if OnAllPDU or WindowedRequestTracking is set
	OnPDU PDUCallback

	// OnAllPDU handles all received PDU from SMSC.
	//
	// This pdu is NOT responded to automatically,
	// manual response/handling is needed
	//
	// User can also decide to close bind by retuning true, default is false
	//
	// Will be ignored if WindowedRequestTracking is set
	OnAllPDU AllPDUCallback

	// OnReceivingError notifies happened error while reading PDU
	// from SMSC.
	OnReceivingError ErrorCallback

	// OnSubmitError notifies fail-to-submit PDU with along error.
	OnSubmitError PDUErrorCallback

	// OnRebindingError notifies error while rebinding.
	OnRebindingError ErrorCallback

	// OnClosed notifies `closed` event due to State.
	OnClosed ClosedCallback

	// OnRebind notifies `rebind` event due to State.
	OnRebind RebindCallback

	// SMPP Bind Window tracking feature config
	*WindowedRequestTracking
	// contains filtered or unexported fields
}

Settings for TX (transmitter), RX (receiver), TRX (transceiver).

type State added in v0.1.4

type State byte

State represents Transmitter/Receiver/Transceiver state.

const (
	// ExplicitClosing indicates that Transmitter/Receiver/Transceiver is closed
	// explicitly (from outside).
	ExplicitClosing State = iota

	// StoppingProcessOnly stops daemons but does not close underlying net conn.
	StoppingProcessOnly

	// InvalidStreaming indicates Transceiver/Receiver data reading state is
	// invalid due to network connection or SMSC responsed with an invalid PDU
	// which potentially damages other following PDU(s).
	//
	// In both cases, Transceiver/Receiver is closed implicitly.
	InvalidStreaming

	// ConnectionIssue indicates that Transmitter/Receiver/Transceiver is closed
	// due to network connection issue or SMSC is not available anymore.
	ConnectionIssue

	// UnbindClosing indicates Receiver got unbind request from SMSC and closed due to this request.
	UnbindClosing
)

func (*State) String added in v0.1.4

func (s *State) String() string

String interface.

type TransceivableOption added in v0.3.0

type TransceivableOption func(session *Session)

type Transceiver added in v0.1.4

type Transceiver interface {
	io.Closer
	Submit(pdu.PDU) error
	SystemID() string
}

Transceiver interface.

type Transmitter

type Transmitter interface {
	io.Closer
	Submit(pdu.PDU) error
	SystemID() string
}

Transmitter interface.

type WindowedRequestTracking added in v0.3.0

type WindowedRequestTracking struct {

	// OnReceivedPduRequest handles received PDU request from SMSC.
	//
	// User can also decide to close bind by retuning true, default is false
	OnReceivedPduRequest AllPDUCallback

	// OnExpectedPduResponse handles expected PDU response from SMSC.
	// Only triggered when the original request is found in the window cache
	//
	// Handle is optional
	// If not set, response will be dropped
	OnExpectedPduResponse func(Response)

	// OnUnexpectedPduResponse handles unexpected PDU response from SMSC.
	// Only triggered if the original request is not found in the window cache
	//
	// Handle is optional
	// If not set, response will be dropped
	OnUnexpectedPduResponse func(pdu.PDU)

	// OnExpiredPduRequest handles expired PDU request with no response received
	//
	// Mandatory: the PduExpireTimeOut must be set
	// Handle is optional
	// If not set, expired PDU will be removed from cache
	// the bind can be closed by retuning true on closeBind.
	OnExpiredPduRequest func(pdu.PDU) (closeBind bool)

	// OnClosePduRequest will return all PDU request found in the store when the bind closes
	OnClosePduRequest func(pdu.PDU)

	// Set the number of second to expire a request sent to the SMSC
	//
	// Zero duration disables pdu expire check and the cache may fill up over time with expired PDU request
	// Recommended: eual or less to the value set in ReadTimeout + EnquireLink
	PduExpireTimeOut time.Duration

	// The time period between each check of the expired PDU in the cache
	//
	// Zero duration disables pdu expire check and the cache may fill up over time with expired PDU request
	// Recommended: Less or half the time set in for PduExpireTimeOut
	// Don't be too aggressive, there is a performance hit if the check is done often
	ExpireCheckTimer time.Duration

	// The maximum number of pending request sent to the SMSC
	//
	// Maximum value is 255
	MaxWindowSize uint8

	// if enabled, EnquireLink and Unbind request will be responded to automatically
	EnableAutoRespond bool

	// Set the number of millisecond to expire a request to store or retrieve data from request store
	//
	// Value must be greater than 0
	// 200 to 1000 is a good starting point
	StoreAccessTimeOut time.Duration
}

WindowedRequestTracking settings for TX (transmitter) and TRX (transceiver) request store.

Jump to

Keyboard shortcuts

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