gsmtcp

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2019 License: MIT Imports: 21 Imported by: 0

README

gsmtcp

A golang library for TCP communication over an embedded GSM device. It was primarily developed with the SIM800 series of devices interfacing with Raspberry Pi, and is still very much a work in progress.

Usage example

When working with a Raspberry Pi, for example, the peripheral drivers must first be initialised. Utilising periph.io:

pState, err := host.Init()
if err != nil {
    log.Error(err)
    os.Exit(1)
}
for _, d := range pState.Failed {
    log.Warn("failed to load", d.String(), ":", d.Err.Error())
}

The GSM module can then be created and initialised:

g, err := gsm.NewGsmModule("/dev/ttyS0")
if err != nil {
    log.Error(err)
    return
}

err = g.Init()
if err != nil {
    log.Error(err)
    return
}
defer func() {
    err := g.Shutdown()
    if err != nil {
        log.Error(err)
    }
}()

A TCP connection can now be created:

conn, err := gsm.NewConnection(g, "<IPv4>:<PORT>")
if err != nil {
    log.Error("could not establish a new connection", err)
    os.Exit(1)
}
defer func() {
    err := conn.Close()
    if err != nil {
        log.Error(err.Error())
    }
    time.Sleep(1 * time.Second)
}()

Establishing a TLS connection

A secure connection can be established by utilising golang's standard libraries:

tlsConfig := &tls.Config{
    Certificates: []tls.Certificate{*cert},
    VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
        for _, chain := range verifiedChains {
            for _, c := range chain {
                // peer certificate verification
            }
        }
        return nil
    },
    InsecureSkipVerify: true,
    Rand:               rand.Reader,
    MinVersion:         tls.VersionTLS12,
}

tlsConn := tls.Client(conn, tlsConfig)
defer func() {
    err := tlsConn.Close()
    if err != nil {
        log.Error(err)
    }
}()

If the TLS TCP connection will be used as-is to send raw data, the handshake can be established as follows:


// perform the handshake
err = tlsConn.Handshake()
if err != nil {
    log.Error(err)
}

The certificate (*cert) can be generated with the help of Talisman.

JSON-RPC

var reply greeter.HelloReply
err = gsmtcp.DoRequest("https://some-server", tlsConn, 
	"Greeter.SayHello",greeter.HelloRequest{Name: "Homer"}, &reply)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DoRequest added in v0.2.0

func DoRequest(url string, conn *tls.Conn, method string, param interface{}, reply interface{}) error

DoRequest executes a JSON-RPC request with the provided param. A pointer to the result reply must be given for the response to be unmarshalled.

func EncodeClientRequest added in v0.2.0

func EncodeClientRequest(method string, args interface{}) ([]byte, error)

EncodeClientRequest encodes parameters for a JSON-RPC client request.

func NewConnection

func NewConnection(g *DefaultGsmModule, address string) (net.Conn, error)

func NewReader

func NewReader(c net.Conn) io.Reader

Types

type APN added in v0.2.0

type APN string

func (APN) Default added in v0.2.0

func (APN) Default() interface{}

func (APN) Type added in v0.2.0

func (APN) Type() ConfigType

func (APN) Value added in v0.2.0

func (c APN) Value() interface{}

type AlreadyConnectedErr

type AlreadyConnectedErr struct {
}

func (AlreadyConnectedErr) Error

func (e AlreadyConnectedErr) Error() string

type Baud

type Baud int

func (Baud) Default

func (Baud) Default() interface{}

func (Baud) Type

func (b Baud) Type() ConfigType

func (Baud) Value

func (b Baud) Value() interface{}

type ClientRequest added in v0.2.0

type ClientRequest struct {
	JsonRpc string         `json:"jsonrpc"`
	Method  string         `json:"method"`
	Params  [1]interface{} `json:"params"`
	Id      string         `json:"id"`
}

ClientRequest represents a JSON-RPC request sent by a client.

type ClientResponse added in v0.2.0

type ClientResponse struct {
	JsonRpc string           `json:"jsonrpc"`
	Result  *json.RawMessage `json:"result"`
	Error   interface{}      `json:"error"`
	Id      string           `json:"id"`
}

ClientResponse represents a JSON-RPC response returned to a client.

type Command

type Command string
const CheckNetworkRegistrationCommand Command = `AT+CGREG?`
const ConnectCommand Command = `AT+CIPSTART="TCP", "%s", "%s"`
const ConnectionStateCommand Command = `AT+CIPSTATUS`
const DisconnectCommand Command = `AT+CIPCLOSE`
const EchoOffCommand Command = `ATE0`
const EchoOnCommand Command = `ATE1`
const GetLocalIPAddressCommand Command = `AT+CIFSR`
const SendCommand Command = `AT+CIPSEND`
const StatusCommand Command = `AT`

type Config

type Config interface {
	Type() ConfigType
	Value() interface{}
	Default() interface{}
}

type ConfigType

type ConfigType string
const APNConfig ConfigType = "APNConfig"
const BaudConfig ConfigType = "Baud"
const NetworkRegistrationRetriesConfig ConfigType = "NetworkRegistrationRetriesConfig"
const NetworkRegistrationRetryDelayConfig ConfigType = "NetworkRegistrationRetryDelayConfig"
const SendTimeoutConfig ConfigType = "SendTimeoutConfig"
const VerboseConfig ConfigType = "VerboseConfig"

type Conn

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

func (Conn) Close

func (c Conn) Close() error

func (Conn) LocalAddr

func (c Conn) LocalAddr() net.Addr

func (Conn) Read

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

func (Conn) RemoteAddr

func (c Conn) RemoteAddr() net.Addr

func (Conn) SetDeadline

func (c Conn) SetDeadline(t time.Time) error

func (Conn) SetReadDeadline

func (c Conn) SetReadDeadline(t time.Time) error

func (Conn) SetWriteDeadline

func (c Conn) SetWriteDeadline(t time.Time) error

func (Conn) Write

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

type DefaultGsmModule

type DefaultGsmModule struct {
	TotalDeadline time.Time
	ReadDeadline  time.Time
	WriteDeadline time.Time
	// contains filtered or unexported fields
}

func NewGsmModule

func NewGsmModule(device string, configs ...Config) (*DefaultGsmModule, error)

NewGsmModule opens a serial connection to the provided serial device.

func (*DefaultGsmModule) CloseGsmModule

func (g *DefaultGsmModule) CloseGsmModule()

CloseGsmModule closes the serial connection to the GSM module.

func (*DefaultGsmModule) CloseTcpConnection

func (g *DefaultGsmModule) CloseTcpConnection() error

CloseTcpConnection closes the current connection.

func (*DefaultGsmModule) CommandEchoOff added in v0.0.13

func (g *DefaultGsmModule) CommandEchoOff() error

CommandEchoOff turns off the echoing of commands

func (*DefaultGsmModule) CommandEchoOn added in v0.0.13

func (g *DefaultGsmModule) CommandEchoOn() error

CommandEchoOn turns on the echoing of commands

func (*DefaultGsmModule) GetLocalIPAddress

func (g *DefaultGsmModule) GetLocalIPAddress() (string, error)

GetLocalIPAddress

func (*DefaultGsmModule) GetStatus

func (g *DefaultGsmModule) GetStatus() (bool, error)

GetStatus determines the status of the module.

func (*DefaultGsmModule) Init

func (g *DefaultGsmModule) Init() error

Init checks the GSM module status, and switches it on if it was off; It then waits for network registration.

func (*DefaultGsmModule) IsConnected

func (g *DefaultGsmModule) IsConnected() (bool, error)

IsConnected determines if a connection is currently established.

func (*DefaultGsmModule) OpenTcpConnection

func (g *DefaultGsmModule) OpenTcpConnection(address string) error

OpenTcpConnection attempts to establish a new connection to the given IP and port.

func (*DefaultGsmModule) ReadData

func (g *DefaultGsmModule) ReadData() (byte, error)

func (*DefaultGsmModule) SendRawTcpData

func (g *DefaultGsmModule) SendRawTcpData(data []byte) (int, error)

SendRawTcpData sends the given data to to open connection.

func (*DefaultGsmModule) Shutdown

func (g *DefaultGsmModule) Shutdown() error

Shutdown switches the GSM module off.

func (*DefaultGsmModule) SwitchGNSSPowerOff added in v0.2.0

