emitter

package module
Version: v0.0.0-...-f787d04 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2018 License: EPL-1.0 Imports: 9 Imported by: 0

README

Emitter Golang SDK api documentation

This repository contains Go/Golang client for Emitter (see also on Emitter GitHub). Emitter is an open-source real-time communication service for connecting online devices. At its core, emitter.io is a distributed, scalable and fault-tolerant publish-subscribe messaging platform based on MQTT protocol and featuring message storage.

This library provides a nicer MQTT interface fine-tuned and extended with specific features provided by Emitter. The code uses the Eclipse Paho MQTT Go Client for handling all the network communication and MQTT protocol, and is released under the same license (EPL v1).

Usage

This library aims to be as simple and straighforward as possible. First thing you'll need to do is to import it.

import emitter "github.com/emitter-io/go"

Then, you can use the functions exposed by Emitter type - they are simple methods such as Connect, Publish, Subscribe, Unsubscribe, GenerateKey, Presence, etc. See the example below.

func main() {
	// Create the options with default values
	o := emitter.NewClientOptions()

	// Set the message handler
	o.SetOnMessageHandler(func(client emitter.Emitter, msg emitter.Message) {
		fmt.Printf("Received message: %s\n", msg.Payload())
	})

	// Set the presence notification handler
	o.SetOnPresenceHandler(func(_ emitter.Emitter, p emitter.PresenceEvent) {
		fmt.Printf("Occupancy: %v\n", p.Occupancy)
	})

	// Create a new emitter client and connect to the broker
	c := emitter.NewClient(o)
	sToken := c.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		panic("Error on Client.Connect(): " + sToken.Error().Error())
	}

	// Subscribe to the presence demo channel
	c.Subscribe("X4-nUeHjiAygHMdN8wst82S3c2KcCMn7", "presence-demo/1")

	// Publish to the channel
	c.Publish("X4-nUeHjiAygHMdN8wst82S3c2KcCMn7", "presence-demo/1", "hello")

	// Ask for presence
	r := emitter.NewPresenceRequest()
	r.Key = "X4-nUeHjiAygHMdN8wst82S3c2KcCMn7"
	r.Channel = "presence-demo/1"
	c.Presence(r)
}

Installation and Build

This client, similarly to the Eclipse Paho client is designed to work with the standard Go tools, so installation is as easy as:

go get -u github.com/emitter-io/go

For usage, please refer to the sample sub-folder in this repository which provides a sample application on how to use the API.

API Documentation

The full API documentation of exported members is available on godoc.org/github.com/emitter-io/go.

License

Licensed with EPL 1.0, similarly to Eclipse Paho MQTT Client.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ClientOptions

type ClientOptions struct {
	Servers              []*url.URL
	ClientID             string
	Username             string
	Password             string
	TLSConfig            *tls.Config
	KeepAlive            time.Duration
	PingTimeout          time.Duration
	ConnectTimeout       time.Duration
	MaxReconnectInterval time.Duration
	AutoReconnect        bool
	OnMessage            OnMessageHandler
	OnConnect            OnConnectHandler
	OnConnectionLost     OnConnectionLostHandler
	OnKeyGen             OnKeyGenHandler
	OnPresence           OnPresenceHandler
}

ClientOptions contains configurable options for an Client.

func NewClientOptions

func NewClientOptions() *ClientOptions

NewClientOptions will create a new ClientClientOptions type with some default values.

func (*ClientOptions) AddBroker

func (o *ClientOptions) AddBroker(server string) *ClientOptions

AddBroker adds a broker URI to the list of brokers to be used. The format should be scheme://host:port Where "scheme" is one of "tcp", "ssl", or "ws", "host" is the ip-address (or hostname) and "port" is the port on which the broker is accepting connections.

func (*ClientOptions) SetAutoReconnect

func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions

SetAutoReconnect sets whether the automatic reconnection logic should be used when the connection is lost, even if disabled the ConnectionLostHandler is still called

func (*ClientOptions) SetClientID

func (o *ClientOptions) SetClientID(id string) *ClientOptions

SetClientID will set the client id to be used by this client when connecting to the MQTT broker. According to the MQTT v3.1 specification, a client id mus be no longer than 23 characters.

func (*ClientOptions) SetConnectTimeout

func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions

SetConnectTimeout limits how long the client will wait when trying to open a connection to an MQTT server before timeing out and erroring the attempt. A duration of 0 never times out. Default 30 seconds. Currently only operational on TCP/TLS connections.

func (*ClientOptions) SetKeepAlive

func (o *ClientOptions) SetKeepAlive(k time.Duration) *ClientOptions

SetKeepAlive will set the amount of time (in seconds) that the client should wait before sending a PING request to the broker. This will allow the client to know that a connection has not been lost with the server.

func (*ClientOptions) SetMaxReconnectInterval

func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions

SetMaxReconnectInterval sets the maximum time that will be waited between reconnection attempts when connection is lost

func (*ClientOptions) SetOnConnectHandler

func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions

SetOnConnectHandler sets the function to be called when the client is connected. Both at initial connection time and upon automatic reconnect.

func (*ClientOptions) SetOnConnectionLostHandler

func (o *ClientOptions) SetOnConnectionLostHandler(onLost OnConnectionLostHandler) *ClientOptions

SetOnConnectionLostHandler will set the OnConnectionLost callback to be executed in the case where the client unexpectedly loses connection with the MQTT broker.

func (*ClientOptions) SetOnKeyGenHandler

func (o *ClientOptions) SetOnKeyGenHandler(handler OnKeyGenHandler) *ClientOptions

SetOnKeyGenHandler sets the OnKeyGenHandler that will be called when a key generation response is received.

func (*ClientOptions) SetOnMessageHandler

func (o *ClientOptions) SetOnMessageHandler(defaultHandler OnMessageHandler) *ClientOptions

SetOnMessageHandler sets the MessageHandler that will be called when a message is received that does not match any known subscriptions.

func (*ClientOptions) SetOnPresenceHandler

func (o *ClientOptions) SetOnPresenceHandler(handler OnPresenceHandler) *ClientOptions

SetOnPresenceHandler sets the OnPresenceHandler that will be called when a presence event is received.

func (*ClientOptions) SetPassword

func (o *ClientOptions) SetPassword(p string) *ClientOptions

SetPassword will set the password to be used by this client when connecting to the MQTT broker. Note: without the use of SSL/TLS, this information will be sent in plaintext accross the wire.

func (*ClientOptions) SetPingTimeout

func (o *ClientOptions) SetPingTimeout(k time.Duration) *ClientOptions

SetPingTimeout will set the amount of time (in seconds) that the client will wait after sending a PING request to the broker, before deciding that the connection has been lost. Default is 10 seconds.

func (*ClientOptions) SetTLSConfig

func (o *ClientOptions) SetTLSConfig(t *tls.Config) *ClientOptions

SetTLSConfig will set an SSL/TLS configuration to be used when connecting to an MQTT broker. Please read the official Go documentation for more information.

func (*ClientOptions) SetUsername

func (o *ClientOptions) SetUsername(u string) *ClientOptions

SetUsername will set the username to be used by this client when connecting to the MQTT broker. Note: without the use of SSL/TLS, this information will be sent in plaintext accross the wire.

type Emitter

type Emitter interface {
	IsConnected() bool
	Connect() Token
	Disconnect(uint)
	Publish(string, string, interface{}, ...Option) Token
	PublishWithTTL(string, string, interface{}, int) Token
	Subscribe(string, string, ...Option) Token
	SubscribeWithHistory(string, string, int) Token
	Unsubscribe(string, string, ...Option) Token
	Presence(*PresenceRequest) Token
	GenerateKey(*KeyGenRequest) Token
}

Emitter defines the externals that a message implementation must support these are received messages that are passed to the callbacks, not internal messages

func NewClient

func NewClient(o *ClientOptions) Emitter

NewClient will create an MQTT v3.1.1 client with all of the options specified in the provided ClientOptions. The client must have the Connect method called on it before it may be used. This is to make sure resources (such as a net connection) are created before the application is actually ready.

type KeyGenRequest

type KeyGenRequest struct {
	Key     string `json:"key"`
	Channel string `json:"channel"`
	Type    string `json:"type"`
	TTL     int    `json:"ttl"`
}

KeyGenRequest represents a request that can be sent to emitter broker in order to generate a new channel key.

func NewKeyGenRequest

func NewKeyGenRequest() *KeyGenRequest

NewKeyGenRequest creates a new KeyGenRequest type with some default values.

type KeyGenResponse

type KeyGenResponse struct {
	Status       int    `json:"status"`
	Key          string `json:"key"`
	Channel      string `json:"channel"`
	ErrorMessage string `json:"message"`
}

KeyGenResponse represents a response from emitter broker which contains the response to the key generation request.

type Message

type Message interface {
	Topic() string
	Payload() []byte
}

Message defines the externals that a message implementation must support these are received messages that are passed to the callbacks, not internal messages

type OnConnectHandler

type OnConnectHandler func(Emitter)

OnConnectHandler is a callback that is called when the client state changes from unconnected/disconnected to connected. Both at initial connection and on reconnection

type OnConnectionLostHandler

type OnConnectionLostHandler func(Emitter, error)

OnConnectionLostHandler is a callback type which can be set to be executed upon an unintended disconnection from the MQTT broker. Disconnects caused by calling Disconnect or ForceDisconnect will not cause an OnConnectionLost callback to execute.

type OnKeyGenHandler

type OnKeyGenHandler func(Emitter, KeyGenResponse)

OnKeyGenHandler is a callback type which can be set to be executed upon the arrival of key generation responses.

type OnMessageHandler

type OnMessageHandler func(Emitter, Message)

OnMessageHandler is a callback type which can be set to be executed upon the arrival of messages published to topics to which the client is subscribed.

type OnPresenceHandler

type OnPresenceHandler func(Emitter, PresenceEvent)

OnPresenceHandler is a callback type which can be set to be executed upon the arrival of presence events.

type Option

type Option struct {
	Key   string
	Value string
}

Option represents a key/value pair that can be supplied to the publish/subscribe or unsubscribe methods and provide ways to configure the operation.

type PresenceEvent

type PresenceEvent struct {
	Event     string         `json:"event"`
	Channel   string         `json:"channel"`
	Occupancy int            `json:"occupancy"`
	Time      int            `json:"time"`
	Who       []PresenceInfo `json:"who"`
}

PresenceEvent represents a response from emitter broker which contains presence state or a join/leave notification.

type PresenceInfo

type PresenceInfo struct {
	ID       string `json:"id"`
	Username string `json:"username"`
}

PresenceInfo represents a response from emitter broker which contains presence information.

type PresenceRequest

type PresenceRequest struct {
	Key     string `json:"key"`
	Channel string `json:"channel"`
	Status  bool   `json:"status"`
	Changes bool   `json:"changes"`
}

PresenceRequest represents a request that can be sent to emitter broker in order to request presence information.

func NewPresenceRequest

func NewPresenceRequest() *PresenceRequest

NewPresenceRequest creates a new PresenceRequest type with some default values.

type Token

type Token interface {
	Wait() bool
	WaitTimeout(time.Duration) bool
	Error() error
}

Token defines the interface for the tokens used to indicate when actions have completed.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL