zhubaomin
2 天以前 10a0b0ca34824307aa7d23b0ad6679b36bd57842
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.dy.rtuMw.server.mqtt;
 
import com.dy.common.mw.protocol4Mqtt.*;
import com.dy.common.mw.protocol4Mqtt.MqttCallback;
import com.dy.common.mw.protocol4Mqtt.MqttTopic;
import com.dy.common.util.Callback;
import com.dy.rtuMw.server.forTcp.RtuLogDealer;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.* ;
 
/**
 * @Author: liurunyu
 * @Date: 2025/6/4 15:52
 * @Description
 */
@Slf4j
public class MqttMessageListener implements IMqttMessageListener{
    private MqttNotify notify ;
    public MqttMessageListener(MqttNotify notify){
        this.notify = notify ;
    }
 
    @Override
    public void messageArrived(String topic, MqttMessage msg) throws Exception {
        MqttTopic subTopic = MqttMsgParser.parseSubTopic(topic) ;
        MqttSubMsg subMsg = MqttMsgParser.parseSubMsg(subTopic, msg, new MqttCallback(){
            @Override
            public void callback(MqttSubMsg subMsg) {
                DevStatusDealer.onLine(subMsg.deviceId, subMsg.protocol);
                DevStatusDealer.afterReceiveSubMessage(subMsg.deviceId);
                RtuLogDealer.log4Mqtt(subMsg.deviceId, "订阅消息    主题:" + subMsg.topic + "   消息:" + subMsg.msg);
            }
            @Override
            public void notify(String devId, MqttNotifyInfo... infos) {
                if(notify != null){
                    notify.notify(devId, infos) ;
                }
            }
        }) ;
        this.nextDeal(subMsg);
    }
    private void nextDeal(MqttSubMsg subMsg)throws Exception {
        subMsg.action(new Callback() {
            @Override
            public void call(Object obj) {
                MqttSubMsg subMs = (MqttSubMsg) obj ;
                MqttPubMsg pubMs = MqttPubMsgCache.matchFromTail(subMs) ;
                if(pubMs != null){
                    //匹配到下行消息(命令)
                    subMs.mqttResultSendWebUrl = pubMs.mqttResultSendWebUrl ;
                    subMs.commandId = pubMs.commandId ;
                    try {
                        MqttComResultCache.getInstance().cacheMqttComResult(new MqttComResultNode(subMs));
                    } catch (Exception e) {
                        log.error("缓存发布消息(命令)结果发生异常", e);
                    }
                }
                try{
                    MqttSubMsgCache.getInstance().cacheMsg(new MqttSubMsgNode(subMsg));
                }catch (Exception e){
                    log.error("缓存订阅消息数据发生异常", e);
                }
            }
            @Override
            public void call(Object... objs) {
            }
            @Override
            public void exception(Exception e) {
            }
        });
    }
}