• Stars
    star
    346
  • Rank 122,430 (Top 3 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Pure Go MQTT Client

GMQ - Pure Go MQTT Client

wercker status Build status Coverage Status GoDoc ![Gitter](https://badges.gitter.im/Join Chat.svg)

Overview

GMQ is a pure Go MQTT client. This library is compatible with MQTT Version 3.1.1. This library provides both a Go package and a command line application.

Installation

$ go get -u github.com/yosssi/gmq/...

MQTT Client Go Package

Example

package main

import (
	"fmt"
	"os"
	"os/signal"

	"github.com/yosssi/gmq/mqtt"
	"github.com/yosssi/gmq/mqtt/client"
)

func main() {
	// Set up channel on which to send signal notifications.
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, os.Interrupt, os.Kill)

	// Create an MQTT Client.
	cli := client.New(&client.Options{
		// Define the processing of the error handler.
		ErrorHandler: func(err error) {
			fmt.Println(err)
		},
	})

	// Terminate the Client.
	defer cli.Terminate()

	// Connect to the MQTT Server.
	err := cli.Connect(&client.ConnectOptions{
		Network:  "tcp",
		Address:  "iot.eclipse.org:1883",
		ClientID: []byte("example-client"),
	})
	if err != nil {
		panic(err)
	}

	// Subscribe to topics.
	err = cli.Subscribe(&client.SubscribeOptions{
		SubReqs: []*client.SubReq{
			&client.SubReq{
				TopicFilter: []byte("foo"),
				QoS:         mqtt.QoS0,
				// Define the processing of the message handler.
				Handler: func(topicName, message []byte) {
					fmt.Println(string(topicName), string(message))
				},
			},
			&client.SubReq{
				TopicFilter: []byte("bar/#"),
				QoS:         mqtt.QoS1,
				Handler: func(topicName, message []byte) {
					fmt.Println(string(topicName), string(message))
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}

	// Publish a message.
	err = cli.Publish(&client.PublishOptions{
		QoS:       mqtt.QoS0,
		TopicName: []byte("bar/baz"),
		Message:   []byte("testMessage"),
	})
	if err != nil {
		panic(err)
	}

	// Unsubscribe from topics.
	err = cli.Unsubscribe(&client.UnsubscribeOptions{
		TopicFilters: [][]byte{
			[]byte("foo"),
		},
	})
	if err != nil {
		panic(err)
	}

	// Wait for receiving a signal.
	<-sigc

	// Disconnect the Network Connection.
	if err := cli.Disconnect(); err != nil {
		panic(err)
	}
}

Details about APIs

CONNECT – Client requests a connection to a Server

// Create an MQTT Client.
cli := client.New(&client.Options{
	ErrorHandler: func(err error) {
		fmt.Println(err)
	},
})

// Terminate the Client.
defer cli.Terminate()

// Connect to the MQTT Server.
err := cli.Connect(&client.ConnectOptions{
	// Network is the network on which the Client connects to.
	Network:         "tcp",
	// Address is the address which the Client connects to.
	Address:         "iot.eclipse.org:1883",
	// TLSConfig is the configuration for the TLS connection.
	// If this property is not nil, the Client tries to use TLS
	// for the connection.
	TLSConfig:       nil,
	// CONNACKTimeout is timeout in seconds for the Client
	// to wait for receiving the CONNACK Packet after sending
	// the CONNECT Packet.
	CONNACKTimeout:  10,
	// PINGRESPTimeout is timeout in seconds for the Client
	// to wait for receiving the PINGRESP Packet after sending
	// the PINGREQ Packet.
	PINGRESPTimeout: 10,
	// ClientID is the Client Identifier of the CONNECT Packet.
	ClientID:        []byte("clientID"),
	// UserName is the User Name of the CONNECT Packet.
	UserName:        []byte("userName"),
	// // Password is the Password of the CONNECT Packet.
	Password:        []byte("password"),
	// CleanSession is the Clean Session of the CONNECT Packet.
	CleanSession:    true,
	// KeepAlive is the Keep Alive of the CONNECT Packet.
	KeepAlive:       30,
	// WillTopic is the Will Topic of the CONNECT Packet.
	WillTopic:       []byte("willTopic"),
	// WillMessage is the Will Message of the CONNECT Packet.
	WillMessage:     []byte("willMessage"),
	// WillQoS is the Will QoS of the CONNECT Packet.
	WillQoS:         mqtt.QoS0,
	// WillRetain is the Will Retain of the CONNECT Packet.
	WillRetain:      true,
})
if err != nil {
	panic(err)
}

CONNECT using TLS

// Create an MQTT Client.
cli := client.New(&client.Options{
	ErrorHandler: func(err error) {
		fmt.Println(err)
	},
})

// Terminate the Client.
defer cli.Terminate()

// Read the certificate file.
b, err := ioutil.ReadFile("/path/to/crtFile")
if err != nil {
	panic(err)
}

roots := x509.NewCertPool()
if ok := roots.AppendCertsFromPEM(b); !ok {
	panic("failed to parse root certificate")
}

tlsConfig = &tls.Config{
	RootCAs: roots,
}

// Connect to the MQTT Server using TLS.
err := cli.Connect(&client.ConnectOptions{
	// Network is the network on which the Client connects to.
	Network:         "tcp",
	// Address is the address which the Client connects to.
	Address:         "iot.eclipse.org:1883",
	// TLSConfig is the configuration for the TLS connection.
	// If this property is not nil, the Client tries to use TLS
	// for the connection.
	TLSConfig:       tlsConfig,
})
if err != nil {
	panic(err)
}

SUBSCRIBE - Subscribe to topics

// Create an MQTT Client.
cli := client.New(&client.Options{
	ErrorHandler: func(err error) {
		fmt.Println(err)
	},
})

// Terminate the Client.
defer cli.Terminate()

// Subscribe to topics.
err = cli.Subscribe(&client.SubscribeOptions{
	SubReqs: []*client.SubReq{
		&client.SubReq{
			// TopicFilter is the Topic Filter of the Subscription.
			TopicFilter: []byte("foo"),
			// QoS is the requsting QoS.
			QoS:         mqtt.QoS0,
			// Handler is the handler which handles the Application Message
			// sent from the Server.
			Handler: func(topicName, message []byte) {
				fmt.Println(string(topicName), string(message))
			},
		},
		&client.SubReq{
			TopicFilter: []byte("bar/#"),
			QoS:         mqtt.QoS1,
			Handler: func(topicName, message []byte) {
				fmt.Println(string(topicName), string(message))
			},
		},
	},
})
if err != nil {
	panic(err)
}

PUBLISH – Publish message

// Create an MQTT Client.
cli := client.New(&client.Options{
	ErrorHandler: func(err error) {
		fmt.Println(err)
	},
})

// Terminate the Client.
defer cli.Terminate()

// Publish a message.
err = cli.Publish(&client.PublishOptions{
	// QoS is the QoS of the PUBLISH Packet.
	QoS:       mqtt.QoS0,
	// Retain is the Retain of the PUBLISH Packet.
	Retain:    true,
	// TopicName is the Topic Name of the PUBLISH Packet.
	TopicName: []byte("bar/baz"),
	// Message is the Application Message of the PUBLISH Packet.
	Message:   []byte("testMessage"),
})
if err != nil {
	panic(err)
}

UNSUBSCRIBE – Unsubscribe from topics

// Create an MQTT Client.
cli := client.New(&client.Options{
	ErrorHandler: func(err error) {
		fmt.Println(err)
	},
})

// Terminate the Client.
defer cli.Terminate()

// Unsubscribe from topics.
err = cli.Unsubscribe(&client.UnsubscribeOptions{
	// TopicFilters represents a slice of the Topic Filters.
	TopicFilters: [][]byte{
		[]byte("foo"),
	},
})
if err != nil {
	panic(err)
}

DISCONNECT – Disconnect the Network Connection

// Create an MQTT Client.
cli := client.New(&client.Options{
	ErrorHandler: func(err error) {
		fmt.Println(err)
	},
})

// Terminate the Client.
defer cli.Terminate()

// Disconnect the network connection.
if err := cli.Disconnect(); err != nil {
	panic(err)
}

MQTT Client Command Line Application

After the installation, you can launch an MQTT client command line application by executing the gmq-cli command.

$ gmq-cli
gmq-cli>

You can see all GMQ Client commands by executing the help GMQ Client command.

gmq-cli> help
GMQ Client 0.0.1
Usage:
conn     establish a Network Connection and send a CONNECT Packet to the Server
disconn  send a DISCONNECT Packet to the Server and disconnect the Network Connection
help     print this help message
pub      send a PUBLISH Packet to the Server
quit     quit this process
sub      send a SUBSCRIBE Packet to the Server
unsub    send a UNSUBSCRIBE Packet to the Server

You can see all flags of a GMQ Client command by executing the command with the -help flag.

gmq-cli> conn -help
Usage:
  -P="": Password
  -c=true: Clean Session
  -crt="": the path of the certificate authority file to verify the server connection
  -ct=30: Timeout in seconds for the Client to wait for receiving the CONNACK Packet after sending the CONNECT Packet
  -h="localhost": host name of the Server which the Client connects to
  -i="": Client identifier for the Client
  -k=60: Keep Alive measured in seconds
  -n="tcp": network on which the Client connects to the Server
  -p=1883: port number of the Server which the Client connects to
  -pt=30: Timeout in seconds for the Client to wait for receiving the PINGRESP Packet after sending the PINGREQ Packet
  -u="": User Name
  -wm="": Will Message
  -wq=0: Will QoS
  -wr=false: Will Retain
  -wt="": Will Topic

More Repositories

1

ace

HTML template engine for Go
Go
834
star
2

gcss

Pure Go CSS Preprocessor
Go
496
star
3

gohtml

HTML formatter for Go
Go
276
star
4

gold

[DEPRECATED]Template engine for Go
Go
145
star
5

goat

File watcher
Go
90
star
6

boltstore

Session store using Bolt
Go
87
star
7

go-fileserver

Go cached file server
Go
40
star
8

martini-acerender

Martini middleware/handler for parsing Ace templates and rendering HTML
Go
20
star
9

vim-ace

Vim syntax highlighting for Ace templates
Vim Script
16
star
10

rendergold

Martini middleware/handler for parsing Gold templates and rendering HTML
Go
15
star
11

galaxy

Simple web framework for Go
Go
15
star
12

go-voicetext

Go言θͺžε‘けVoiceText Web APIγ‚―γƒ©γ‚€γ‚’γƒ³γƒˆ
Go
14
star
13

koa-stylus

Stylus middleware for Koa
JavaScript
12
star
14

gocover

Go coverage profile HTML showing tool
Go
9
star
15

vim-gcss

Vim syntax highlighting for GCSS
Vim Script
6
star
16

goesjp

Go news website
Go
5
star
17

go-session-store-benchmarks

Go session store benchmarks
Go
5
star
18

gospritz

Spritz program in Golang
Go
5
star
19

ace-proxy

Proxy for the Ace template engine
Go
4
star
20

gologger

Logger in Go
Go
4
star
21

ace-tmbundle

Ace TextMate/Sublime Text Bundle
4
star
22

goproject

Go project search engine
Go
3
star
23

vim-gold

Vim syntax highlighting for Gold templates
Vim Script
3
star
24

gold.yoss.si

Website about Gold
Go
3
star
25

staticbin

Martini middleware/handler for serving static files from binary data
Go
3
star
26

go-perm

Permutation Generator in Go
Go
3
star
27

ip2domain

IP address to domain name converter
Java
3
star
28

docker-errbit

Dockerfile for Errbit
Shell
3
star
29

orgs.io

Wep application for organizing bookmarks
Go
3
star
30

docker-elasticsearch

Dockerfile for Elasticsearch
Shell
2
star
31

httprouter

Go
2
star
32

gogithub

GitHub API client in Golang
Go
2
star
33

xpress

Simple blogging service
Go
2
star
34

packer-errbit

Packer configuration file for Errbit
2
star
35

goes

Go news gatherer
Go
2
star
36

slides.yoss.si

Website showing slides
Go
2
star
37

dockerfile-dev

Dockerfile for general development
Shell
1
star
38

wercker-box-golang-latest

wercker box using the latest version of Go
1
star
39

ace.yoss.si

Website of Ace
Go
1
star
40

golang-study-slices

Golang study about slices
Go
1
star
41

t-rex-ai

T-Rex Game AI
JavaScript
1
star
42

go-stylus

Stylus caller in Go
Go
1
star
43

goelasticsearch

Elasticsearch client in Golang
Go
1
star
44

chainer-vagrant

Vagrantfile for Chainer
Shell
1
star
45

vagrant-box-templates

Vagrant box templates
Shell
1
star
46

go-hpg

γƒ›γƒƒγƒˆγƒšγƒƒγƒ‘γƒΌ Webァービス γ‚―γƒ©γ‚€γ‚’γƒ³γƒˆ
Go
1
star
47

uguis

Twitter音声θͺ­γΏδΈŠγ’γ‚³γƒžγƒ³γƒ‰γƒ©γ‚€γƒ³γƒ„γƒΌγƒ«
Go
1
star
48

yoss.si

Website of Keiji Yoshida
Go
1
star
49

drone-test-custom-docker-image

Drone Test - Custom Docker Image
Go
1
star
50

golang-links-ja

Go言θͺžγ«ι–’するγƒͺンク
1
star
51

golang-links

Links about Go
1
star
52

gold-tmbundle

Gold TextMate/Sublime Text Bundle
1
star
53

fluent-plugin-cloud-pubsub

fluent-plugin-cloud-pubsub
Ruby
1
star
54

goc

Command which opens Go package documentation in a web browser
Go
1
star
55

algorithms-in-go

Algorithms in Go
Go
1
star
56

html2ace

HTML to Ace Template Converter
1
star
57

gonhk

NHK API Client in Go
Go
1
star
58

cfnews

Articles relating to Crowdfunding
Go
1
star
59

talks

Talks
Go
1
star
60

goimpl

Go tool which searches structs which implement the specified interface
1
star
61

go-jsonp-callback-validator

JSONP callback validator
Go
1
star
62

docker-go1.2-mongo2.4

Dockerfile for Go 1.2 and MongoDB 2.4
1
star
63

i2d

IP address to domain name converter
Go
1
star
64

gofmtchk

Format check tool in Go
Go
1
star
65

gofmtall

Format tool in Go
Go
1
star
66

vagrantfiles

Vagrantfiles
Ruby
1
star
67

cfnewsjp

Articles relating to Crowdfunding
Go
1
star
68

goutils

Utility functions in Go
Go
1
star
69

xpress-packer-template

Xpress packer template
Shell
1
star
70

gocmd

Command utility functions in Go
Go
1
star