Example usage for io.netty.handler.codec.mqtt MqttQoS AT_LEAST_ONCE

List of usage examples for io.netty.handler.codec.mqtt MqttQoS AT_LEAST_ONCE

Introduction

In this page you can find the example usage for io.netty.handler.codec.mqtt MqttQoS AT_LEAST_ONCE.

Prototype

MqttQoS AT_LEAST_ONCE

To view the source code for io.netty.handler.codec.mqtt MqttQoS AT_LEAST_ONCE.

Click Source Link

Usage

From source file:com.caricah.iotracah.core.handlers.protocal.http.PushHandler.java

License:Apache License

public void pushToUrl(PublishMessage publishMessage, OnPushSuccessListener onPushSuccessListener) {

    ByteBuffer payloadBuffer = ByteBuffer.wrap((byte[]) publishMessage.getPayload());

    String payload = UTF8.decode(payloadBuffer).toString();

    MultipartBody httpMessage = Unirest.post(publishMessage.getProtocolData())
            .header("accept", "application/json").field("topic", publishMessage.getTopic())
            .field("message", payload);

    if (MqttQoS.AT_LEAST_ONCE.value() == publishMessage.getQos()) {

        httpMessage.asJsonAsync(new Callback<JsonNode>() {

            public void failed(UnirestException e) {
                log.info(" httpPushToUrl failed : problems calling service", e);
            }//ww w  .  j av  a 2 s.  c o m

            public void completed(HttpResponse<JsonNode> response) {
                int code = response.getStatus();

                JsonNode responseBody = response.getBody();
                log.info(" httpPushToUrl completed : external server responded with {}", responseBody);
                if (200 == code) {

                    AcknowledgeMessage ackMessage = AcknowledgeMessage.from(publishMessage.getMessageId());
                    ackMessage.copyTransmissionData(publishMessage);

                    onPushSuccessListener.success(ackMessage);

                }
            }

            public void cancelled() {
                log.info(" httpPushToUrl cancelled : request cancelled.");
            }

        });
    } else {
        httpMessage.asJsonAsync();
    }

}

From source file:com.caricah.iotracah.core.handlers.PublishInHandler.java

License:Apache License

/**
 * A PUBLISH Control Packet is sent from a Client to a Server or from Server to a Client
 * to transport an Application Message.//from   w ww.  jav  a  2s .  c  o m
 *
 * @throws RetriableException
 * @throws UnRetriableException
 */
@Override
public void handle(PublishMessage publishMessage) throws RetriableException, UnRetriableException {

    log.debug(" handle : client attempting to publish a message.");

    /**
     * During an attempt to publish a message.
     *
     * All Topic Names and Topic Filters MUST be at least one character long [MQTT-4.7.3-1]
     *
     * The wildcard characters can be used in Topic Filters,
     * but MUST NOT be used within a Topic Name [MQTT-4.7.1-1].
     *
     * Topic Names and Topic Filters MUST NOT include the null character (Unicode U+0000) [Unicode] [MQTT-4.7.3-2]
     *
     * Topic Names and Topic Filters are UTF-8 encoded strings, they MUST NOT encode to more than 65535 bytes [MQTT-4.7.3-3]. See Section 1.5.3
     *
     */
    String topic = publishMessage.getTopic();
    if (null == topic || topic.isEmpty() || topic.contains(Constant.MULTI_LEVEL_WILDCARD)
            || topic.contains(Constant.SINGLE_LEVEL_WILDCARD) || topic.contains(Constant.SYS_PREFIX)) {
        log.info(" handle : Invalid topic " + publishMessage.getTopic());
        throw new ShutdownException(" Invalid topic name");
    }

    /**
     * Before publishing we should get the current session and validate it.
     */
    Observable<IOTClient> permissionObservable = checkPermission(publishMessage.getSessionId(),
            publishMessage.getAuthKey(), AuthorityRole.PUBLISH, topic);

    permissionObservable.subscribe((iotSession) -> {

        try {

            publishMessage.setPartitionId(iotSession.getPartitionId());
            publishMessage.setClientId(iotSession.getSessionId());
            publishMessage.setId(-1);

            /**
             * Message processing is based on 4.3 Quality of Service levels and protocol flows
             */

            /**
             *  4.3.1 QoS 0: At most once delivery
             *  Accepts ownership of the message when it receives the PUBLISH packet.
             */
            if (MqttQoS.AT_MOST_ONCE.value() == publishMessage.getQos()) {

                getMessenger().publish(iotSession.getPartitionId(), publishMessage);
            }

            /**
             * 4.3.2 QoS 1: At least once delivery
             *
             * MUST respond with a PUBACK Packet containing the Packet Identifier from the incoming PUBLISH Packet, having accepted ownership of the Application Message
             * After it has sent a PUBACK Packet the Receiver MUST treat any incoming PUBLISH packet that contains the same Packet Identifier as being a new publication, irrespective of the setting of its DUP flag.
             */
            if (MqttQoS.AT_LEAST_ONCE.value() == publishMessage.getQos()) {

                getMessenger().publish(iotSession.getPartitionId(), publishMessage);

                //We need to generate a puback message to close this conversation.

                AcknowledgeMessage acknowledgeMessage = AcknowledgeMessage.from(publishMessage.getMessageId());
                acknowledgeMessage.copyTransmissionData(publishMessage);

                pushToServer(acknowledgeMessage);

            }

            /**
             * 4.3.3 QoS 2: Exactly once delivery
             *
             * MUST respond with a PUBREC containing the Packet Identifier from the incoming PUBLISH Packet, having accepted ownership of the Application Message.
             * Until it has received the corresponding PUBREL packet, the Receiver MUST acknowledge any subsequent PUBLISH packet with the same Packet Identifier by sending a PUBREC.
             * It MUST NOT cause duplicate messages to be delivered to any onward recipients in this case.
             *
             */

            if (MqttQoS.EXACTLY_ONCE.value() == publishMessage.getQos()) {

                queueQos2Message(publishMessage);
            }

        } catch (UnRetriableException | RetriableException e) {
            disconnectDueToError(e, publishMessage);
        }

    }, throwable -> disconnectDueToError(throwable, publishMessage)

    );

}

