use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project smarthome by eclipse.
the class MqttBrokerConnection method publish.
/**
* Publish a message to the broker.
*
* @param topic The topic
* @param payload The message payload
* @param listener An optional listener to be notified of success or failure of the delivery.
* @return The message ID of the published message. Can be used in the callback to identify the asynchronous task.
* Returns -1 if not connected currently.
* @throws MqttException
*/
public int publish(String topic, byte[] payload, MqttPublishCallback listener) throws MqttException {
MqttAsyncClient client_ = client;
if (client_ == null) {
return -1;
}
// publish message asynchronously
IMqttDeliveryToken deliveryToken;
try {
deliveryToken = client_.publish(topic, payload, qos, retain, null, new IMqttActionListener() {
@Override
public void onSuccess(@Nullable IMqttToken token_) {
// token is never null, but the interface is not
IMqttToken token = (@NonNull IMqttToken) token_;
// annotated correctly
listener.onSuccess(new MqttPublishResult(token.getMessageId(), topic));
}
@Override
public void onFailure(@Nullable IMqttToken token, @Nullable Throwable error) {
if (token != null && error != null) {
listener.onFailure(new MqttPublishResult(token.getMessageId(), topic), error);
}
}
});
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
throw new MqttException(e);
}
logger.debug("Publishing message {} to topic '{}'", deliveryToken.getMessageId(), topic);
return deliveryToken.getMessageId();
}
use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project smarthome by eclipse.
the class MqttBrokerConnection method start.
/**
* This will establish a connection to the MQTT broker and if successful, notify all
* publishers and subscribers that the connection has become active. This method will
* do nothing if there is already an active connection.
*
* If you want a synchronised way of establishing a broker connection, you can use the
* following pattern:
*
* Object o = new Object();
* conn.addConnectionObserver((isConnected, error) -> o.notify() );
* conn.start();
* o.wait(timeout_in_ms);
* boolean success = conn.connectionState()==MqttConnectionState.CONNECTED;
*
* @throws MqttException If a communication error occurred, this exception is thrown.
* @throws ConfigurationException If no url is given or parameters are invalid, this exception is thrown.
*/
public synchronized void start() throws MqttException, ConfigurationException {
if (connectionState() != MqttConnectionState.DISCONNECTED) {
return;
}
// Ensure the reconnect strategy is started
if (reconnectStrategy != null) {
reconnectStrategy.start();
}
// Storage
String tmpDir = System.getProperty("java.io.tmpdir") + "/" + host;
MqttClientPersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
StringBuilder serverURI = new StringBuilder();
serverURI.append((secure ? "ssl://" : "tcp://"));
serverURI.append(host);
serverURI.append(":");
serverURI.append(port);
// Close client if there is still one existing
if (client != null) {
try {
client.close();
} catch (org.eclipse.paho.client.mqttv3.MqttException ignore) {
}
client = null;
}
// Create new client connection
MqttAsyncClient _client;
try {
_client = new MqttAsyncClient(serverURI.toString(), clientId, dataStore);
client = _client;
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
throw new MqttException(e);
}
_client.setCallback(clientCallbacks);
logger.info("Starting MQTT broker connection to '{}' with clientid {} and file store '{}'", host, getClientId(), tmpDir);
// Perform the connection attempt
isConnecting = true;
try {
_client.connect(createMqttOptions(), null, createConnectionListener());
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
throw new MqttException(e);
}
}
use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project mist by snuspl.
the class MQTTNoSharedResource method getMqttSinkClient.
@Override
public IMqttAsyncClient getMqttSinkClient(final String brokerURI, final String topic) throws MqttException, IOException {
final IMqttAsyncClient client = new MqttAsyncClient(brokerURI, MQTT_PUBLISHER_ID_PREFIX + sinkClientCounter.getAndIncrement());
final MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setMaxInflight(maxInflightMqttEventNum);
connectOptions.setKeepAliveInterval(mqttSinkKeepAliveSec);
client.connect(connectOptions).waitForCompletion();
return client;
}
use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project xian by happyyangyuan.
the class AbstractMqttClient method connectBroker.
/**
* 连接mqtt server,并返回一个客户端对象,如果连接失败,那么返回null
*/
public MqttAsyncClient connectBroker() {
LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 准备建立连接,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName));
try {
sampleClient = new MqttAsyncClient("tcp://overriddenByMqttConnectOptions.setServerURIs:1883", getMqttClientId(), persistence);
connOpts = new MqttConnectOptions();
connOpts.setAutomaticReconnect(true);
connOpts.setServerURIs(serverURIs);
connOpts.setUserName(userName);
connOpts.setPassword(getPwd());
connOpts.setCleanSession(cleanSession);
connOpts.setMaxInflight(1000);
connOpts.setKeepAliveInterval(keepAliveInterval);
sampleClient.setCallback(getCallback(this));
sampleClient.connect(connOpts).waitForCompletion(60 * 1000);
LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 建立连接完成,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName));
return sampleClient;
} catch (MqttException me) {
throw new RuntimeException(String.format("mqtt=======客户端%s与rabbitMQ server: %s 连接失败!!! userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName), me);
}
}
use of org.eclipse.paho.client.mqttv3.MqttAsyncClient in project spring-integration by spring-projects.
the class MqttAdapterTests method testSubscribeFailure.
@Test
public void testSubscribeFailure() throws Exception {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
factory.setCleanSession(false);
factory.setConnectionTimeout(23);
factory.setKeepAliveInterval(45);
factory.setPassword("pass");
MemoryPersistence persistence = new MemoryPersistence();
factory.setPersistence(persistence);
final SocketFactory socketFactory = mock(SocketFactory.class);
factory.setSocketFactory(socketFactory);
final Properties props = new Properties();
factory.setSslProperties(props);
factory.setUserName("user");
Will will = new Will("foo", "bar".getBytes(), 2, true);
factory.setWill(will);
factory = spy(factory);
MqttAsyncClient aClient = mock(MqttAsyncClient.class);
final MqttClient client = mock(MqttClient.class);
willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
given(client.isConnected()).willReturn(true);
new DirectFieldAccessor(client).setPropertyValue("aClient", aClient);
willAnswer(new CallsRealMethods()).given(client).connect(any(MqttConnectOptions.class));
willAnswer(new CallsRealMethods()).given(client).subscribe(any(String[].class), any(int[].class));
willReturn(alwaysComplete).given(aClient).connect(any(MqttConnectOptions.class), any(), any());
IMqttToken token = mock(IMqttToken.class);
given(token.getGrantedQos()).willReturn(new int[] { 0x80 });
willReturn(token).given(aClient).subscribe(any(String[].class), any(int[].class), any(), any());
MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
AtomicReference<Method> method = new AtomicReference<>();
ReflectionUtils.doWithMethods(MqttPahoMessageDrivenChannelAdapter.class, m -> {
m.setAccessible(true);
method.set(m);
}, m -> m.getName().equals("connectAndSubscribe"));
assertNotNull(method.get());
try {
method.get().invoke(adapter);
fail("Expected InvocationTargetException");
} catch (InvocationTargetException e) {
assertThat(e.getCause(), instanceOf(MqttException.class));
assertThat(((MqttException) e.getCause()).getReasonCode(), equalTo((int) MqttException.REASON_CODE_SUBSCRIBE_FAILED));
}
}
Aggregations