Java Code Examples for org.eclipse.paho.client.mqttv3.MqttConnectOptions#setAutomaticReconnect()
The following examples show how to use
org.eclipse.paho.client.mqttv3.MqttConnectOptions#setAutomaticReconnect() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractMqttClient.java From xian with Apache License 2.0 | 6 votes |
/** * 连接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 /**默认的值是10,对于我们来说这个值太小!*/); 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); } }
Example 2
Source File: MqttTestClient.java From diozero with MIT License | 6 votes |
public MqttTestClient(String mqttUrl) throws MqttException { mqttClient = new MqttClient(mqttUrl, MqttClient.generateClientId(), new MemoryPersistence()); mqttClient.setCallback(this); MqttConnectOptions con_opts = new MqttConnectOptions(); con_opts.setAutomaticReconnect(true); con_opts.setCleanSession(true); mqttClient.connect(con_opts); Logger.debug("Connected to {}", mqttUrl); lock = new ReentrantLock(); conditions = new HashMap<>(); responses = new HashMap<>(); // Subscribe Logger.debug("Subscribing to {}...", MqttProviderConstants.RESPONSE_TOPIC); mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC); Logger.debug("Subscribed"); }
Example 3
Source File: SparkplugListener.java From Sparkplug with Eclipse Public License 1.0 | 6 votes |
public void run() { try { // Connect to the MQTT Server MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(true); options.setConnectionTimeout(30); options.setKeepAliveInterval(30); options.setUserName(username); options.setPassword(password.toCharArray()); client = new MqttClient(serverUrl, clientId); client.setTimeToWait(5000); // short timeout on failure to connect client.connect(options); client.setCallback(this); // Just listen to all DDATA messages on spAv1.0 topics and wait for inbound messages client.subscribe("spBv1.0/#", 0); } catch(Exception e) { e.printStackTrace(); } }
Example 4
Source File: ApplicationConfig.java From iot-java with Eclipse Public License 1.0 | 6 votes |
public MqttConnectOptions getMqttConnectOptions() throws NoSuchAlgorithmException, KeyManagementException { MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setConnectionTimeout(DEFAULT_CONNECTION_TIMEMOUT); connectOptions.setUserName(getMqttUsername()); connectOptions.setPassword(getMqttPassword().toCharArray()); connectOptions.setCleanSession(this.options.mqtt.cleanStart); connectOptions.setKeepAliveInterval(this.options.mqtt.keepAlive); connectOptions.setMaxInflight(DEFAULT_MAX_INFLIGHT_MESSAGES); connectOptions.setAutomaticReconnect(true); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); connectOptions.setSocketFactory(sslContext.getSocketFactory()); return connectOptions; }
Example 5
Source File: DeviceConfig.java From iot-java with Eclipse Public License 1.0 | 6 votes |
public MqttConnectOptions getMqttConnectOptions() throws NoSuchAlgorithmException, KeyManagementException { MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setConnectionTimeout(DEFAULT_CONNECTION_TIMEMOUT); if (getMqttPassword() != null) { connectOptions.setUserName(getMqttUsername()); connectOptions.setPassword(getMqttPassword().toCharArray()); } connectOptions.setCleanSession(this.options.mqtt.cleanStart); connectOptions.setKeepAliveInterval(this.options.mqtt.keepAlive); connectOptions.setMaxInflight(DEFAULT_MAX_INFLIGHT_MESSAGES); connectOptions.setAutomaticReconnect(true); if (!Arrays.asList(1883, 80).contains(options.mqtt.port)) { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); connectOptions.setSocketFactory(sslContext.getSocketFactory()); } return connectOptions; }
Example 6
Source File: MqttPlugin.java From iotplatform with Apache License 2.0 | 6 votes |
@Override public void init(MqttPluginConfiguration configuration) { retryInterval = configuration.getRetryInterval(); mqttClientOptions = new MqttConnectOptions(); mqttClientOptions.setCleanSession(false); mqttClientOptions.setMaxInflight(configuration.getMaxInFlight()); mqttClientOptions.setAutomaticReconnect(true); String clientId = configuration.getClientId(); if (StringUtils.isEmpty(clientId)) { clientId = UUID.randomUUID().toString(); } if (!StringUtils.isEmpty(configuration.getAccessToken())) { mqttClientOptions.setUserName(configuration.getAccessToken()); } try { mqttClient = new MqttAsyncClient("tcp://" + configuration.getHost() + ":" + configuration.getPort(), clientId); } catch (Exception e) { log.error("Failed to create mqtt client", e); throw new RuntimeException(e); } // connect(); }
Example 7
Source File: MoquetteConnectivityTest.java From rxmqtt with Apache License 2.0 | 5 votes |
@Test public void whenBrokerIsRestartedThenWithAutoReconnectClientIsReconnected() throws Throwable { // Create client with re-connect and dirty sessions MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence()); ObservableMqttClient observableClient = observableClient(asyncClient, options); // Connect observableClient.connect().blockingAwait(); Assert.assertTrue(observableClient.isConnected()); // Stop the broker proxy this.brokerProxy.disable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); // Restart the broker proxy this.brokerProxy.enable(); Thread.sleep(5000); Assert.assertTrue(observableClient.isConnected()); }
Example 8
Source File: MoquetteConnectivityTest.java From rxmqtt with Apache License 2.0 | 5 votes |
@Test public void whenBrokerIsStoppedThenClientIsDisconnected() throws Throwable { // Create client with re-connect and dirty sessions MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(false); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence()); ObservableMqttClient observableClient = observableClient(asyncClient, options); // Connect observableClient.connect().blockingAwait(); Assert.assertTrue(observableClient.isConnected()); // Stop the broker proxy this.brokerProxy.disable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); // Restart the broker proxy this.brokerProxy.enable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); }
Example 9
Source File: ToxiproxyConnectivityITCase.java From rxmqtt with Apache License 2.0 | 5 votes |
@Ignore @Test public void whenBrokerIsStoppedThenClientIsDisconnected() throws Throwable { // Create client with re-connect and dirty sessions MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(false); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence()); ObservableMqttClient observableClient = observableClient(asyncClient, options); // Connect observableClient.connect().blockingAwait(); Assert.assertTrue(observableClient.isConnected()); // Stop the broker proxy this.brokerProxy.disable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); // Restart the broker proxy this.brokerProxy.enable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); }
Example 10
Source File: MqttPahoClient.java From joynr with Apache License 2.0 | 5 votes |
private MqttConnectOptions getConnectOptions() { MqttConnectOptions options = new MqttConnectOptions(); if (username != null && !username.isEmpty()) { if (password == null || password.isEmpty()) { throw new JoynrIllegalStateException("MQTT password not configured or empty"); } options.setUserName(username); options.setPassword(password.toCharArray()); } options.setAutomaticReconnect(false); options.setConnectionTimeout(connectionTimeoutSec); options.setKeepAliveInterval(keepAliveTimerSec); options.setMaxInflight(maxMsgsInflight); options.setCleanSession(cleanSession); if (isSecureConnection) { // Set global SSL properties for all Joynr SSL clients Properties sslClientProperties = new Properties(); sslClientProperties.setProperty(SSLSocketFactoryFactory.KEYSTORETYPE, keyStoreType); sslClientProperties.setProperty(SSLSocketFactoryFactory.KEYSTORE, keyStorePath); sslClientProperties.setProperty(SSLSocketFactoryFactory.KEYSTOREPWD, keyStorePWD); sslClientProperties.setProperty(SSLSocketFactoryFactory.TRUSTSTORETYPE, trustStoreType); sslClientProperties.setProperty(SSLSocketFactoryFactory.TRUSTSTORE, trustStorePath); sslClientProperties.setProperty(SSLSocketFactoryFactory.TRUSTSTOREPWD, trustStorePWD); options.setSSLProperties(sslClientProperties); } return options; }
Example 11
Source File: PushSenderMqtt.java From hmdm-server with Apache License 2.0 | 5 votes |
@Override public void init() { try { client = new MqttClient("tcp://" + serverUri, "HMDMServer", persistence); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(true); options.setAutomaticReconnect(true); client.connect(options); } catch (Exception e) { e.printStackTrace(); } }
Example 12
Source File: ManagerMQTT.java From helloiot with GNU General Public License v3.0 | 5 votes |
@Override public void connect() { String[] listtopics = worktopics.toArray(new String[worktopics.size()]); int[] listqos = new int[workqos.size()]; for (int i = 0; i < workqos.size(); i++) { listqos[i] = workqos.get(i); } try { mqttClient = new MqttClient(url, clientid, new MemoryPersistence()); MqttConnectOptions options = new MqttConnectOptions(); if (!Strings.isNullOrEmpty(username)) { options.setUserName(username); options.setPassword(password.toCharArray()); } options.setConnectionTimeout(timeout); options.setKeepAliveInterval(keepalive); options.setMqttVersion(version); options.setCleanSession(true); options.setAutomaticReconnect(false); options.setMaxInflight(maxinflight); options.setSSLProperties(sslproperties); options.setWill(topicsys + "app/" + clientid, new StringFormatSwitch().devalue(MiniVarBoolean.FALSE), 0, true); mqttClient.connect(options); mqttClient.setCallback(this); if (listtopics.length > 0) { mqttClient.subscribe(listtopics, listqos); } statusPublish(MiniVarBoolean.TRUE); } catch (MqttException ex) { logger.log(Level.WARNING, null, ex); throw new RuntimeException(String.format(resources.getString("exception.mqtt"), url), ex); } }
Example 13
Source File: MqttClientInstance.java From maestro-java with Apache License 2.0 | 5 votes |
public static MqttConnectOptions getConnectionOptions() { final MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); connOpts.setAutomaticReconnect(true); /* Paho uses 10 as the default max inflight exchanges. This may be a bit too small when sending log files, handling stats messages, ping requests ... all at the same. */ connOpts.setMaxInflight(20); return connOpts; }
Example 14
Source File: MqttJsonServer.java From diozero with MIT License | 5 votes |
public MqttJsonServer(String mqttUrl) throws UnknownHostException, MqttException { mqttClient = new MqttClient(mqttUrl, CLIENT_ID_PREFIX + InetAddress.getLocalHost().getHostName(), new MemoryPersistence()); mqttClient.setCallback(this); MqttConnectOptions con_opts = new MqttConnectOptions(); con_opts.setAutomaticReconnect(true); con_opts.setCleanSession(true); Logger.debug("Connecting to {}...", mqttUrl); mqttClient.connect(con_opts); Logger.debug("Connected to {}", mqttUrl); }
Example 15
Source File: MqttProtobufServer.java From diozero with MIT License | 5 votes |
public MqttProtobufServer(String mqttUrl) throws UnknownHostException, MqttException { mqttClient = new MqttClient(mqttUrl, CLIENT_ID_PREFIX + InetAddress.getLocalHost().getHostName(), new MemoryPersistence()); mqttClient.setCallback(this); MqttConnectOptions con_opts = new MqttConnectOptions(); con_opts.setAutomaticReconnect(true); con_opts.setCleanSession(true); Logger.debug("Connecting to {}...", mqttUrl); mqttClient.connect(con_opts); Logger.debug("Connected to {}", mqttUrl); }
Example 16
Source File: SparkplugExample.java From Sparkplug with Eclipse Public License 1.0 | 5 votes |
public void run() { try { // Connect to the MQTT Server MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(true); options.setConnectionTimeout(30); options.setKeepAliveInterval(30); options.setUserName(username); options.setPassword(password.toCharArray()); client = new MqttClient(serverUrl, clientId); client.setTimeToWait(2000); client.setCallback(this); client.connect(options); // Subscribe to control/command messages for both the edge of network node and the attached devices client.subscribe(NAMESPACE + "/" + groupId + "/+/" + edgeNode, 0); client.subscribe(NAMESPACE + "/" + groupId + "/+/" + edgeNode + "/*", 0); // Loop to receive input commands while (true) { System.out.print("\n> "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); handleCommand(line); } } catch(Exception e) { e.printStackTrace(); } }
Example 17
Source File: SparkplugExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
public void run() { try { // Random generator and thread pool for outgoing published messages executor = Executors.newFixedThreadPool(1); // Build up DEATH payload - note DEATH payloads don't have a regular sequence number SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date()); deathPayload = addBdSeqNum(deathPayload); byte[] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload()); MqttConnectOptions options = new MqttConnectOptions(); if (USING_REAL_TLS) { SocketFactory sf = SSLSocketFactory.getDefault(); options.setSocketFactory(sf); } // Connect to the MQTT Server options.setAutomaticReconnect(true); options.setCleanSession(true); options.setConnectionTimeout(30); options.setKeepAliveInterval(30); options.setUserName(username); options.setPassword(password.toCharArray()); options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false); client = new MqttClient(serverUrl, clientId); client.setTimeToWait(2000); client.setCallback(this); // short timeout on failure to connect client.connect(options); // Subscribe to control/command messages for both the edge of network node and the attached devices client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0); client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0); // Loop forever publishing data every PUBLISH_PERIOD while (true) { Thread.sleep(PUBLISH_PERIOD); if (client.isConnected()) { synchronized (seqLock) { System.out.println("Connected - publishing new data"); // Create the payload and add some metrics SparkplugBPayload payload = new SparkplugBPayload(new Date(), newComplexTemplateInstance(), getSeqNum(), newUUID(), null); client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId, new SparkplugBPayloadEncoder().getBytes(payload), 0, false); } } else { System.out.println("Not connected - not publishing data"); } } } catch (Exception e) { e.printStackTrace(); } }
Example 18
Source File: SparkplugExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
public void run() { try { // Random generator and thread pool for outgoing published messages executor = Executors.newFixedThreadPool(1); // Build up DEATH payload - note DEATH payloads don't have a regular sequence number SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date()); deathPayload = addBdSeqNum(deathPayload); byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload()); MqttConnectOptions options = new MqttConnectOptions(); if (USING_REAL_TLS) { SocketFactory sf = SSLSocketFactory.getDefault(); options.setSocketFactory(sf); } // Connect to the MQTT Server options.setAutomaticReconnect(true); options.setCleanSession(true); options.setConnectionTimeout(30); options.setKeepAliveInterval(30); options.setUserName(username); options.setPassword(password.toCharArray()); options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false); client = new MqttClient(serverUrl, clientId); client.setTimeToWait(30000); client.setCallback(this); // short timeout on failure to connect client.connect(options); // Subscribe to control/command messages for both the edge of network node and the attached devices client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0); client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0); List<Metric> nodeMetrics = new ArrayList<Metric>(); List<Metric> deviceMetrics = new ArrayList<Metric>(); // Loop forever publishing data every PUBLISH_PERIOD while (true) { Thread.sleep(PUBLISH_PERIOD); synchronized(seqLock) { if (client.isConnected()) { System.out.println("Time: " + calendar.getTimeInMillis() + " Index: " + index); // Add a 'real time' metric nodeMetrics.add(new MetricBuilder("MyNodeMetric", Int32, index) .timestamp(calendar.getTime()) .createMetric()); // Add a 'real time' metric deviceMetrics.add(new MetricBuilder("MyDeviceMetric", Int32, index+50) .timestamp(calendar.getTime()) .createMetric()); // Publish, increment the calendar and index and reset calendar.add(Calendar.MILLISECOND, 1); if (index == 50) { index = 0; System.out.println("nodeMetrics: " + nodeMetrics.size()); System.out.println("deviceMetrics: " + deviceMetrics.size()); SparkplugBPayload nodePayload = new SparkplugBPayload( new Date(), nodeMetrics, getSeqNum(), null, null); client.publish(NAMESPACE + "/" + groupId + "/NDATA/" + edgeNode, new SparkplugBPayloadEncoder().getBytes(nodePayload), 0, false); SparkplugBPayload devicePayload = new SparkplugBPayload( new Date(), deviceMetrics, getSeqNum(), null, null); client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId, new SparkplugBPayloadEncoder().getBytes(devicePayload), 0, false); nodeMetrics = new ArrayList<Metric>(); deviceMetrics = new ArrayList<Metric>(); } else { index++; } } else { System.out.println("Not connected - not publishing data"); } } } } catch(Exception e) { e.printStackTrace(); } }
Example 19
Source File: MqttAsyncClientFactory.java From jframe with Apache License 2.0 | 4 votes |
private MqttConnectOptions createConnectOptions() { MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setAutomaticReconnect(conf.getConfBool(id, MqttClientConf.F_mqtt_session_autoReconnect, "false")); connOpts.setCleanSession(conf.getConfBool(id, MqttClientConf.F_mqtt_session_clean, "false")); return connOpts; }
Example 20
Source File: EngineTemperatureSensorLiveTest.java From tutorials with MIT License | 3 votes |
@Test public void whenSendSingleMessage_thenSuccess() throws Exception { String publisherId = UUID.randomUUID().toString(); MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId); String subscriberId = UUID.randomUUID().toString(); MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId); MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(true); options.setConnectionTimeout(10); subscriber.connect(options); publisher.connect(options); CountDownLatch receivedSignal = new CountDownLatch(1); subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> { byte[] payload = msg.getPayload(); log.info("[I46] Message received: topic={}, payload={}", topic, new String(payload)); receivedSignal.countDown(); }); Callable<Void> target = new EngineTemperatureSensor(publisher); target.call(); receivedSignal.await(1, TimeUnit.MINUTES); log.info("[I56] Success !"); }