use of org.eclipse.paho.client.mqttv3.MqttClient in project kafka-connect-mqtt by jcustenborder.
the class MqttSourceTask method start.
@Override
public void start(Map<String, String> settings) {
this.config = new MqttSourceConnectorConfig(settings);
this.sourceConverter = new SourceConverter(this.config, this.time);
this.records = SourceRecordDequeBuilder.of().batchSize(4096).emptyWaitMs(100).maximumCapacityTimeoutMs(60000).maximumCapacity(50000).build();
try {
this.client = new MqttClient(this.config.serverUri.get(0), MqttClient.generateClientId());
} catch (MqttException e) {
throw new ConnectException(e);
}
try {
log.info("Connecting to Mqtt Server.");
this.client.connect(this.config.connectOptions());
} catch (MqttException e) {
throw new ConnectException(e);
}
final String[] topicSubscriptions = this.config.mqttTopics.toArray(new String[this.config.mqttTopics.size()]);
final int[] qosLevels = new int[] { this.config.mqttQos };
try {
log.info("Subscribing to {} with QOS of {}", Joiner.on(',').join(topicSubscriptions), this.config.mqttQos);
this.client.subscribe(topicSubscriptions, qosLevels, new IMqttMessageListener[] { this });
} catch (MqttException e) {
throw new ConnectException(e);
}
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project activemq-artemis by apache.
the class PahoMQTTTest method testLotsOfClients.
@Test(timeout = 300000)
public void testLotsOfClients() throws Exception {
final int CLIENTS = Integer.getInteger("PahoMQTTTest.CLIENTS", 100);
LOG.info("Using: {} clients: " + CLIENTS);
final AtomicInteger receiveCounter = new AtomicInteger();
MqttClient client = createPahoClient("consumer");
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
receiveCounter.incrementAndGet();
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
client.connect();
client.subscribe("test");
final AtomicReference<Throwable> asyncError = new AtomicReference<>();
final CountDownLatch connectedDoneLatch = new CountDownLatch(CLIENTS);
final CountDownLatch disconnectDoneLatch = new CountDownLatch(CLIENTS);
final CountDownLatch sendBarrier = new CountDownLatch(1);
for (int i = 0; i < CLIENTS; i++) {
Thread.sleep(10);
new Thread(null, null, "client:" + i) {
@Override
public void run() {
try {
MqttClient client = createPahoClient(Thread.currentThread().getName());
client.connect();
connectedDoneLatch.countDown();
sendBarrier.await();
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
client.publish("test", "hello".getBytes(), 1, false);
}
client.disconnect();
client.close();
} catch (Throwable e) {
e.printStackTrace();
asyncError.set(e);
} finally {
disconnectDoneLatch.countDown();
}
}
}.start();
}
connectedDoneLatch.await();
assertNull("Async error: " + asyncError.get(), asyncError.get());
sendBarrier.countDown();
LOG.info("All clients connected... waiting to receive sent messages...");
// We should eventually get all the messages.
within(30, TimeUnit.SECONDS, new Task() {
@Override
public void run() throws Exception {
assertTrue(receiveCounter.get() == CLIENTS * 10);
}
});
LOG.info("All messages received.");
disconnectDoneLatch.await();
assertNull("Async error: " + asyncError.get(), asyncError.get());
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project Applozic-Android-SDK by AppLozic.
the class ApplozicMqttService method publishTopic.
public synchronized void publishTopic(final String applicationId, final String status, final String loggedInUserId, final String userId) {
try {
final MqttClient client = connect();
if (client == null || !client.isConnected()) {
return;
}
MqttMessage message = new MqttMessage();
message.setRetained(false);
message.setPayload((applicationId + "," + loggedInUserId + "," + status).getBytes());
message.setQos(0);
client.publish("typing" + "-" + applicationId + "-" + userId, message);
Utils.printLog(context, TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + userId);
} catch (Exception e) {
e.printStackTrace();
}
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project Applozic-Android-SDK by AppLozic.
the class ApplozicMqttService method unSubscribeToTypingTopic.
public synchronized void unSubscribeToTypingTopic(Channel channel) {
try {
String currentId = null;
if (channel != null) {
currentId = String.valueOf(channel.getKey());
} else {
MobiComUserPreference mobiComUserPreference = MobiComUserPreference.getInstance(context);
currentId = mobiComUserPreference.getUserId();
}
final MqttClient client = connect();
if (client == null || !client.isConnected()) {
return;
}
client.unsubscribe("typing-" + getApplicationKey(context) + "-" + currentId);
Utils.printLog(context, TAG, "UnSubscribed to topic: " + "typing-" + getApplicationKey(context) + "-" + currentId);
} catch (Exception e) {
e.printStackTrace();
}
}
use of org.eclipse.paho.client.mqttv3.MqttClient in project joynr by bmwcarit.
the class MqttPahoClientTest method mqttClientTestResubscriptionWithCleanRestartEnabled.
@Test
public void mqttClientTestResubscriptionWithCleanRestartEnabled() throws Exception {
properties.put(MqttModule.PROPERTY_KEY_MQTT_BROKER_URI, "tcp://localhost:1883");
injector = Guice.createInjector(new MqttPahoModule(), new JoynrPropertiesModule(properties), new AbstractModule() {
@Override
protected void configure() {
bind(MessageRouter.class).toInstance(mockMessageRouter);
bind(ScheduledExecutorService.class).annotatedWith(Names.named(MessageRouter.SCHEDULEDTHREADPOOL)).toInstance(Executors.newScheduledThreadPool(10));
bind(RawMessagingPreprocessor.class).to(NoOpRawMessagingPreprocessor.class);
Multibinder.newSetBinder(binder(), new TypeLiteral<JoynrMessageProcessor>() {
});
}
});
ownTopic = injector.getInstance((Key.get(MqttAddress.class, Names.named(MqttModule.PROPERTY_MQTT_GLOBAL_ADDRESS))));
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
MqttClientIdProvider mqttClientIdProvider = injector.getInstance(MqttClientIdProvider.class);
String clientId = mqttClientIdProvider.getClientId();
String brokerUri = "tcp://localhost:1883";
int reconnectSleepMs = 100;
int keepAliveTimerSec = 60;
int connectionTimeoutSec = 60;
int timeToWaitMs = -1;
int maxMsgsInflight = 100;
int maxMsgSizeBytes = 0;
boolean cleanSession = true;
MqttClient mqttClient = new MqttClient(brokerUri, clientId, new MemoryPersistence(), scheduledExecutorService);
joynrMqttClient = new MqttPahoClient(mqttClient, reconnectSleepMs, keepAliveTimerSec, connectionTimeoutSec, timeToWaitMs, maxMsgsInflight, maxMsgSizeBytes, cleanSession, "", "", "", "", mock(MqttStatusReceiver.class));
joynrMqttClient.start();
joynrMqttClient.setMessageListener(mockReceiver);
joynrMqttClient.subscribe(ownTopic.getTopic());
// manually call disconnect and connectionLost
mqttClient.disconnect(500);
MqttException exeption = new MqttException(MqttException.REASON_CODE_CLIENT_TIMEOUT);
MqttPahoClient mqttPahoClient = (MqttPahoClient) joynrMqttClient;
mqttPahoClient.connectionLost(exeption);
joynrMqttClientPublishAndVerifyReceivedMessage(serializedMessage);
}
Aggregations