All Projects → goiiot → Libmqtt

goiiot / Libmqtt

Licence: apache-2.0
MQTT v3.1.1/5.0 library in Go

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Libmqtt

Mtproto Core
Telegram API JS (MTProto) client library for browser and nodejs
Stars: ✭ 242 (-16.55%)
Mutual labels:  library, lib, client
Curl
A command line tool and library for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP. libcurl offers a myriad of powerful features
Stars: ✭ 22,875 (+7787.93%)
Mutual labels:  library, mqtt, client
Amqp
AMQP 1.0 client library for Go.
Stars: ✭ 135 (-53.45%)
Mutual labels:  library, client
Pipedrive
Complete Pipedrive API client for PHP
Stars: ✭ 138 (-52.41%)
Mutual labels:  library, client
Bt
BitTorrent library and client with DHT, magnet links, encryption and more
Stars: ✭ 2,011 (+593.45%)
Mutual labels:  library, client
Freeradius Client
A BSD licenced RADIUS client library
Stars: ✭ 103 (-64.48%)
Mutual labels:  library, client
Math Engine
Mathematical expression parsing and calculation engine library. 数学表达式解析计算引擎库
Stars: ✭ 123 (-57.59%)
Mutual labels:  library, lib
Pysnow
Python library for the ServiceNow REST API
Stars: ✭ 162 (-44.14%)
Mutual labels:  library, client
Graphql client
GraphQL Client.
Stars: ✭ 78 (-73.1%)
Mutual labels:  library, client
Beanstalk
Minimalistic PHP client for beanstalkd without any dependencies
Stars: ✭ 199 (-31.38%)
Mutual labels:  library, client
Sdk
Library for using Grafana' structures in Go programs and client for Grafana REST API.
Stars: ✭ 193 (-33.45%)
Mutual labels:  library, client
Pdf Lib
Create and modify PDF documents in any JavaScript environment
Stars: ✭ 3,426 (+1081.38%)
Mutual labels:  library, lib
Ts3admin.class
The ts3admin.class is a powerful api for communication with Teamspeak 3 Servers from your website! Your creativity knows no bounds!
Stars: ✭ 103 (-64.48%)
Mutual labels:  library, client
Gowebdav
A golang WebDAV client library and command line tool.
Stars: ✭ 97 (-66.55%)
Mutual labels:  library, client
Pyrogram
Telegram MTProto API Client Library and Framework in Pure Python for Users and Bots
Stars: ✭ 2,252 (+676.55%)
Mutual labels:  library, client
Cocsharp
Clash of Clans library, proxy and server written in .NET [Unmaintained]
Stars: ✭ 94 (-67.59%)
Mutual labels:  library, client
Deeply
PHP client for the DeepL.com translation API (unofficial)
Stars: ✭ 152 (-47.59%)
Mutual labels:  library, client
Easygo
基于Kotlin、OkHttp的声明式网络框架,像写HTML界面一样写网络调用代码
Stars: ✭ 40 (-86.21%)
Mutual labels:  library, lib
Adrestia
APIs & SDK for interacting with Cardano.
Stars: ✭ 56 (-80.69%)
Mutual labels:  library, client
Simple Web Server
A very simple, fast, multithreaded, platform independent HTTP and HTTPS server and client library implemented using C++11 and Boost.Asio. Created to be an easy way to make REST resources available from C++ applications.
Stars: ✭ 2,261 (+679.66%)
Mutual labels:  library, client

libmqtt

Build Status GoDoc GoReportCard codecov

Feature rich modern MQTT library in pure Go, for Go, C/C++, Java

Table of contents

Features

  1. MQTT v3.1.1/v5.0 client support (async only)
  2. High performance and less memory footprint (see Benchmark)
  3. Customizable topic routing (see Topic Routing)
  4. Multiple Builtin session persist methods (see Session Persist)
  5. C/C++ lib, Java lib, Command line client support
  6. Idiomatic Go

Usage

This package can be used as

As a Go lib

Prerequisite

  • Go 1.9+

Steps

TL;DR: You can find a full example at examples/client.go

1.Go get this project

go get github.com/goiiot/libmqtt

2.Import this package in your project file

import "github.com/goiiot/libmqtt"

3.Create a custom client

// Create a client and enable auto reconnect when connection lost
// We primarily use `RegexRouter` for client
client, err := libmqtt.NewClient(
    // enable keepalive (10s interval) with 20% tolerance
    libmqtt.WithKeepalive(10, 1.2),
    // enable auto reconnect and set backoff strategy
    libmqtt.WithAutoReconnect(true),
    libmqtt.WithBackoffStrategy(time.Second, 5*time.Second, 1.2),
    // use RegexRouter for topic routing if not specified
    // will use TextRouter, which will match full text
    libmqtt.WithRouter(libmqtt.NewRegexRouter()),
)

if err != nil {
    // handle client creation error
    panic("create mqtt client failed")
}

Notice: If you would like to explore all the options available, please refer to GoDoc#Option

4.Register the handlers and Connect, then you are ready to pub/sub with server

Optional, but we recommend to register handlers for pub, sub, unsub, net error and persist error, and you can gain more controllability of the lifecycle of the client

client.HandlePub(PubHandler) // register handler for pub success/fail (optional, but recommended)
client.HandleSub(SubHandler) // register handler for sub success/fail (optional, but recommended)
client.HandleUnSub(UnSubHandler) // register handler for unsub success/fail (optional, but recommended)
client.HandleNet(NetHandler) // register handler for net error (optional, but recommended)
client.HandlePersist(PersistHandler) // register handler for persist error (optional, but recommended)

// define your topic handlers like a golang http server client.Handle("foo", func(topic string, qos libmqtt.QosLevel, msg []byte) { // handle the topic message })

client.Handle("bar", func(topic string, qos libmqtt.QosLevel, msg []byte) { // handle the topic message })

// connect to server
client.ConnectServer("test.mosquitto.org:8883", 
	libmqtt.WithCustomTLS(nil),
	libmqtt.WithConnHandleFunc(func(server string, code byte, err error) {
		if err != nil {
			// failed
			panic(err)
		}
		
		if code != libmqtt.CodeSuccess {
			// server rejected or in error
			panic(code)
		}

		// success
		// you are now connected to the `server`
		// (the `server` is one of your provided `servers` when create the client)
		// start your business logic here or send a signal to your logic to start

		// subscribe some topic(s)
		client.Subscribe([]*libmqtt.Topic{
			{Name: "foo"},
			{Name: "bar", Qos: libmqtt.Qos1},
		}...)

		// publish some topic message(s)
		client.Publish([]*libmqtt.PublishPacket{
			{TopicName: "foo", Payload: []byte("bar"), Qos: libmqtt.Qos0},
			{TopicName: "bar", Payload: []byte("foo"), Qos: libmqtt.Qos1},
		}...)
	}),
)

5.Unsubscribe from topic(s)

client.UnSubscribe("foo", "bar")

6.Destroy the client when you would like to

// use true for a immediate disconnect to server
// use false to send a DisConn packet to server before disconnect
client.Destroy(true)

As a C/C++ lib

Please refer to c - README.md

As a Java lib

Please refer to java - README.md

As a command line client

Please refer to cmd/libmqtt - README.md

As MQTT infrastructure

This package can also be used as MQTT packet encoder and decoder

// decode one mqtt 3.1.1 packet from reader
packet, err := libmqtt.Decode(libmqtt.V311, reader)
// ...

// encode one mqtt packet to buffered writer
err := libmqtt.Encode(packet, bufferedWriter)
// ...

Topic Routing

Routing topics is one of the most important thing when it comes to business logic, we currently have built two TopicRouters which is ready to use, they are TextRouter and RegexRouter

  • TextRouter will match the exact same topic which was registered to client by Handle method. (this is the default router in a client)
  • RegexRouter will go through all the registered topic handlers, and use regular expression to test whether that is matched and should dispatch to the handler

If you would like to apply other routing strategy to the client, you can provide this option when creating the client

client, err := libmqtt.NewClient(
    // ...
    // e.g. use `RegexRouter`
    libmqtt.WithRouter(libmqtt.NewRegexRouter()),
    // ...
)

Session Persist

Per MQTT Specification, session state should be persisted and be recovered when next time connected to server without clean session flag set, currently we provide persist method as following:

  1. NonePersist - no session persist
  2. memPersist - in memory session persist
  3. filePersist - files session persist (with write barrier)
  4. redisPersist - redis session persist (available inside github.com/goiiot/libmqtt/extension package)

Note: Use RedisPersist if possible.

Benchmark

The procedure of the benchmark is:

  1. Create the client
  2. Connect to server
  3. Publish N times to topic foo
  4. Unsubscribe topic (just ensure all pub message has been sent)
  5. Destroy client (without disconnect packet)

The benchmark result listed below was taken on a MacBook Pro 13' (Early 2015, macOS 10.13.2), statistics inside which is the value of ten times average

Bench Name Pub Count ns/op B/op allocs/op
BenchmarkLibmqttClient-4 (this project) 100000 20187 176 6
BenchmarkPahoClient-4 (eclipse paho) 100000 25072 816 15

You can make the benchmark using source code from benchmark

Extensions

Helpful extensions for libmqtt (see extension)

LICENSE

GitHub license

Copyright Go-IIoT (https://github.com/goiiot)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].