Java Code Examples for org.eclipse.paho.client.mqttv3.MqttConnectOptions#setCleanSession()
The following examples show how to use
org.eclipse.paho.client.mqttv3.MqttConnectOptions#setCleanSession() .
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: MQTTOverWebSocketTest.java From WeEvent with Apache License 2.0 | 6 votes |
@Test public void testWill() { try { String clientId = UUID.randomUUID().toString(); MqttClient mqttClient = new MqttClient(this.url, clientId, null); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setConnectionTimeout(this.actionTimeout); connectOptions.setKeepAliveInterval(this.actionTimeout); connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); connectOptions.setWill(this.topicName, this.content.getBytes(), 1, false); connectOptions.setCleanSession(true); mqttClient.connect(this.cleanupOptions); mqttClient.disconnect(); Assert.assertTrue(true); } catch (MqttException e) { log.error("exception", e); Assert.fail(); } }
Example 2
Source File: MQTTTest.java From WeEvent with Apache License 2.0 | 6 votes |
@Test public void testWill() { try { String clientId = UUID.randomUUID().toString(); MqttClient mqttClient = new MqttClient(this.url, clientId, null); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setConnectionTimeout(this.actionTimeout); connectOptions.setKeepAliveInterval(this.actionTimeout); connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); connectOptions.setWill(this.topicName, this.content.getBytes(), 1, false); connectOptions.setCleanSession(true); mqttClient.connect(this.cleanupOptions); mqttClient.disconnect(); Assert.assertTrue(true); } catch (MqttException e) { log.error("exception", e); Assert.fail(); } }
Example 3
Source File: MqttAutoConfiguration.java From mqtt-spring-boot with MIT License | 6 votes |
@Bean public DefaultMqttPahoClientFactory clientFactory() { MqttConnectOptions connectOptions = new MqttConnectOptions(); String username = mqttProperties.getUsername(); String password = mqttProperties.getPassword(); if(username != null) { connectOptions.setUserName(username); } if (password != null) { connectOptions.setPassword(password.toCharArray()); } String[] serverURIs = mqttProperties.getServerURIs(); if (serverURIs == null || serverURIs.length == 0) { throw new NullPointerException("serverURIs can not be null"); } connectOptions.setCleanSession(mqttProperties.getCleanSession()); connectOptions.setKeepAliveInterval(mqttProperties.getKeepAliveInterval()); connectOptions.setServerURIs(serverURIs); DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); factory.setConnectionOptions(connectOptions); return factory; }
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: MQTTTestClient.java From product-ei with Apache License 2.0 | 6 votes |
/** * Generate a MQTT client with given parameters * * @param brokerURL url of MQTT provider * @param userName username to connect to MQTT provider * @param password password to connect to MQTT provider * @param clientId unique id for the publisher/subscriber client * @throws MqttException in case of issue of connect/publish/consume */ public MQTTTestClient(String brokerURL, String userName, char[] password, String clientId) throws MqttException { this.brokerURL = brokerURL; //Store messages until server fetches them MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(JAVA_TMP_DIR + "/" + clientId); mqttClient = new MqttClient(brokerURL, clientId, dataStore); SimpleMQTTCallback callback = new SimpleMQTTCallback(); mqttClient.setCallback(callback); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setUserName(userName); connectOptions.setPassword(password); connectOptions.setCleanSession(true); mqttClient.connect(connectOptions); log.info("MQTTTestClient successfully connected to broker at " + this.brokerURL); }
Example 6
Source File: MQTTTestClient.java From micro-integrator with Apache License 2.0 | 6 votes |
/** * Generate a MQTT client with given parameters * * @param brokerURL url of MQTT provider * @param userName username to connect to MQTT provider * @param password password to connect to MQTT provider * @param clientId unique id for the publisher/subscriber client * @throws MqttException in case of issue of connect/publish/consume */ public MQTTTestClient(String brokerURL, String userName, char[] password, String clientId) throws MqttException { this.brokerURL = brokerURL; //Store messages until server fetches them MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(JAVA_TMP_DIR + "/" + clientId); mqttClient = new MqttClient(brokerURL, clientId, dataStore); SimpleMQTTCallback callback = new SimpleMQTTCallback(); mqttClient.setCallback(callback); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setUserName(userName); connectOptions.setPassword(password); connectOptions.setCleanSession(true); mqttClient.connect(connectOptions); log.info("MQTTTestClient successfully connected to broker at " + this.brokerURL); }
Example 7
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 8
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 9
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 10
Source File: MqttSubscriberClient.java From product-iots with Apache License 2.0 | 5 votes |
/** * * @param serverAddress Mqtt broker address * @param clientId Client ID * @param topicName Topic Name * @throws MqttException Mqtt Exception */ public MqttSubscriberClient(String serverAddress, String clientId, String topicName, String accessToken) throws MqttException { mqttMessages = new ArrayList<>(); MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(serverAddress, clientId, persistence); MqttConnectOptions connectOptions = new MqttConnectOptions(); client.setCallback(this); connectOptions.setUserName(accessToken); connectOptions.setPassword("".toCharArray()); connectOptions.setCleanSession(true); connectOptions.setKeepAliveInterval(300); client.connect(connectOptions); client.subscribe(topicName); }
Example 11
Source File: MQTT_PVConn.java From phoebus with Eclipse Public License 1.0 | 5 votes |
private void setOptions() { connOpt = new MqttConnectOptions(); connOpt.setCleanSession(true); connOpt.setKeepAliveInterval(30); connOpt.setWill("ERROR", "PV Disconnected".getBytes(), 0, true); //connOpt.setUserName(userName); //connOpt.setPassword(passWord.getBytes()); //TODO: Look up best practices for reconnect }
Example 12
Source File: AbstractMQTTProcessor.java From nifi with Apache License 2.0 | 5 votes |
protected void onScheduled(final ProcessContext context){ broker = context.getProperty(PROP_BROKER_URI).getValue(); clientID = context.getProperty(PROP_CLIENTID).evaluateAttributeExpressions().getValue(); if (clientID == null) { clientID = UUID.randomUUID().toString(); } connOpts = new MqttConnectOptions(); connOpts.setCleanSession(context.getProperty(PROP_CLEAN_SESSION).asBoolean()); connOpts.setKeepAliveInterval(context.getProperty(PROP_KEEP_ALIVE_INTERVAL).asInteger()); connOpts.setMqttVersion(context.getProperty(PROP_MQTT_VERSION).asInteger()); connOpts.setConnectionTimeout(context.getProperty(PROP_CONN_TIMEOUT).asInteger()); PropertyValue sslProp = context.getProperty(PROP_SSL_CONTEXT_SERVICE); if (sslProp.isSet()) { Properties sslProps = transformSSLContextService((SSLContextService) sslProp.asControllerService()); connOpts.setSSLProperties(sslProps); } PropertyValue lastWillTopicProp = context.getProperty(PROP_LAST_WILL_TOPIC); if (lastWillTopicProp.isSet()){ String lastWillMessage = context.getProperty(PROP_LAST_WILL_MESSAGE).getValue(); PropertyValue lastWillRetain = context.getProperty(PROP_LAST_WILL_RETAIN); Integer lastWillQOS = context.getProperty(PROP_LAST_WILL_QOS).asInteger(); connOpts.setWill(lastWillTopicProp.getValue(), lastWillMessage.getBytes(), lastWillQOS, lastWillRetain.isSet() ? lastWillRetain.asBoolean() : false); } PropertyValue usernameProp = context.getProperty(PROP_USERNAME); if(usernameProp.isSet()) { connOpts.setUserName(usernameProp.getValue()); connOpts.setPassword(context.getProperty(PROP_PASSWORD).getValue().toCharArray()); } }
Example 13
Source File: MqttTestApp.java From diozero with MIT License | 5 votes |
public MqttTestApp() 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); mqttClient.subscribe("outTopic"); mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC); }
Example 14
Source File: MqttAcknowledgementTest.java From activemq-artemis with Apache License 2.0 | 5 votes |
private MqttClient createMqttClient(String clientId) throws MqttException { MqttClient client = new MqttClient("tcp://localhost:" + getPort(), clientId, new MemoryPersistence()); client.setCallback(createCallback()); client.setManualAcks(true); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); client.connect(options); return client; }
Example 15
Source File: TrafficService.java From AirMapSDK-Android with Apache License 2.0 | 4 votes |
/** * Initialize an TrafficService to receive traffic alerts and situational awareness * * @param context An Android Context */ public TrafficService(Context context) { String clientId = UUID.randomUUID().toString(); client = new MqttAndroidClient(context, mqttBaseUrl, clientId); client.setCallback(new MqttEventCallback()); options = new MqttConnectOptions(); options.setCleanSession(true); options.setKeepAliveInterval(15); options.setPassword(AirMap.getInstance().getAuthToken().toCharArray()); connectionState = ConnectionState.Disconnected; allTraffic = new CopyOnWriteArrayList<>(); //Thread safe list listeners = new ArrayList<>(); checkForUpdatedFlight = false; currentFlightCallback = new CurrentFlightAirMapCallback(); actionListener = new MqttActionCallback(); new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { clearOldTraffic(); updateTrafficProjections(); } }, 0, 1000); //Clear old traffic every second new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (checkForUpdatedFlight) { AirMap.getCurrentFlight(new AirMapCallback<AirMapFlight>() { @Override public void onSuccess(AirMapFlight response) { if (response != null && !response.getFlightId().equals(flightId)) { connect(); } } @Override public void onError(AirMapException e) { e.printStackTrace(); } }); } } }, 0, 1000 * 60); //Update current flight every minute handler = new Handler(Looper.getMainLooper()); }
Example 16
Source File: AbstractMQTTProcessor.java From localization_nifi with Apache License 2.0 | 4 votes |
protected void buildClient(ProcessContext context){ try { broker = context.getProperty(PROP_BROKER_URI).getValue(); clientID = context.getProperty(PROP_CLIENTID).getValue(); connOpts = new MqttConnectOptions(); connOpts.setCleanSession(context.getProperty(PROP_CLEAN_SESSION).asBoolean()); connOpts.setKeepAliveInterval(context.getProperty(PROP_KEEP_ALIVE_INTERVAL).asInteger()); connOpts.setMqttVersion(context.getProperty(PROP_MQTT_VERSION).asInteger()); connOpts.setConnectionTimeout(context.getProperty(PROP_CONN_TIMEOUT).asInteger()); PropertyValue sslProp = context.getProperty(PROP_SSL_CONTEXT_SERVICE); if (sslProp.isSet()) { Properties sslProps = transformSSLContextService((SSLContextService) sslProp.asControllerService()); connOpts.setSSLProperties(sslProps); } PropertyValue lastWillTopicProp = context.getProperty(PROP_LAST_WILL_TOPIC); if (lastWillTopicProp.isSet()){ String lastWillMessage = context.getProperty(PROP_LAST_WILL_MESSAGE).getValue(); PropertyValue lastWillRetain = context.getProperty(PROP_LAST_WILL_RETAIN); Integer lastWillQOS = context.getProperty(PROP_LAST_WILL_QOS).asInteger(); connOpts.setWill(lastWillTopicProp.getValue(), lastWillMessage.getBytes(), lastWillQOS, lastWillRetain.isSet() ? lastWillRetain.asBoolean() : false); } PropertyValue usernameProp = context.getProperty(PROP_USERNAME); if(usernameProp.isSet()) { connOpts.setUserName(usernameProp.getValue()); connOpts.setPassword(context.getProperty(PROP_PASSWORD).getValue().toCharArray()); } mqttClientConnectLock.writeLock().lock(); try{ mqttClient = getMqttClient(broker, clientID, persistence); } finally { mqttClientConnectLock.writeLock().unlock(); } } catch(MqttException me) { logger.error("Failed to initialize the connection to the " + me.getMessage()); } }
Example 17
Source File: DeviceTypeManagementJMeterTestCase.java From product-iots with Apache License 2.0 | 4 votes |
@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods = {"DeviceTypeManagementTest"} ) public void testMqttFlow() throws Exception { String deviceId = "123422578912"; String deviceType = "firealarmmqtt"; String payload = "{\"deviceIdentifiers\":[123422578912],\"operation\":{\"code\":\"ring\",\"type\":\"CONFIG\"," + "\"payLoad\":\"volume:30%\"}}"; String topic = automationContext.getContextTenant().getDomain() + "/"+deviceType+"/" + deviceId + "/operation/#"; String clientId = deviceId + ":firealarmmqtt"; MqttSubscriberClient mqttDeviceSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken); restClient.post("/api/device-mgt/v1.0/devices/" + deviceType + "/operations", payload); // Allow some time for message delivery Thread.sleep(10000); ArrayList<MqttMessage> mqttMessages = mqttDeviceSubscriberClient.getMqttMessages(); Assert.assertEquals("listener did not received mqtt messages ", 1, mqttMessages.size()); String topicPub = automationContext.getContextTenant().getDomain() + "/"+deviceType+"/"+deviceId+"/events"; int qos = 2; String clientIdPub = deviceId + ":firealarmmqttpub"; MemoryPersistence persistence = new MemoryPersistence(); MqttClient sampleClient = new MqttClient(broker, clientIdPub, persistence); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setUserName(accessToken); connOpts.setPassword("".toCharArray()); connOpts.setKeepAliveInterval(120); connOpts.setCleanSession(false); log.info("Connecting to broker: " + broker); sampleClient.connect(connOpts); log.info("Connected"); for (int i = 0; i < 100; i++) { payload = "{\"temperature\":%d,\"status\":\"workingh\",\"humidity\":20}"; MqttMessage message = new MqttMessage(String.format(payload, i).getBytes()); message.setQos(qos); sampleClient.publish(topicPub, message); log.info("Message is published to Mqtt Client"); Thread.sleep(1000); } sampleClient.disconnect(); log.info("Mqtt Client is Disconnected"); // Allow some time for message delivery HttpResponse response = restClient.get("/api/device-mgt/v1.0/events/last-known/" + deviceType + "/" + deviceId); Assert.assertEquals("No published event found (mqtt)", HttpStatus.SC_OK, response.getResponseCode()); log.error(response.getData()); JsonElement jsonElement = new JsonParser().parse(response.getData()).getAsJsonObject().get("count"); int count = jsonElement.getAsInt(); Assert.assertTrue("Event count does not match published event count, " + response.getData(), count > 0); }
Example 18
Source File: PahoMQTTQOS2SecurityTest.java From activemq-artemis with Apache License 2.0 | 4 votes |
@Test(timeout = 300000) public void testSendAndReceiveMQTT() throws Exception { final CountDownLatch latch = new CountDownLatch(1); MqttClient consumer = createPahoClient("consumerId"); MqttClient producer = createPahoClient("producerId"); MqttConnectOptions conOpt = new MqttConnectOptions(); conOpt.setCleanSession(true); conOpt.setUserName(user1); conOpt.setPassword(password1.toCharArray()); consumer.connect(conOpt); consumer.subscribe(getQueueName(), 2); final boolean[] failed = new boolean[1]; consumer.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { cause.printStackTrace(); failed[0] = true; latch.countDown(); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { latch.countDown(); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } }); producer.connect(conOpt); producer.publish(getQueueName(), "hello".getBytes(), 2, false); waitForLatch(latch); producer.disconnect(); producer.close(); Assert.assertFalse(failed[0]); }
Example 19
Source File: MoquetteConnectivityTest.java From rxmqtt with Apache License 2.0 | 4 votes |
/** * This test is unreliable because the subscriptions * don't always arrive. * Need to investigate why this is and reinstate. */ @Ignore @Test public void whenAutoReconnectAndCleanSessionFalseThenNoNeedToResubscribe() throws Throwable { // Create a latch and a way to count subscription receipts CountDownLatch latch = new CountDownLatch(2); List<SubscribeMessage> subscribes = new ArrayList<>(); // Create client with re-connect and dirty sessions MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); // Topic String topic = "topical"; // Create clients String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient publisher = new MqttAsyncClient(proxyUrl, "test-publisher-id", new MemoryPersistence(), new TimerPingSender()); MqttAsyncClient subscriber = new MqttAsyncClient(proxyUrl, "test-subscriber-id", new MemoryPersistence(), new TimerPingSender()); ObservableMqttClient publisherObs = observableClient(publisher, options); ObservableMqttClient subscriberObs = observableClient(subscriber, options); // Connect, subscribe, publish test message publisherObs.connect().blockingAwait(); subscriberObs.connect().blockingAwait(); Assert.assertTrue(subscriberObs.isConnected()); Assert.assertTrue(publisherObs.isConnected()); subscriberObs.subscribe(topic, 1).subscribe(m -> { System.out.println(m); subscribes.add(m); latch.countDown(); }); publisherObs.publish(topic, PublishMessage.create("Test Message 1".getBytes(), 1, false)).blockingGet(); Assert.assertEquals(1, broker.getMessages().size()); // Stop the proxy, wait, check status brokerProxy.disable(); Thread.sleep(3000); Assert.assertFalse(publisherObs.isConnected()); Assert.assertFalse(subscriberObs.isConnected()); // Restart the broker, wait, check status brokerProxy.enable(); Thread.sleep(10000); Assert.assertTrue(publisherObs.isConnected()); Assert.assertTrue(subscriberObs.isConnected()); // Publish and check for subscription publisherObs.publish(topic, PublishMessage.create("Test Message 2".getBytes(), 1, false)).blockingGet(); Assert.assertEquals(2, broker.getMessages().size()); // Check we got all the messages on the subscription latch.await(3, TimeUnit.SECONDS); Assert.assertEquals(2, subscribes.size()); }
Example 20
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); client.subscribe(NAMESPACE + "/#", 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(), newMetrics(false), 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(); } }