first
This commit is contained in:
64
pkg/emq/emq.go
Normal file
64
pkg/emq/emq.go
Normal 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())
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user