use of org.eclipse.paho.client.mqttv3.MqttClient in project activemq-artemis by apache.
the class PahoMQTTTest method testSendAndReceiveMQTT.
@Test(timeout = 300000)
public void testSendAndReceiveMQTT() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient("consumerId");
MqttClient producer = createPahoClient("producerId");
consumer.connect();
consumer.subscribe("test");
consumer.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
latch.countDown();
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
producer.connect();
producer.publish("test", "hello".getBytes(), 1, false);
waitForLatch(latch);
producer.disconnect();
producer.close();
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project FogLight-Examples by oci-pronghorn.
the class PublishDataMQTT method message.
@Override
public boolean message(CharSequence topic, ChannelReader payload) {
try {
if (null == client) {
client = new MqttClient(serverURI, clientId, new MemoryPersistence());
}
MqttMessage message = new MqttMessage();
int payloadSize = payload.available();
byte[] data = new byte[payloadSize];
payload.read(data);
message.setPayload(data);
message.setRetained(false);
message.setQos(QOS);
client.connect(connOptions);
client.setTimeToWait(-1);
StringBuilder builder = new StringBuilder();
builder.append(root).append('/');
builder.append(clientId).append('/');
builder.append(topic);
logger.info("publish MQTT {} {}", QOS, builder.toString());
client.publish(builder.toString(), message);
client.disconnect();
} catch (MqttException e) {
client = null;
logger.warn("Unable to send payload", e);
}
return true;
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project FogLight-Examples by oci-pronghorn.
the class MQTTPublishPAHOStage method message.
public boolean message(StringBuilder topic, byte[] data) {
try {
if (null == client) {
client = new MqttClient(serverURI, clientId, new MemoryPersistence());
client.connect(connOptions);
client.setTimeToWait(-1);
}
MqttMessage message = new MqttMessage();
message.setPayload(data);
message.setRetained(retained);
message.setQos(QOS);
nextMessageTime = System.currentTimeMillis() + TIME_LIMIT;
client.publish(topic.toString(), message);
errorCount = 0;
logger.info("publish MQTT QOS: {} topic: {}", QOS, topic);
return true;
} catch (MqttException e) {
if (e.getMessage().contains("is not connected")) {
client = null;
return false;
}
try {
client.disconnect();
} catch (MqttException e1) {
// ignore
}
client = null;
if (++errorCount > 10) {
logger.warn("Unable to send payload, is the MQTT broaker {} up and running?", serverURI, e);
}
return false;
}
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project FogLight-Examples by oci-pronghorn.
the class SubscribeDataMQTT method startup.
@Override
public void startup() {
try {
client = new MqttClient(serverURI, clientId, new MemoryPersistence());
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
logger.warn("connection lost, re-subscribe after timeout");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// call startup again.
startup();
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
logger.info("received MQTT message on topic {}", topic);
commandChannel.publishTopic(publishTopic, w -> {
w.writeUTF(topic);
w.write(message.getPayload());
});
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
client.connect(connOptions);
// client.setTimeToWait(-1);
client.subscribe(subscriptionTopic, 1);
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project openhab1-addons by openhab.
the class MqttBrokerConnection method openConnection.
/**
* Open an MQTT client connection.
*
* @throws Exception
*/
private void openConnection() throws Exception {
if (client != null && client.isConnected()) {
return;
}
if (StringUtils.isBlank(url)) {
throw new Exception("Missing url");
}
if (client == null) {
if (StringUtils.isBlank(clientId) || clientId.length() > 23) {
clientId = MqttClient.generateClientId();
}
String tmpDir = System.getProperty("java.io.tmpdir") + "/" + name;
MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
logger.debug("Creating new client for '{}' using id '{}' and file store '{}'", url, clientId, tmpDir);
client = new MqttClient(url, clientId, dataStore);
client.setCallback(this);
}
MqttConnectOptions options = new MqttConnectOptions();
if (!StringUtils.isBlank(user)) {
options.setUserName(user);
}
if (!StringUtils.isBlank(password)) {
options.setPassword(password.toCharArray());
}
if (url.toLowerCase().contains("ssl")) {
if (StringUtils.isNotBlank(System.getProperty("com.ibm.ssl.protocol"))) {
// get all com.ibm.ssl properties from the system properties
// and set them as the SSL properties to use.
Properties sslProps = new Properties();
addSystemProperty("com.ibm.ssl.protocol", sslProps);
addSystemProperty("com.ibm.ssl.contextProvider", sslProps);
addSystemProperty("com.ibm.ssl.keyStore", sslProps);
addSystemProperty("com.ibm.ssl.keyStorePassword", sslProps);
addSystemProperty("com.ibm.ssl.keyStoreType", sslProps);
addSystemProperty("com.ibm.ssl.keyStoreProvider", sslProps);
addSystemProperty("com.ibm.ssl.trustStore", sslProps);
addSystemProperty("com.ibm.ssl.trustStorePassword", sslProps);
addSystemProperty("com.ibm.ssl.trustStoreType", sslProps);
addSystemProperty("com.ibm.ssl.trustStoreProvider", sslProps);
addSystemProperty("com.ibm.ssl.enabledCipherSuites", sslProps);
addSystemProperty("com.ibm.ssl.keyManager", sslProps);
addSystemProperty("com.ibm.ssl.trustManager", sslProps);
options.setSSLProperties(sslProps);
} else {
// use standard JSSE available in the runtime and
// use TLSv1.2 which is the default for a secured mosquitto
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, new TrustManager[] { getVeryTrustingTrustManager() }, new java.security.SecureRandom());
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
options.setSocketFactory(socketFactory);
}
}
if (lastWill != null) {
options.setWill(lastWill.getTopic(), lastWill.getPayload(), lastWill.getQos(), lastWill.isRetain());
}
options.setKeepAliveInterval(keepAliveInterval);
client.connect(options);
}
Aggregations