mqttClient.setCallback(mqttV3Receiver); connectToken = mqttClient.connect(null, null); connectToken.waitForCompletion(waitForCompletionTime); subToken = mqttClient.subscribe(topicNames, topicQos, null, null); subToken.waitForCompletion(waitForCompletionTime); unsubToken = mqttClient.unsubscribe(topicNames, null, null); unsubToken.waitForCompletion(waitForCompletionTime); subToken = mqttClient.subscribe(topicNames, topicQos, null, null); subToken.waitForCompletion(waitForCompletionTime); pubToken = mqttClient.publish(topicNames[0], message, 0, false, null, null); pubToken.waitForCompletion(waitForCompletionTime); try { IMqttToken disconnectToken; disconnectToken = mqttClient.disconnect(null, null); disconnectToken.waitForCompletion(waitForCompletionTime); mqttClient.close();
ConnectBG(ClientComms cc, MqttToken cToken, MqttConnect cPacket, ExecutorService executorService) { clientComms = cc; conToken = cToken; conPacket = cPacket; threadName = "MQTT Con: "+getClient().getClientId(); }
public Properties getDebug() { Properties props = new Properties(); props.put("conState", new Integer(conState)); props.put("serverURI", getClient().getServerURI()); props.put("callback", callback); props.put("stoppingComms", new Boolean(stoppingComms)); return props; }
@Override public synchronized void connectionLost(Throwable cause) { logger.error("Lost connection; will attempt reconnect on next request"); if (this.client != null) { try { this.client.setCallback(null); this.client.close(); } catch (MqttException e) { // NOSONAR } this.client = null; } }
@Override protected void doStop() { try { IMqttAsyncClient theClient = this.client; if (theClient != null) { theClient.disconnect().waitForCompletion(this.completionTimeout); theClient.close(); this.client = null; } } catch (MqttException e) { logger.error("Failed to disconnect", e); } }
private synchronized IMqttAsyncClient checkConnection() throws MqttException { if (this.client != null && !this.client.isConnected()) { this.client.setCallback(null); this.client.close(); this.client = null; } if (this.client == null) { try { MqttConnectOptions connectionOptions = this.clientFactory.getConnectionOptions(); Assert.state(this.getUrl() != null || connectionOptions.getServerURIs() != null, "If no 'url' provided, connectionOptions.getServerURIs() must not be null"); this.client = this.clientFactory.getAsyncClientInstance(this.getUrl(), this.getClientId()); incrementClientInstance(); this.client.setCallback(this); this.client.connect(connectionOptions).waitForCompletion(this.completionTimeout); if (logger.isDebugEnabled()) { logger.debug("Client connected"); } } catch (MqttException e) { if (this.client != null) { this.client.close(); this.client = null; } throw new MessagingException("Failed to connect", e); } } return this.client; }
/** * Tests that a client can be constructed and that it can connect to and * disconnect from the service * * @throws Exception */ public void testConnect() throws Exception { IMqttAsyncClient mqttclient = null; try { mqttclient = new MqttAndroidClient(mContext,mqttServerURI, "testConnect"); IMqttToken connectToken = null; IMqttToken disconnectToken = null; connectToken = mqttclient.connect(null, null); connectToken.waitForCompletion(waitForCompletionTime); disconnectToken = mqttclient.disconnect(null, null); disconnectToken.waitForCompletion(waitForCompletionTime); connectToken = mqttclient.connect(null, null); connectToken.waitForCompletion(waitForCompletionTime); disconnectToken = mqttclient.disconnect(null, null); disconnectToken.waitForCompletion(waitForCompletionTime); } catch (Exception exception){ fail("Failed: " + "testConnect" + " exception= " + exception); } finally { if(mqttclient != null){ mqttclient.close(); } } }
private void connect() throws MqttException { if (registry.getWill().isPresent()) { final Message will = registry.getWill().get(); final MqttMessage mqttMessage = serialize(will); this.options.setWill( topicPrefix + will.getTopic(), mqttMessage.getPayload(), mqttMessage.getQos(), mqttMessage.isRetained() ); } logger.info("Connecting to {} as {}...", client.getServerURI(), client.getClientId()); client.connect(options).waitForCompletion(); logger.info("Connected."); logger.info("Subscribing to topics..."); for (final Map.Entry<String, QualityOfService> entry : registry.getSubscriptions().entrySet()) { logger.info(" - {}", topicPrefix + entry.getKey()); client.subscribe(topicPrefix + entry.getKey(), entry.getValue().ordinal()); } logger.info("Subscribed."); logger.info("Sending initial messages..."); registry.getInitialMessages().stream().forEach(this::publish); logger.info("Engine started."); }
/** * Tests isConnected() returns false after a disconnect() call. * @throws Exception */ public void testIsConnected() throws Exception { IMqttAsyncClient mqttClient = null; try { mqttClient = new MqttAndroidClient(mContext, mqttServerURI, "testConnect"); IMqttToken connectToken = null; IMqttToken disconnectToken = null; assertFalse(mqttClient.isConnected()); connectToken = mqttClient.connect(null, null); connectToken.waitForCompletion(waitForCompletionTime); assertTrue(mqttClient.isConnected()); disconnectToken = mqttClient.disconnect(null, null); disconnectToken.waitForCompletion(waitForCompletionTime); assertFalse(mqttClient.isConnected()); } finally { if (mqttClient != null) { mqttClient.close(); } } }
/** * Persists a buffered message to the persistence layer * * @param message The {@link MqttWireMessage} to persist */ public void persistBufferedMessage(MqttWireMessage message) { final String methodName = "persistBufferedMessage"; String key = getSendBufferedPersistenceKey(message); // Because the client will have disconnected, we will want to re-open persistence try { message.setMessageId(getNextMessageId()); key = getSendBufferedPersistenceKey(message); try { persistence.put(key, (MqttPublish) message); } catch (MqttPersistenceException mpe){ //@TRACE 515=Could not Persist, attempting to Re-Open Persistence Store log.fine(CLASS_NAME,methodName, "515"); persistence.open(this.clientComms.getClient().getClientId(), this.clientComms.getClient().getServerURI()); persistence.put(key, (MqttPublish) message); } //@TRACE 513=Persisted Buffered Message key={0} log.fine(CLASS_NAME,methodName, "513", new Object[]{key}); } catch (MqttException ex){ //@TRACE 514=Failed to persist buffered message key={0} log.warning(CLASS_NAME,methodName, "513", new Object[]{key}); } }
public void testConnect() throws Throwable { IMqttAsyncClient mqttClient = null; mqttClient = new MqttAndroidClient(mContext, serverURI, "testConnect"); IMqttToken connectToken = null; IMqttToken disconnectToken = null; connectToken = mqttClient.connect(null, new ActionListener(notifier)); notifier.waitForCompletion(waitForCompletionTime); disconnectToken = mqttClient.disconnect(null, new ActionListener(notifier)); notifier.waitForCompletion(waitForCompletionTime); connectToken = mqttClient.connect(null, new ActionListener(notifier)); notifier.waitForCompletion(waitForCompletionTime); disconnectToken = mqttClient.disconnect(null, new ActionListener(notifier)); notifier.waitForCompletion(waitForCompletionTime); }
@Override public void doConnect(ChannelPool pool) throws ProviderException { String poolId = pool.getId(); LOGGER.info("doConnect ChannelPool: " + poolId); Authentication auth = pool.getClient().getAuthentication(); MemoryPersistence persistence = new MemoryPersistence(); final MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(true); if (pool.getUri() == null) { pool.setUri(defaultConnectionString); LOGGER.warn(String.format("ConnectionString not specified, using public default %s", pool.getUri())); } try { mqttClient = new MqttAsyncClient(pool.getUri(), poolId, persistence); mqttClient.connect(options, new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { LOGGER.info("ChannelPool connected: " + poolId); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { LOGGER.info("ChannelPool could not establish connection: " + poolId); } }).waitForCompletion(); } catch (MqttException e) { throw new ProviderException("ChannelPool \"" + poolId + "\" cannot connect to \"" + pool.getUri() + "\"", e); } }
private void disconnect() throws MqttException { client.disconnect(); }
@Override protected void publish(String topic, Object mqttMessage, Message<?> message) throws Exception { Assert.isInstanceOf(MqttMessage.class, mqttMessage); IMqttDeliveryToken token = checkConnection() .publish(topic, (MqttMessage) mqttMessage); if (!this.async) { token.waitForCompletion(this.completionTimeout); } else if (this.asyncEvents && this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent( new MqttMessageSentEvent(this, message, topic, token.getMessageId(), getClientId(), getClientInstance())); } }
@Test public void testCloseOnBadConnectOut() throws Exception { final IMqttAsyncClient client = mock(IMqttAsyncClient.class); willThrow(new MqttException(0)).given(client).connect(any()); MqttPahoMessageHandler adapter = buildAdapterOut(client); adapter.start(); try { adapter.handleMessage(new GenericMessage<>("foo")); fail("exception expected"); } catch (MessageHandlingException e) { // NOSONAR } verify(client).close(); adapter.stop(); }
@Override public void installIncomingChannel(String externalChannelName, String internalChannelName) { Channel internalChannel = cf.openChannel(context.getSharedChannelPool(), internalChannelName, false, null); try { mqttClient.subscribe(externalChannelName, 2, new IMqttMessageListener() { // TODO: unterscheiden handleNotification/Request @Override public void messageArrived(String topic, MqttMessage message) throws Exception { String mqttPayload = new String(message.getPayload(), StandardCharsets.UTF_8); Notification not = CommFactory.getInstance().createNotification(mqttPayload); internalChannel.sendNotification(not); } }).waitForCompletion(); incoming.put(externalChannelName,internalChannel); } catch (MqttException e) { throw new ProviderException("Cannot subscribe MqttGateway to topic \"" + externalChannelName + "\"", e); } }
persistence ); this.client.setCallback(this);
public void testHAConnect() throws Exception{ String methodName = "testHAConnect"; IMqttAsyncClient client = null; try { try { String junk = "tcp://junk:123"; client = new MqttAndroidClient(mContext, junk, methodName); String[] urls = new String[]{"tcp://junk", mqttServerURI}; MqttConnectOptions options = new MqttConnectOptions(); options.setServerURIs(urls); Log.i(methodName, "HA connect"); IMqttToken connectToken = client.connect(options); connectToken.waitForCompletion(waitForCompletionTime); Log.i(methodName, "HA disconnect"); IMqttToken disconnectToken = client.disconnect(null, null); disconnectToken.waitForCompletion(waitForCompletionTime); Log.i(methodName, "HA success"); } catch (Exception e) { e.printStackTrace(); throw e; } } finally { if (client != null) { client.close(); } } }
/** * Persists a buffered message to the persistence layer * * @param message The {@link MqttWireMessage} to persist */ public void persistBufferedMessage(MqttWireMessage message) { final String methodName = "persistBufferedMessage"; String key = getSendBufferedPersistenceKey(message); // Because the client will have disconnected, we will want to re-open persistence try { message.setMessageId(getNextMessageId()); key = getSendBufferedPersistenceKey(message); try { persistence.put(key, (MqttPublish) message); } catch (MqttPersistenceException mpe){ //@TRACE 515=Could not Persist, attempting to Re-Open Persistence Store log.fine(CLASS_NAME,methodName, "515"); persistence.open(this.clientComms.getClient().getClientId(), this.clientComms.getClient().getServerURI()); persistence.put(key, (MqttPublish) message); } //@TRACE 513=Persisted Buffered Message key={0} log.fine(CLASS_NAME,methodName, "513", new Object[]{key}); } catch (MqttException ex){ //@TRACE 514=Failed to persist buffered message key={0} log.warning(CLASS_NAME,methodName, "513", new Object[]{key}); } }
mqttClient.connect(options, new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) {