func (g *DefaultGsmModule) SwitchGNSSPowerOff() error

func (*DefaultGsmModule) SwitchGNSSPowerOn added in v0.2.0

func (g *DefaultGsmModule) SwitchGNSSPowerOn() error

func (*DefaultGsmModule) ToggleModule

func (g *DefaultGsmModule) ToggleModule() error

ToggleModule toggles the PWRKEY pin of the module.

func (*DefaultGsmModule) WaitForNetworkRegistration

func (g *DefaultGsmModule) WaitForNetworkRegistration() error

WaitForNetworkRegistration waits for the GSM module to be registered with the network.

type Error added in v0.2.0

type Error struct {
	Data interface{}
}

Error represents an arbitrary error value returned by a JSON-RPC request.

func (*Error) Error added in v0.2.0

func (e *Error) Error() string

type MaxBytesErr added in v0.2.0

type MaxBytesErr struct {
}

func (MaxBytesErr) Error added in v0.2.0

func (e MaxBytesErr) Error() string

type NetworkRegistrationRetries

type NetworkRegistrationRetries int

func (NetworkRegistrationRetries) Default

func (NetworkRegistrationRetries) Default() interface{}

func (NetworkRegistrationRetries) Type

func (NetworkRegistrationRetries) Value

func (c NetworkRegistrationRetries) Value() interface{}

type NetworkRegistrationRetryDelay

type NetworkRegistrationRetryDelay time.Duration

func (NetworkRegistrationRetryDelay) Default

func (NetworkRegistrationRetryDelay) Default() interface{}

func (NetworkRegistrationRetryDelay) Type

func (NetworkRegistrationRetryDelay) Value

func (c NetworkRegistrationRetryDelay) Value() interface{}

type NetworkRegistrationStatus

type NetworkRegistrationStatus string
const NotRegistered NetworkRegistrationStatus = "0"
const RegisteredHome NetworkRegistrationStatus = "1"
const RegisteredRoaming NetworkRegistrationStatus = "5"
const RegistrationDenied NetworkRegistrationStatus = "3"
const TryingToRegister NetworkRegistrationStatus = "2"
const UnknownRegistrationError NetworkRegistrationStatus = "4"

type NotReadyErr

type NotReadyErr struct {
}

func (NotReadyErr) Error

func (e NotReadyErr) Error() string

type Reader

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

func (Reader) Read

func (r Reader) Read(p []byte) (n int, err error)

type ResponseMessage

type ResponseMessage string
const AlreadyConnectedResponse ResponseMessage = "ALREADY CONNECT"
const CloseOkResponse ResponseMessage = "CLOSE OK"
const ConnectFailedResponse ResponseMessage = "CONNECT FAIL"
const ConnectOkResponse ResponseMessage = "CONNECT OK"
const ErrorResponse ResponseMessage = "ERROR"
const OkResponse ResponseMessage = "OK"
const SendOkResponse ResponseMessage = "SEND OK"
const StateConnectOkResponse ResponseMessage = "STATE: CONNECT OK"
const StateTcpClosedResponse ResponseMessage = "STATE: TCP CLOSED"

type SendTimeout added in v0.0.6

type SendTimeout time.Duration

func (SendTimeout) Default added in v0.0.6

func (SendTimeout) Default() interface{}

func (SendTimeout) Type added in v0.0.6

func (SendTimeout) Type() ConfigType

func (SendTimeout) Value added in v0.0.6

func (c SendTimeout) Value() interface{}

type TimedOutErr

type TimedOutErr struct {
}

func (TimedOutErr) Error

func (e TimedOutErr) Error() string

type Transport added in v0.2.0

type Transport struct {
	Conn net.Conn
}

Transport is a custom implementation of the Transport interface for utilising an existing TLS connection.

func (Transport) RoundTrip added in v0.2.0

func (r Transport) RoundTrip(req *http.Request) (*http.Response, error)

type Verbose added in v0.0.8

type Verbose bool

func (Verbose) Default added in v0.0.8

func (Verbose) Default() interface{}

func (Verbose) Type added in v0.0.8

func (Verbose) Type() ConfigType

func (Verbose) Value added in v0.0.8

func (c Verbose) Value() interface{}

Jump to

Keyboard shortcuts

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