This commit is contained in:
Sakurasan
2023-04-06 22:40:20 +08:00
commit d11241960a
8 changed files with 396 additions and 0 deletions

64
pkg/emq/emq.go Normal file
View File

@@ -0,0 +1,64 @@
package emq
import (
"fmt"
"log"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
var (
Client mqtt.Client
)
type Emq struct {
mqtt.Client
}
func init() {
opts := mqtt.NewClientOptions().AddBroker("tcp://138.2.17.73:1883")
Client = mqtt.NewClient(opts)
if token := Client.Connect(); token.Wait() && token.Error() != nil {
log.Fatal(token.Error())
}
}
func mqttConnectHandler(client mqtt.Client) {
log.Printf("Connected to broker\n")
}
func mqttConnectionLostHandler(client mqtt.Client, err error) {
log.Printf("Connection to broker lost: %v\n", err)
}
func mqttReconnectingHandler(client mqtt.Client, opts *mqtt.ClientOptions) {
log.Printf("Attempting to reconnect to broker\n")
}
func (c *Emq) Connect() error {
if token := c.Client.Connect(); token.Wait() && token.Error() != nil {
return token.Error()
}
return nil
}
func (c *Emq) Publish(topic, msg string) error {
token := c.Client.Publish(topic, 0, false, msg)
if token.Wait() && token.Error() != nil {
return token.Error()
}
return nil
}
func (c *Emq) Subscribe(topic string) error {
if token := c.Client.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil {
return token.Error()
}
return nil
}
func (c *Emq) AddRoute(topic string) {
c.Client.AddRoute(topic, func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
})
}