From source file:com.caricah.iotracah.core.worker.DumbWorker.java

License:Apache License

/**
 * Provides the Observer with a new item to observe.
 * <p>/*w  ww. ja va2s  . com*/
 * The {@link com.caricah.iotracah.core.modules.Server} may call this method 0 or more times.
 * <p>
 * The {@code Observable} will not call this method again after it calls either {@link #onCompleted} or
 * {@link #onError}.
 *
 * @param iotMessage the item emitted by the Observable
 */
@Override
public void onNext(IOTMessage iotMessage) {

    getExecutorService().submit(() -> {
        log.info(" onNext : received {}", iotMessage);
        try {

            IOTMessage response = null;

            switch (iotMessage.getMessageType()) {
            case ConnectMessage.MESSAGE_TYPE:
                ConnectMessage connectMessage = (ConnectMessage) iotMessage;
                response = ConnectAcknowledgeMessage.from(connectMessage.isDup(), connectMessage.getQos(),
                        connectMessage.isRetain(), connectMessage.getKeepAliveTime(),
                        MqttConnectReturnCode.CONNECTION_ACCEPTED);

                break;
            case SubscribeMessage.MESSAGE_TYPE:

                SubscribeMessage subscribeMessage = (SubscribeMessage) iotMessage;

                List<Integer> grantedQos = new ArrayList<>();
                subscribeMessage.getTopicFilterList().forEach(topic -> {

                    String topicKey = quickCheckIdKey("",
                            Arrays.asList(topic.getKey().split(Constant.PATH_SEPARATOR)));

                    Set<String> channelIds = subscriptions.get(topicKey);

                    if (Objects.isNull(channelIds)) {
                        channelIds = new HashSet<>();
                    }

                    channelIds.add(subscribeMessage.getConnectionId());
                    subscriptions.put(topicKey, channelIds);

                    grantedQos.add(topic.getValue());

                });

                response = SubscribeAcknowledgeMessage.from(subscribeMessage.getMessageId(), grantedQos);

                break;
            case UnSubscribeMessage.MESSAGE_TYPE:
                UnSubscribeMessage unSubscribeMessage = (UnSubscribeMessage) iotMessage;
                response = UnSubscribeAcknowledgeMessage.from(unSubscribeMessage.getMessageId());

                break;
            case Ping.MESSAGE_TYPE:
                response = iotMessage;
                break;
            case PublishMessage.MESSAGE_TYPE:

                PublishMessage publishMessage = (PublishMessage) iotMessage;

                Set<String> matchingTopics = getMatchingSubscriptions("", publishMessage.getTopic());

                for (String match : matchingTopics) {
                    Set<String> channelIds = subscriptions.get(match);

                    if (Objects.nonNull(channelIds)) {

                        channelIds.forEach(id -> {

                            PublishMessage clonePublishMessage = publishMessage.cloneMessage();
                            clonePublishMessage.copyTransmissionData(iotMessage);
                            clonePublishMessage.setConnectionId(id);
                            pushToServer(clonePublishMessage);
                        });

                    }

                }

                if (MqttQoS.AT_MOST_ONCE.value() == publishMessage.getQos()) {

                    break;

                } else if (MqttQoS.AT_LEAST_ONCE.value() == publishMessage.getQos()) {

                    response = AcknowledgeMessage.from(publishMessage.getMessageId());
                    break;

                }

            case PublishReceivedMessage.MESSAGE_TYPE:
            case ReleaseMessage.MESSAGE_TYPE:
            case CompleteMessage.MESSAGE_TYPE:
            case DisconnectMessage.MESSAGE_TYPE:
            case AcknowledgeMessage.MESSAGE_TYPE:
            default:
                DisconnectMessage disconnectMessage = DisconnectMessage.from(true);
                disconnectMessage.copyTransmissionData(iotMessage);

                throw new ShutdownException(disconnectMessage);

            }

            if (Objects.nonNull(response)) {

                response.copyTransmissionData(iotMessage);
                pushToServer(response);
            }

        } catch (ShutdownException e) {

            IOTMessage response = e.getResponse();
            if (Objects.nonNull(response)) {
                pushToServer(response);
            }

        } catch (Exception e) {
            log.error(" onNext : Serious error that requires attention ", e);
        }

    });
}

From source file:examples.VertxMqttClientExamples.java

License:Apache License

/**
 * Example for sending publish message/*  w  w w  .j ava 2  s  .c  o m*/
 *
 * @param client
 */
public void example3(MqttClient client) {
    client.publish("temperature", Buffer.buffer("hello"), MqttQoS.AT_LEAST_ONCE, false, false);
}

From source file:examples.VertxMqttClientExamples.java

License:Apache License

/**
 * Example for publishCompletionHandler method demonstration
 *
 * @param client/* w  w w .  j av  a  2 s.com*/
 */
public void example5(MqttClient client) {
    client.publishCompletionHandler(id -> {
        System.out.println("Id of just received PUBACK or PUBCOMP packet is " + id);
    })
            // The line of code below will trigger publishCompletionHandler (QoS 2)
            .publish("hello", Buffer.buffer("hello"), MqttQoS.EXACTLY_ONCE, false, false)
            // The line of code below will trigger publishCompletionHandler (QoS is 1)
            .publish("hello", Buffer.buffer("hello"), MqttQoS.AT_LEAST_ONCE, false, false)
            // The line of code below does not trigger because QoS value is 0
            .publish("hello", Buffer.buffer("hello"), MqttQoS.AT_LEAST_ONCE, false, false);

}

From source file:examples.VertxMqttServerExamples.java

License:Apache License

/**
 * Example for handling client published message
 * @param endpoint//from   w  ww  . j  a  va  2s .  c  o m
 */
public void example6(MqttEndpoint endpoint) {

    // handling incoming published messages
    endpoint.publishHandler(message -> {

        System.out.println("Just received message [" + message.payload().toString(Charset.defaultCharset())
                + "] with QoS [" + message.qosLevel() + "]");

        if (message.qosLevel() == MqttQoS.AT_LEAST_ONCE) {
            endpoint.publishAcknowledge(message.messageId());
        } else if (message.qosLevel() == MqttQoS.EXACTLY_ONCE) {
            endpoint.publishRelease(message.messageId());
        }

    }).publishReleaseHandler(messageId -> {

        endpoint.publishComplete(messageId);
    });
}

From source file:io.crate.mqtt.netty.Client.java

License:Open Source License

public void disconnect() {
    LOGGER.debug("[mqtt-client] disconnect");
    sendMessage(MqttMessages.newDisconnectMessage(MqttQoS.AT_LEAST_ONCE));
}

From source file:io.crate.mqtt.operations.MqttPingIntegrationTest.java

@Test
public void testPing() throws Exception {
    mqttClient.sendMessage(MqttMessages.newPingRequest(MqttQoS.AT_LEAST_ONCE));
    MqttMessage response = mqttClient.lastReceivedMessage();
    assertThat(response.fixedHeader().messageType(), is(MqttMessageType.PINGRESP));
}

From source file:io.crate.mqtt.protocol.MqttProcessor.java

public void handlePingReq(Channel channel) {
    channel.writeAndFlush(MqttMessageFactory.newPingResponse(MqttQoS.AT_LEAST_ONCE))
            .addListener(cf -> LOGGER.info("PINGRESP sent"));
}

From source file:io.crate.mqtt.protocol.MqttProcessorTest.java

@Test
public void testConnectWithWrongMqttVersion() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel();

    MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_LEAST_ONCE,
            false, 0);//from   w  ww  .jav a2  s . c o m
    MqttConnectVariableHeader variableHeader = new MqttConnectVariableHeader("connect", (byte) 1, false, false,
            false, (byte) 1, false, false, 60);
    MqttConnectPayload payload = new MqttConnectPayload("mqttClient", "someTopic", new byte[0], null, null);
    processor.handleConnect(ch, (MqttConnectMessage) io.netty.handler.codec.mqtt.MqttMessageFactory
            .newMessage(fixedHeader, variableHeader, payload));

    MqttConnAckMessage response = ch.readOutbound();
    assertThat(response.variableHeader().connectReturnCode(),
            is(MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION));
    assertFalse(response.variableHeader().isSessionPresent());
}