123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- package admin
- import (
- "errors"
- "fmt"
- "regexp"
- "runtime"
- "server/utils/logger"
- "server/utils/mqtt"
- "server/utils/protocol"
- "strings"
- "sync"
- "time"
- )
- func InitMqtt() {
- MqttService = GetHandler()
- MqttService.SubscribeTopics()
- go MqttService.Handler()
- }
- var MqttService *MqttHandler
- var timeoutReg = regexp.MustCompile("Client .* has exceeded timeout")
- var connectReg = regexp.MustCompile(`New client connected from .* as .*\(`)
- var disconnectReg = regexp.MustCompile("Client mqttx_893e4b7d disconnected")
- type MqttHandler struct {
- queue *mqtt.MlQueue
- }
- var _handlerOnce sync.Once
- var _handlerSingle *MqttHandler
- func GetHandler() *MqttHandler {
- _handlerOnce.Do(func() {
- _handlerSingle = &MqttHandler{
- queue: mqtt.NewQueue(10000),
- }
- })
- return _handlerSingle
- }
- func (o *MqttHandler) SubscribeTopics() {
- mqtt.GetMQTTMgr().Subscribe("smart_tunnel/#", mqtt.AtLeastOnce, o.HandlerData)
- }
- func (o *MqttHandler) HandlerData(m mqtt.Message) {
- for {
- ok, cnt := o.queue.Put(&m)
- if ok {
- break
- } else {
- logger.Get().Error("HandlerData:查询队列失败,队列消息数量:%d", cnt)
- runtime.Gosched()
- }
- }
- }
- func (o *MqttHandler) Handler() interface{} {
- defer func() {
- if err := recover(); err != nil {
- go GetHandler().Handler()
- //logger.Logger.Errorf("MqttHandler.Handler:发生异常:%s", string(debug.Stack()))
- }
- }()
- for {
- msg, ok, quantity := o.queue.Get()
- if !ok {
- time.Sleep(10 * time.Millisecond)
- continue
- } else if quantity > 1000 {
- logger.Get().Warnf("数据队列累积过多,请注意优化,当前队列条数:%d", quantity)
- }
- m, ok := msg.(*mqtt.Message)
- if !ok {
- continue
- }
- _, topic, err := parseTopic(m.Topic())
- fmt.Println(m.Topic())
- fmt.Println(m.PayloadString())
- if err != nil {
- //logger.Logger.Errorf("parseTopic err")
- continue
- }
- switch topic {
- case protocol.TopicTunnelControlAck:
- }
- }
- }
- func (o *MqttHandler) Publish(topic string, data interface{}) error {
- return mqtt.GetMQTTMgr().Publish(topic, data, mqtt.AtLeastOnce)
- }
- func (o *MqttHandler) GetTopic(deviceSn, protocol string) string {
- return fmt.Sprintf("mini/%s/%s", deviceSn, protocol)
- }
- // parseTopic 获取设备SN, topic
- // "mini/*****/switch_control/ack"
- func parseTopic(topic string) (string, string, error) {
- strList := strings.Split(topic, "/")
- if len(strList) < 4 {
- return "", "", errors.New("不支持的topic")
- }
- topic = strings.Join(strList[2:], "/")
- return strList[1], topic, nil
- }
|