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

com.feingto.iot.common.service.MqttConsumer Maven / Gradle / Ivy

There is a newer version: 2.3.3.RELEASE
Show newest version
package com.feingto.iot.common.service;

import com.feingto.iot.common.bootstrap.MqttConsumerBootstrap;
import com.feingto.iot.common.config.properties.NettyProperties;
import com.feingto.iot.common.model.mqtt.SendMessage;
import com.feingto.iot.common.model.mqtt.SubscribeMessage;
import com.feingto.iot.common.service.mqtt.IMessageConsume;
import com.feingto.iot.common.service.mqtt.MessageRequest;
import com.feingto.iot.common.util.MessageId;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.handler.codec.mqtt.MqttTopicSubscription;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * MQTT 消费者
 *
 * @author longfei
 */
@Slf4j
@Accessors(fluent = true)
public class MqttConsumer {
    private Channel channel;
    @Setter
    private IMessageConsume messageService;

    /**
     * 连接服务端
     */
    public void connect(NettyProperties config) {
        try {
            this.channel = new MqttConsumerBootstrap(config).messageService(messageService).start();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("IoT client exception: {}", e.getMessage());
        }
    }

    /**
     * 推送消息至主题
     */
    public void publish(String topic, String message) {
        this.publish(topic, message, false, 0);
    }

    /**
     * 推送Qos消息至主题
     */
    public void publish(String topic, String message, int qos) {
        this.publish(topic, message, false, qos);
    }

    /**
     * 推送是否保留的消息至主题
     */
    public void publish(String topic, String message, boolean retained) {
        this.publish(topic, message, retained, 0);
    }

    /**
     * 推送是否保留的Qos消息至主题
     */
    public void publish(String topic, String message, boolean retained, int qos) {
        MessageRequest.publish(channel, new SendMessage()
                .id(MessageId.messageId())
                .topic(topic)
                .mqttQoS(MqttQoS.valueOf(qos))
                .retain(retained)
                .payload(message.getBytes()));
    }

    /**
     * 订阅
     */
    public void subscribe(SubscribeMessage... messages) {
        MessageRequest.subscribe(channel, Stream.of(messages)
                .map(message -> new MqttTopicSubscription(message.topicName(), MqttQoS.valueOf(message.mqttQoS())))
                .collect(Collectors.toList()), MessageId.messageId());
    }

    /**
     * 取消订阅
     */
    public void unsubscribe(String... topics) {
        MessageRequest.unsubscribe(channel, Arrays.asList(topics), MessageId.messageId());
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy