Go安裝配置與使用mqtt

1. 安裝

  1. 引入mosquitto倉庫並更新
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
sudo apt-get update
  1. 執行以下命令安裝mosquitto包
sudo apt-get install mosquitto
  1. 安裝mosquitto開發包
sudo apt-get install mosquitto-dev
  1. 安裝mosquitto客戶端
sudo apt-get install mosquitto-clients
  1. 查詢mosquitto是否正確運行
sudo service mosquitto status 

active則爲正常運行

2. 測試

2.1 參數說明

參數 說明
-h 服務器主機,默認localhost
-p 端口號,默認1883
-t 指定主題
-u 用戶名
-P 密碼
-i 客戶端id,唯一
-m 發佈的消息內容

2.2 註冊一個top進行接收

mosquitto_sub -h localhost -t "mqtt" -v

2.3 發佈消息到剛註冊的top

需要另開一個終端,當執行完下面命令後,會在上一個終端出打印出我們發佈的消息

mosquitto_pub -h localhost -t "mqtt" -m "Hello MQTT"

3. 配置Mqtt

設置一下用戶名和密碼,這樣我們的mqtt纔會比較安全。mqtt總配置在/etc/mosquitto/mosquitto.conf

在該文件末尾添加下面三個配置

# 關閉匿名
allow_anonymous false
# 設置用戶名和密碼
password_file /etc/mosquitto/pwfile
# 配置訪問控制列表(topic和用戶的關係)
acl_file /etc/mosquitto/acl
# 配置端口
port 8000

3.1 添加用戶

添加一個用戶,用戶名爲pibigstar,這個命令執行之後會讓你輸入密碼,密碼自己定義就好

sudo mosquitto_passwd -c /etc/mosquitto/pwfile pibigstar

3.2 添加Topic和用戶的關係

新增acl文件

sudo vim /etc/mosquitto/acl

添加下面內容

# 用戶test只能發佈以test爲前綴的主題
# 訂閱以mqtt開頭的主題
user test
topic write test/#
topic read mqtt/#

user pibigstar
topic write mqtt/#
topic write mqtt/#

3.3 重啓mqtt

sudo /etc/init.d/mosquitto restart

3.4 測試

3.4.1 監聽消費

mosquitto_sub -h 127.0.0.1 -p 8000 -t "mqtt" -v -u pibigstar -P 123456

3.4.2 發佈消息

mosquitto_pub -h 127.0.0.1 -p 8000 -t "mqtt" -m "Hello MQTT" -u pibigstar -P 123456

4. Go語言使用Mqtt

package mqtt

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"sync"
	"time"

	gomqtt "github.com/eclipse/paho.mqtt.golang"
)

const (
	Host     = "192.168.1.101:8000"
	UserName = "pibigstar"
	Password = "123456"
)

type Client struct {
	nativeClient  gomqtt.Client
	clientOptions *gomqtt.ClientOptions
	locker        *sync.Mutex
	// 消息收到之後處理函數
	observer func(c *Client, msg *Message)
}

type Message struct {
	ClientID string `json:"clientId"`
	Type     string `json:"type"`
	Data     string `json:"data,omitempty"`
	Time     int64  `json:"time"`
}

func NewClient(clientId string) *Client {
	clientOptions := gomqtt.NewClientOptions().
		AddBroker(Host).
		SetUsername(UserName).
		SetPassword(Password).
		SetClientID(clientId).
		SetCleanSession(false).
		SetAutoReconnect(true).
		SetKeepAlive(120 * time.Second).
		SetPingTimeout(10 * time.Second).
		SetWriteTimeout(10 * time.Second).
		SetOnConnectHandler(func(client gomqtt.Client) {
			// 連接被建立後的回調函數
			fmt.Println("Mqtt is connected!", "clientId", clientId)
		}).
		SetConnectionLostHandler(func(client gomqtt.Client, err error) {
			// 連接被關閉後的回調函數
			fmt.Println("Mqtt is disconnected!", "clientId", clientId, "reason", err.Error())
		})

	nativeClient := gomqtt.NewClient(clientOptions)

	return &Client{
		nativeClient:  nativeClient,
		clientOptions: clientOptions,
		locker:        &sync.Mutex{},
	}
}

func (client *Client) GetClientID() string {
	return client.clientOptions.ClientID
}

func (client *Client) Connect() error {
	return client.ensureConnected()
}

// 確保連接
func (client *Client) ensureConnected() error {
	if !client.nativeClient.IsConnected() {
		client.locker.Lock()
		defer client.locker.Unlock()
		if !client.nativeClient.IsConnected() {
			if token := client.nativeClient.Connect(); token.Wait() && token.Error() != nil {
				return token.Error()
			}
		}
	}
	return nil
}

// 發佈消息
// retained: 是否保留信息
func (client *Client) Publish(topic string, qos byte, retained bool, data []byte) error {
	if err := client.ensureConnected(); err != nil {
		return err
	}

	token := client.nativeClient.Publish(topic, qos, retained, data)
	if err := token.Error(); err != nil {
		return err
	}

	// return false is the timeout occurred
	if !token.WaitTimeout(time.Second * 10) {
		return errors.New("mqtt publish wait timeout")
	}

	return nil
}

// 消費消息
func (client *Client) Subscribe(observer func(c *Client, msg *Message), qos byte, topics ...string) error {
	if len(topics) == 0 {
		return errors.New("the topic is empty")
	}

	if observer == nil {
		return errors.New("the observer func is nil")
	}

	if client.observer != nil {
		return errors.New("an existing observer subscribed on this client, you must unsubscribe it before you subscribe a new observer")
	}
	client.observer = observer

	filters := make(map[string]byte)
	for _, topic := range topics {
		filters[topic] = qos
	}
	client.nativeClient.SubscribeMultiple(filters, client.messageHandler)

	return nil
}

func (client *Client) messageHandler(c gomqtt.Client, msg gomqtt.Message) {
	if client.observer == nil {
		fmt.Println("not subscribe message observer")
		return
	}
	message, err := decodeMessage(msg.Payload())
	if err != nil {
		fmt.Println("failed to decode message")
		return
	}
	client.observer(client, message)
}

func decodeMessage(payload []byte) (*Message, error) {
	message := new(Message)
	decoder := json.NewDecoder(strings.NewReader(string(payload)))
	decoder.UseNumber()
	if err := decoder.Decode(&message); err != nil {
		return nil, err
	}
	return message, nil
}

func (client *Client) Unsubscribe(topics ...string) {
	client.observer = nil
	client.nativeClient.Unsubscribe(topics...)
}

4.1 測試

package mqtt

import (
	"encoding/json"
	"fmt"
	"sync"
	"testing"
	"time"
)

func TestMqtt(t *testing.T) {
	var (
		clientId = "pibigstar"
		wg       sync.WaitGroup
	)
	client := NewClient(clientId)
	err := client.Connect()
	if err != nil {
		t.Errorf(err.Error())
	}

	wg.Add(1)
	go func() {
		err := client.Subscribe(func(c *Client, msg *Message) {
			fmt.Printf("接收到消息: %+v \n", msg)
			wg.Done()
		}, 1, "mqtt")

		if err != nil {
			panic(err)
		}
	}()

	msg := &Message{
		ClientID: clientId,
		Type:     "text",
		Data:     "Hello Pibistar",
		Time:     time.Now().Unix(),
	}
	data, _ := json.Marshal(msg)

	err = client.Publish("mqtt", 1, false, data)
	if err != nil {
		panic(err)
	}

	wg.Wait()
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章