You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
1.6 KiB
Go
73 lines
1.6 KiB
Go
4 months ago
|
// package main
|
||
|
|
||
|
// import (
|
||
|
// "flag"
|
||
|
// "fmt"
|
||
|
|
||
|
// "git.runcible.io/learning/learn_mqtt_go/common"
|
||
|
// )
|
||
|
|
||
|
// func main() {
|
||
|
// flag.Parse()
|
||
|
// fmt.Printf("MQTT Host: %s\nMQTT Port: %s\n", *common.BrokerHost, *common.BrokerPort)
|
||
|
// }
|
||
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"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 = "0.0.0.0"
|
||
|
var port = 1883
|
||
|
opts := mqtt.NewClientOptions()
|
||
|
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
|
||
|
// opts.SetClientID("go_mqtt_client")
|
||
|
opts.SetUsername("dirp")
|
||
|
opts.SetPassword("dirp")
|
||
|
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("topic/test", 0, false, text)
|
||
|
token.Wait()
|
||
|
time.Sleep(time.Second)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func sub(client mqtt.Client) {
|
||
|
topic := "topic/test"
|
||
|
token := client.Subscribe(topic, 1, nil)
|
||
|
token.Wait()
|
||
|
fmt.Printf("Subscribed to topic: %s", topic)
|
||
|
}
|