Go 安裝與使用 mqtt

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

    active則為正常執行

2.1 註冊一個top進行接收

mosquitto_sub -h localhost -t "mqtt" -v

2.2 釋出訊息到剛註冊的top

需要另開一個終端,當執行完下面命令後,會在上一個終端出列印出我們釋出的訊息

mosquitto_pub -h localhost -t "mqtt" -m "Hello 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

```bash
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
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()
}