Search in sources :

Example 1 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project openhab1-addons by openhab.

the class MqttBrokerConnection method startProducer.

/**
     * Start a registered producer, so that it can start sending messages.
     * 
     * @param publisher
     *            to start.
     */
private void startProducer(MqttMessageProducer publisher) {
    logger.trace("Starting message producer for broker '{}'", name);
    publisher.setSenderChannel(new MqttSenderChannel() {

        @Override
        public void publish(String topic, byte[] payload) throws Exception {
            if (!started) {
                logger.warn("Broker connection not started. Cannot publish message to topic '{}'", topic);
                return;
            }
            // Create and configure a message
            MqttMessage message = new MqttMessage(payload);
            message.setQos(qos);
            message.setRetained(retain);
            // publish message asynchronously
            MqttTopic mqttTopic = client.getTopic(topic);
            MqttDeliveryToken deliveryToken = mqttTopic.publish(message);
            logger.debug("Publishing message {} to topic '{}'", deliveryToken.getMessageId(), topic);
            if (!async) {
                // wait for publish confirmation
                deliveryToken.waitForCompletion(10000);
                if (!deliveryToken.isComplete()) {
                    logger.error("Did not receive completion message within timeout limit whilst publishing to topic '{}'", topic);
                }
            }
        }
    });
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttTopic(org.eclipse.paho.client.mqttv3.MqttTopic) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) MqttDeliveryToken(org.eclipse.paho.client.mqttv3.MqttDeliveryToken) MqttSenderChannel(org.openhab.io.transport.mqtt.MqttSenderChannel) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 2 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project camel by apache.

the class PahoConsumer method doStart.

@Override
protected void doStart() throws Exception {
    super.doStart();
    String topic = getEndpoint().getTopic();
    getEndpoint().getClient().subscribe(topic);
    getEndpoint().getClient().setCallback(new MqttCallback() {

        @Override
        public void connectionLost(Throwable cause) {
            LOG.debug("MQTT broker connection lost due " + cause.getMessage(), cause);
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            LOG.debug("Message arrived on topic: {} -> {}", topic, message);
            Exchange exchange = getEndpoint().createExchange(message, topic);
            getAsyncProcessor().process(exchange, new AsyncCallback() {

                @Override
                public void done(boolean doneSync) {
                // noop
                }
            });
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            LOG.debug("Delivery complete. Token: {}", token);
        }
    });
}
Also used : Exchange(org.apache.camel.Exchange) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) AsyncCallback(org.apache.camel.AsyncCallback) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)

Example 3 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project camel by apache.

the class PahoProducer method process.

@Override
public void process(Exchange exchange) throws Exception {
    MqttClient client = getEndpoint().getClient();
    String topic = getEndpoint().getTopic();
    int qos = exchange.getIn().getHeader(PahoConstants.CAMEL_PAHO_MSG_QOS, getEndpoint().getQos(), Integer.class);
    boolean retained = exchange.getIn().getHeader(PahoConstants.CAMEL_PAHO_MSG_RETAINED, getEndpoint().isRetained(), Boolean.class);
    byte[] payload = exchange.getIn().getBody(byte[].class);
    MqttMessage message = new MqttMessage(payload);
    message.setQos(qos);
    message.setRetained(retained);
    client.publish(topic, message);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage)

Example 4 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project camel by apache.

the class PahoComponentTest method shouldKeepOriginalMessageInHeader.

@Test
public void shouldKeepOriginalMessageInHeader() throws InterruptedException {
    // Given
    final String msg = "msg";
    mock.expectedBodiesReceived(msg);
    // When
    template.sendBody("direct:test2", msg);
    // Then
    mock.assertIsSatisfied();
    Exchange exchange = mock.getExchanges().get(0);
    MqttMessage message = exchange.getIn(PahoMessage.class).getMqttMessage();
    assertNotNull(message);
    assertEquals(msg, new String(message.getPayload()));
}
Also used : Exchange(org.apache.camel.Exchange) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) Test(org.junit.Test)

Example 5 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project pentaho-kettle by pentaho.

the class MQTTProducer method processRow.

@Override
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    Object[] row = getRow();
    if (null == row) {
        setOutputDone();
        if (null != data.mqttClient) {
            try {
                data.mqttClient.disconnect();
                data.mqttClient.close();
            } catch (MqttException e) {
                logError(e.getMessage(), e);
            }
        }
        return false;
    }
    if (first) {
        logDebug("Publishing using a quality of service level of " + environmentSubstitute(meta.getQOS()));
        data.messageFieldIndex = getInputRowMeta().indexOfValue(environmentSubstitute(meta.getMessageField()));
        try {
            data.mqttClient = MQTTClientBuilder.builder().withBroker(meta.getMqttServer()).withTopics(Collections.singletonList(meta.getTopic())).withClientId(meta.getClientId()).withQos(meta.getQOS()).withStep(this).withUsername(meta.getUsername()).withPassword(meta.getPassword()).withSslConfig(meta.getSslConfig()).withIsSecure(meta.isUseSsl()).withKeepAliveInterval(meta.getKeepAliveInterval()).withMaxInflight(meta.getMaxInflight()).withConnectionTimeout(meta.getConnectionTimeout()).withCleanSession(meta.getCleanSession()).withStorageLevel(meta.getStorageLevel()).withServerUris(meta.getServerUris()).withMqttVersion(meta.getMqttVersion()).withAutomaticReconnect(meta.getAutomaticReconnect()).buildAndConnect();
        } catch (MqttException e) {
            stopAll();
            logError(e.toString());
            return false;
        }
        first = false;
    }
    MqttMessage mqttMessage = new MqttMessage();
    try {
        mqttMessage.setQos(Integer.parseInt(environmentSubstitute(meta.getQOS())));
    } catch (NumberFormatException e) {
        throw new KettleStepException(BaseMessages.getString(PKG, "MQTTProducer.Error.QOS", environmentSubstitute(meta.getQOS())));
    }
    mqttMessage.setPayload((row[data.messageFieldIndex]).toString().getBytes(defaultCharset()));
    try {
        data.mqttClient.publish(environmentSubstitute(meta.getTopic()), mqttMessage);
        incrementLinesOutput();
        // copy row to possible alternate rowset(s).
        putRow(getInputRowMeta(), row);
        if (checkFeedback(getLinesRead())) {
            if (log.isBasic()) {
                logBasic(BaseMessages.getString(PKG, "MQTTProducer.Log.LineNumber") + getLinesRead());
            }
        }
    } catch (MqttException e) {
        logError(BaseMessages.getString(PKG, "MQTTProducer.Error.QOSNotSupported", meta.getQOS()));
        logError(e.getMessage(), e);
        setErrors(1);
        stopAll();
    }
    return true;
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) KettleStepException(org.pentaho.di.core.exception.KettleStepException) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Aggregations

MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)64 MqttException (org.eclipse.paho.client.mqttv3.MqttException)28 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)19 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)16 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)16 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)15 Test (org.junit.Test)14 MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)8 CountDownLatch (java.util.concurrent.CountDownLatch)4 JsonParser (com.google.gson.JsonParser)3 IOException (java.io.IOException)3 MqttAsyncClient (org.eclipse.paho.client.mqttv3.MqttAsyncClient)3 JSONObject (org.json.JSONObject)3 Test (org.testng.annotations.Test)3 JsonArray (com.google.gson.JsonArray)2 JsonObject (com.google.gson.JsonObject)2 MISTEdge (edu.snu.mist.common.graph.MISTEdge)2 ArrayList (java.util.ArrayList)2 Properties (java.util.Properties)2 CamelContext (org.apache.camel.CamelContext)2