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);
}
}
}
});
}
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);
}
});
}
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);
}
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()));
}
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;
}
Aggregations