-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (74 loc) · 2.37 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
}
var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
fmt.Println("Connected")
}
var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
fmt.Printf("Connect lost: %v", err)
}
func main() {
var broker = "test.mosquitto.org" // broker.hivemq.com or test.mosquitto.org
var port = 1883
// create a new MQTT client and connect to an MQTT broker running on "test.mosquitto.org"
opts := mqtt.NewClientOptions().AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
opts.SetClientID("go_mqtt_client_bf94")
// opts.SetUsername("")
// opts.SetPassword("")
opts.SetDefaultPublishHandler(messagePubHandler)
opts.OnConnect = connectHandler
opts.OnConnectionLost = connectLostHandler
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
sub(client)
// publish(client)
client.Disconnect(250)
}
func publish(client mqtt.Client) {
num := 10
for i := 0; i < num; i++ {
text := fmt.Sprintf("Message %d", i)
token := client.Publish("bf94/gendata", 0, false, text)
token.Wait()
time.Sleep(time.Second)
}
}
func sub(client mqtt.Client) {
topic := "bf94/gendata"
qos := 1
// Set up a channel to receive OS signals (e.g. SIGINT or SIGTERM)
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)
// Set up a channel to receive MQTT messages
msgchan := make(chan mqtt.Message, 10)
// Subscribe to the MQTT topic
if token := client.Subscribe(topic, byte(qos), func(client mqtt.Client, msg mqtt.Message) {
// Pass a callback function to handle incoming messages
msgchan <- msg // The callback function simply sends the message to the msgchan channel
}); token.Wait() && token.Error() != nil {
panic(token.Error())
}
// Wait for OS signals or MQTT messages
for {
select {
case sig := <-sigchan:
fmt.Printf("Received signal %v\n", sig)
// Disconnect from the MQTT broker and exit the program
client.Disconnect(250)
os.Exit(0)
case msg := <-msgchan:
fmt.Printf("Received message on topic %s: %s\n", msg.Topic(), msg.Payload())
}
}
}