mqtt

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2022 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package mqtt wraps github.com/eclipse/paho.mqtt.golang

Example
package main

import (
	"strconv"
	"sync"
	"time"

	"github.com/lovelacelee/clsgo/v1/config"

	"github.com/lovelacelee/clsgo/v1/log"
	"github.com/lovelacelee/clsgo/v1/mqtt"
)

const PublishCount = 5

func main() {
	server := config.GetStringWithDefault("mqtt.server", "tcp://192.168.137.100:1883")
	user := config.GetStringWithDefault("mqtt.user", "lee")
	password := config.GetStringWithDefault("mqtt.password", "lovelace")

	mqtt := mqtt.New(server, user, password, "ID_CLIENT_TEST")
	defer mqtt.Close()
	mqtt.Subscribe("test/#", 2)
	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		log.Info("Publish routine begin")
		for i := 0; i < PublishCount; i++ {
			mqtt.Publish("test/abc", 2, true, "Hello"+strconv.Itoa(i))
			time.Sleep(time.Microsecond)
		}
		wg.Done()
		log.Info("Publish routine done")
	}()
	go func() {
		log.Info("Sub routine begin")
		// delivery := mqtt.Consume()
		// for m := range delivery {
		// 	log.Info(m.Payload())
		// }
		wg.Done()
		log.Info("Sub routine done")
	}()
	wg.Wait()
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MQTT

type MQTT struct {
	Cli      mqtt.Client
	Opt      *mqtt.ClientOptions
	Subs     map[string]byte
	Timeout  time.Duration
	Delivery chan MQTTMsg
}

func New

func New(broker string, username string, password string, clientId string) *MQTT

broker format: tcp://broker.emqx.io:1883

func (*MQTT) Close

func (mqtt *MQTT) Close()

func (*MQTT) Consume

func (mqtt *MQTT) Consume() <-chan MQTTMsg

func (*MQTT) Publish

func (mqtt *MQTT) Publish(topic string, qos byte, retained bool, payload interface{})

func (*MQTT) Subscribe

func (mqtt *MQTT) Subscribe(topic string, qos byte)

func (*MQTT) UnSubscribe

func (mqtt *MQTT) UnSubscribe(topic string)

type MQTTMsg

type MQTTMsg = mqtt.Message

Jump to

Keyboard shortcuts

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