Java Code Examples for org.eclipse.paho.client.mqttv3.MqttClient#isConnected()
The following examples show how to use
org.eclipse.paho.client.mqttv3.MqttClient#isConnected() .
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: ApplozicMqttService.java From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License | 6 votes |
public synchronized void subscribe(boolean useEncrypted) { if (!Utils.isInternetAvailable(context)) { return; } final String deviceKeyString = MobiComUserPreference.getInstance(context).getDeviceKeyString(); final String userKeyString = MobiComUserPreference.getInstance(context).getSuUserKeyString(); if (TextUtils.isEmpty(deviceKeyString) || TextUtils.isEmpty(userKeyString)) { return; } try { final MqttClient client = connect(); if (client == null || !client.isConnected()) { return; } connectPublish(userKeyString, deviceKeyString, "1"); subscribeToConversation(useEncrypted); if (client != null) { client.setCallback(ApplozicMqttService.this); } } catch (Exception e) { e.printStackTrace(); } }
Example 2
Source File: ApplozicMqttService.java From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License | 6 votes |
public synchronized void subscribeToCustomTopic(String customTopic, boolean useEncrypted) { try { String userKeyString = MobiComUserPreference.getInstance(context).getSuUserKeyString(); if (TextUtils.isEmpty(userKeyString)) { return; } final MqttClient client = connect(); if (client != null && client.isConnected()) { String topic = (useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + SUPPORT_GROUP_TOPIC + getApplicationKey(context); Utils.printLog(context, TAG, "Subscribing to support group topic : " + topic); client.subscribe(topic, 0); } } catch (Exception e) { e.printStackTrace(); } }
Example 3
Source File: ApplozicMqttService.java From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License | 6 votes |
public synchronized void subscribeToSupportGroup(boolean useEncrypted) { try { String userKeyString = MobiComUserPreference.getInstance(context).getSuUserKeyString(); if (TextUtils.isEmpty(userKeyString)) { return; } final MqttClient client = connect(); if (client != null && client.isConnected()) { String topic = (useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + SUPPORT_GROUP_TOPIC + getApplicationKey(context); Utils.printLog(context, TAG, "Subscribing to support group topic : " + topic); client.subscribe(topic, 0); } } catch (Exception e) { e.printStackTrace(); } }
Example 4
Source File: ApplozicMqttService.java From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 + "," + User.getEncodedUserId(loggedInUserId) + "," + status).getBytes()); message.setQos(0); client.publish("typing" + "-" + applicationId + "-" + User.getEncodedUserId(userId), message); Utils.printLog(context, TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + User.getEncodedUserId(userId)); } catch (Exception e) { e.printStackTrace(); } }
Example 5
Source File: ApplozicMqttService.java From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License | 6 votes |
public synchronized void subscribeToTypingTopic(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.subscribe("typing-" + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId), 0); Utils.printLog(context, TAG, "Subscribed to topic: " + "typing-" + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId)); } catch (Exception e) { e.printStackTrace(); } }
Example 6
Source File: ApplozicMqttService.java From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License | 6 votes |
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) + "-" + User.getEncodedUserId(currentId)); Utils.printLog(context, TAG, "UnSubscribed to topic: " + "typing-" + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId)); } catch (Exception e) { e.printStackTrace(); } }
Example 7
Source File: ApplozicMqttService.java From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License | 6 votes |
public synchronized void subscribeToOpenGroupTopic(Channel channel) { try { String currentId = null; if (channel != null) { currentId = String.valueOf(channel.getKey()); } final MqttClient client = connect(); if (client == null || !client.isConnected()) { return; } client.subscribe(OPEN_GROUP + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId), 0); Utils.printLog(context, TAG, "Subscribed to Open group: " + OPEN_GROUP + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId)); } catch (Exception e) { e.printStackTrace(); } }
Example 8
Source File: ApplozicMqttService.java From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License | 6 votes |
public synchronized void unSubscribeToOpenGroupTopic(Channel channel) { try { String currentId = null; if (channel != null) { currentId = String.valueOf(channel.getKey()); } final MqttClient client = connect(); if (client == null || !client.isConnected()) { return; } client.unsubscribe(OPEN_GROUP + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId)); Utils.printLog(context, TAG, "UnSubscribed to topic: " + OPEN_GROUP + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId)); } catch (Exception e) { e.printStackTrace(); } }
Example 9
Source File: MqttConnector.java From quarks with Apache License 2.0 | 5 votes |
@Override protected synchronized MqttClient doConnect(MqttClient client) throws MqttException { MqttConfig config = configFn.get(); if (client == null) client = newClient(config); if (client.isConnected()) return client; MqttConnectOptions options = (MqttConnectOptions) config.options(); logger.info("{} cleanSession:{} userName:{} password:{} idleTimeout:{} idleReconnectTimeout:{} cnTimeout:{} keepalive:{} serverURIs:{} willDst:{} willMsg:{}", id(), options.isCleanSession(), options.getUserName(), options.getPassword() == null ? null : "*****", config.getIdleTimeout(), config.getSubscriberIdleReconnectInterval(), options.getConnectionTimeout(), options.getKeepAliveInterval(), options.getServerURIs(), options.getWillDestination(), options.getWillMessage() ); client.connect(options); setIdleTimeout(config.getIdleTimeout(), TimeUnit.SECONDS); MqttSubscriber<?> sub = subscriber; if (sub != null) { setIdleReconnectInterval(config.getSubscriberIdleReconnectInterval()); sub.connected(client); } return client; }
Example 10
Source File: CustomAction.java From itracing2 with GNU General Public License v2.0 | 5 votes |
@Override public void run() { final Matcher matcher = pattern.matcher(this.domain); if (matcher.matches()) { String login = matcher.group(2); String password = matcher.group(3); String host = matcher.group(4); String port = matcher.group(5); String topic = matcher.group(6); if (port == null) { port = "1883"; } try { final MqttClient client = new MqttClient("tcp://" + host + ":" + port, MqttClient.generateClientId(), new MemoryPersistence() ); final MqttConnectOptions options = new MqttConnectOptions(); if (login != null && password != null) { options.setUserName(login); options.setPassword(password.toCharArray()); } client.connect(options); if (client.isConnected()) { client.publish(topic, payload.getBytes(), 0, false); client.disconnect(); } } catch (MqttException e) { Log.d(TAG, "exception", e); } } }
Example 11
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(); } }
Example 12
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 13
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 14
Source File: MqttConnector.java From quarks with Apache License 2.0 | 4 votes |
@Override protected synchronized void doDisconnect(MqttClient client) throws Exception { if (client.isConnected()) client.disconnect(); }
Example 15
Source File: MqttExample.java From java-docs-samples with Apache License 2.0 | 4 votes |
/** Connects the gateway to the MQTT bridge. */ protected static MqttClient startMqtt( String mqttBridgeHostname, int mqttBridgePort, String projectId, String cloudRegion, String registryId, String gatewayId, String privateKeyFile, String algorithm) throws NoSuchAlgorithmException, IOException, MqttException, InterruptedException, InvalidKeySpecException { // [START iot_gateway_start_mqtt] // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL // connections are accepted. For server authentication, the JVM's root certificates // are used. final String mqttServerAddress = String.format("ssl://%s:%s", mqttBridgeHostname, mqttBridgePort); // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For // Google Cloud IoT Core, it must be in the format below. final String mqttClientId = String.format( "projects/%s/locations/%s/registries/%s/devices/%s", projectId, cloudRegion, registryId, gatewayId); MqttConnectOptions connectOptions = new MqttConnectOptions(); // Note that the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we // explictly set this. If you don't set MQTT version, the server will immediately close its // connection to your device. connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); Properties sslProps = new Properties(); sslProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2"); connectOptions.setSSLProperties(sslProps); // With Google Cloud IoT Core, the username field is ignored, however it must be set for the // Paho client library to send the password field. The password field is used to transmit a JWT // to authorize the device. connectOptions.setUserName("unused"); if ("RS256".equals(algorithm)) { connectOptions.setPassword(createJwtRsa(projectId, privateKeyFile).toCharArray()); } else if ("ES256".equals(algorithm)) { connectOptions.setPassword(createJwtEs(projectId, privateKeyFile).toCharArray()); } else { throw new IllegalArgumentException( "Invalid algorithm " + algorithm + ". Should be one of 'RS256' or 'ES256'."); } System.out.println(String.format("%s", mqttClientId)); // Create a client, and connect to the Google MQTT bridge. MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence()); // Both connect and publish operations may fail. If they do, allow retries but with an // exponential backoff time period. long initialConnectIntervalMillis = 500L; long maxConnectIntervalMillis = 6000L; long maxConnectRetryTimeElapsedMillis = 900000L; float intervalMultiplier = 1.5f; long retryIntervalMs = initialConnectIntervalMillis; long totalRetryTimeMs = 0; while ((totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) && !client.isConnected()) { try { client.connect(connectOptions); } catch (MqttException e) { int reason = e.getReasonCode(); // If the connection is lost or if the server cannot be connected, allow retries, but with // exponential backoff. System.out.println("An error occurred: " + e.getMessage()); if (reason == MqttException.REASON_CODE_CONNECTION_LOST || reason == MqttException.REASON_CODE_SERVER_CONNECT_ERROR) { System.out.println("Retrying in " + retryIntervalMs / 1000.0 + " seconds."); Thread.sleep(retryIntervalMs); totalRetryTimeMs += retryIntervalMs; retryIntervalMs *= intervalMultiplier; if (retryIntervalMs > maxConnectIntervalMillis) { retryIntervalMs = maxConnectIntervalMillis; } } else { throw e; } } } attachCallback(client, gatewayId); // The topic gateways receive error updates on. QoS must be 0. String errorTopic = String.format("/devices/%s/errors", gatewayId); System.out.println(String.format("Listening on %s", errorTopic)); client.subscribe(errorTopic, 0); return client; // [END iot_gateway_start_mqtt] }