使用树莓派安装 Mosquitto MQTT borker

未完待续

使用树莓派安装 Mosquitto MQTT borker,并使用paho.mqtt.golang客户端进行测试

介绍

MQTT 是用于物联网 (IoT) 的 OASIS 标准消息传递协议。它被设计为一种极其轻量级的发布/订阅消息传输,非常适合连接具有小代码足迹和最小网络带宽的远程设备。如今,MQTT 被广泛用于各种行业,例如汽车、制造、电信、石油和天然气等。

配置

更新

sudo apt update

sudo apt upgrade

安装

sudo apt install mosquitto mosquitto-clients

启动

sudo systemctl enable mosquitto

sudo systemctl start mosquitto

状态

sudo systemctl status mosquitto

如果服务已经正常启动,应该看到 “active(running)”的文字。

测试

本机测试

订阅者,打开终端,输入

mosquitto_sub -h localhost -t "test/topic"

发布者,重新打开终端,输入

mosquitto_pub -h localhost -t "test/topic" -m "hello world"

返回订阅者终端,查看结果是否为

hello world

远端测试

配置文件

sudo vim /etc/mosquitto/mosquitto.conf

add

  #配置端口
  listener 1883

  # 允许匿名
  allow_anonymous true

sudo systemctl restart mosquitto

程序访问

    package main

    import (
      "fmt"
      //import the Paho Go MQTT library
      MQTT "github.com/eclipse/paho.mqtt.golang"
      "os"
      "time"
    )

    //define a function for the default message handler
    var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
      fmt.Printf("TOPIC: %s\n", msg.Topic())
      fmt.Printf("MSG: %s\n", msg.Payload())
    }

    func main() {
      //create a ClientOptions struct setting the broker address, clientid, turn
      //off trace output and set the default message handler
      opts := MQTT.NewClientOptions().AddBroker("tcp://{your-device-ip}:1883")
      opts.SetClientID("go-simple")
      opts.SetDefaultPublishHandler(f)

      //create and start a client using the above ClientOptions
      c := MQTT.NewClient(opts)
      if token := c.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
      }

      //subscribe to the topic /go-mqtt/sample and request messages to be delivered
      //at a maximum qos of zero, wait for the receipt to confirm the subscription
      if token := c.Subscribe("test/topic", 0, nil); token.Wait() && token.Error() != nil {
        fmt.Println(token.Error())
        os.Exit(1)
      }

      //Publish 5 messages to /go-mqtt/sample at qos 1 and wait for the receipt
      //from the server after sending each message
      for i := 0; i < 5; i++ {
        text := fmt.Sprintf("this is msg #%d!", i)
        token := c.Publish("test/topic", 0, false, text)
        token.Wait()
      }

      time.Sleep(3 * time.Second)

      //unsubscribe from /go-mqtt/sample
      if token := c.Unsubscribe("test/topic"); token.Wait() && token.Error() != nil {
        fmt.Println(token.Error())
        os.Exit(1)
      }

      c.Disconnect(250)
    }

客户端访问

mqttx

MQTT Explorer

web端访问

js库

MQTT.js :star2:

paho.mqtt.javascript

配置文件

sudo vim /etc/mosquitto/mosquitto.conf

add

  #配置端口
  listener 8883

  #配置协议
  protocol websocketse

sudo systemctl restart mosquitto

demo

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0 ,maximum-scale=1, user-scalable=0" />
		<title>Document</title>
	</head>
	<body>
		<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
		<script>
			const client = mqtt.connect("ws://{your-device-ip}:8883"); // you add a ws:// url here
			client.on("connect", function () {
				client.subscribe("presence", function (err) {
					if (!err) {
						client.publish("presence", "Hello mqtt");
					}
				});
			});

			client.on("message", function (topic, message) {
				// message is Buffer
				console.log(1, message.toString());
				client.end();
			});
		</script>
	</body>
</html>

注意事项

  1. 使用snap方式安装,其配置文件位置与文档不符,且配置文件修改后未被加载,多次重启后仍无法进行局域网访

  2. 请尽量使用默认源安装