All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feingto.iot.server.handler.MqttMessageHandler Maven / Gradle / Ivy

There is a newer version: 1.2.5.RELEASE
Show newest version
package com.feingto.iot.server.handler;

import com.feingto.iot.common.handler.DefaultSimpleChannelHandler;
import com.feingto.iot.common.model.mqtt.SendMessage;
import com.feingto.iot.common.model.mqtt.SessionStore;
import com.feingto.iot.server.cache.SessionCache;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * Mqtt 消息处理器
 *
 * @author longfei
 */
@Slf4j
@Sharable
public class MqttMessageHandler extends DefaultSimpleChannelHandler {
    @Override
    public void handleMessage(ChannelHandlerContext ctx, MqttMessage msg) {
        MqttFixedHeader header = msg.fixedHeader();
        if (header == null) {
            return;
        }

        MqttHandlerChain.getHandler().proceed(header.messageType(), ctx.channel(), msg);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state() == IdleState.ALL_IDLE) {
                String clientId = (String) ctx.channel().attr(AttributeKey.valueOf("clientId")).get();
                // 发布遗嘱消息
                Optional.ofNullable(SessionCache.getInstance().get(clientId))
                        .filter(sess -> sess.willMessage() != null)
                        .map(SessionStore::willMessage)
                        .ifPresent(msg -> {
                            log.debug(">>> publish will message to {}", clientId);
                            MqttHandlerChain.getInstance().pushService.internalSend(SendMessage.newInstance(msg));
                        });
                ctx.close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy