88 lines
1.8 KiB
Go
88 lines
1.8 KiB
Go
package mqtt
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
|
|
"github.com/eclipse/paho.golang/autopaho"
|
|
"github.com/eclipse/paho.golang/paho"
|
|
"google.golang.org/protobuf/proto"
|
|
mproto "joylink.club/iot/mqtt/proto"
|
|
)
|
|
|
|
type Manager struct {
|
|
cc *autopaho.ClientConfig
|
|
cm *autopaho.ConnectionManager
|
|
}
|
|
|
|
var manager *Manager
|
|
|
|
func Start(cmc *ClientManageConfig) error {
|
|
cc, err := cmc.tryInto()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cm, err := autopaho.NewConnection(context.Background(), *cc)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
manager = &Manager{
|
|
cc: cc,
|
|
cm: cm,
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func Publish(ctx context.Context, publish *paho.Publish) (*paho.PublishResponse, error) {
|
|
return manager.cm.Publish(ctx, publish)
|
|
}
|
|
|
|
func PubIotServiceState(s *mproto.IotServiceState) error {
|
|
return manager.PubIotServiceState(s)
|
|
}
|
|
|
|
func SubIotServiceState(topic string) error {
|
|
return manager.SubIotServiceState(topic)
|
|
}
|
|
|
|
func (m *Manager) PubIotServiceState(s *mproto.IotServiceState) error {
|
|
if s == nil {
|
|
return nil
|
|
}
|
|
slog.Debug("PubIotServiceState", "topic", GetIotServiceStateTopic(), "state", s)
|
|
b, err := proto.Marshal(s)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = m.cm.Publish(context.Background(), &paho.Publish{
|
|
Topic: GetIotServiceStateTopic(),
|
|
QoS: 0,
|
|
Payload: b,
|
|
})
|
|
return err
|
|
}
|
|
|
|
func RegisterHandler(topic string, h func(m *paho.Publish)) {
|
|
manager.cc.Router.RegisterHandler(topic, h)
|
|
}
|
|
|
|
func (m *Manager) RegisterHandler(topic string, h func(m *paho.Publish)) {
|
|
m.cc.Router.RegisterHandler(topic, h)
|
|
}
|
|
|
|
func (m *Manager) SubIotServiceState(topic string) error {
|
|
slog.Debug("订阅IotServiceState", "topic", topic)
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
_, err := m.cm.Subscribe(ctx, &paho.Subscribe{
|
|
Subscriptions: []paho.SubscribeOptions{
|
|
{
|
|
Topic: topic,
|
|
QoS: 0,
|
|
// NoLocal: true,
|
|
},
|
|
},
|
|
})
|
|
return err
|
|
}
|