Java Code Examples for org.eclipse.paho.client.mqttv3.MqttConnectOptions#setWill()
The following examples show how to use
org.eclipse.paho.client.mqttv3.MqttConnectOptions#setWill() .
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: Connection.java From EMQ-Android-Toolkit with Apache License 2.0 | 6 votes |
public MqttConnectOptions getMqttConnectOptions() { MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(isCleanSession()); options.setConnectionTimeout(getTimeout()); options.setKeepAliveInterval(getKeepAlive()); if (!getUsername().isEmpty()) { options.setUserName(getUsername()); } if (!getPassword().isEmpty()) { options.setPassword(getPassword().toCharArray()); } if (!getLwtTopic().isEmpty() && !getLwtPayload().isEmpty()) { options.setWill(getLwtTopic(), getLwtPayload().getBytes(), getLwtQos(), isLwtRetained()); } return options; }
Example 4
Source File: AwsIotMqttConnection.java From aws-iot-device-sdk-java with Apache License 2.0 | 6 votes |
private MqttConnectOptions buildMqttConnectOptions(AbstractAwsIotClient client, SocketFactory socketFactory) { MqttConnectOptions options = new MqttConnectOptions(); options.setSocketFactory(socketFactory); options.setCleanSession(client.isCleanSession()); options.setConnectionTimeout(client.getConnectionTimeout() / 1000); options.setKeepAliveInterval(client.getKeepAliveInterval() / 1000); if(client.isClientEnableMetrics()) { options.setUserName(USERNAME_METRIC_STRING); } Set<String> serverUris = getServerUris(); if (serverUris != null && !serverUris.isEmpty()) { String[] uriArray = new String[serverUris.size()]; serverUris.toArray(uriArray); options.setServerURIs(uriArray); } if (client.getWillMessage() != null) { AWSIotMessage message = client.getWillMessage(); options.setWill(message.getTopic(), message.getPayload(), message.getQos().getValue(), false); } return options; }
Example 5
Source File: MainActivity.java From Sparkplug with Eclipse Public License 1.0 | 6 votes |
public void connect(Connection connection) { String[] actionArgs = new String[1]; actionArgs[0] = connection.getId(); final ActionListener callback = new ActionListener(this, ActionListener.Action.CONNECT, connection, actionArgs); connection.getClient().setCallback(new MqttCallbackHandler(this, connection.handle())); try { MqttConnectOptions mqttConnectOptions = connection.getConnectionOptions(); SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date()); deathPayload = connection.addBdSeqNum(deathPayload); byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload()); String lwtTopic = "spBv1.0/" + connection.getGroupId() + "/NDEATH/" + connection.getEdgeNodeId(); Log.d(TAG, "1. Setting up LWT: " + lwtTopic); mqttConnectOptions.setWill(lwtTopic, deathBytes, 0, false); connection.getClient().connect(mqttConnectOptions, null, callback); } catch (Exception e) { Log.e(this.getClass().getCanonicalName(), "Exception occurred", e); } }
Example 6
Source File: Producer.java From jmqtt with Apache License 2.0 | 5 votes |
private static MqttClient getMqttClient(){ try { MqttClient pubClient = new MqttClient(broker,clientId,new MemoryPersistence()); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setWill("lwt","this is a will message".getBytes(),1,false); connectOptions.setCleanSession(true); System.out.println("Connecting to broker: " + broker); pubClient.connect(connectOptions); return pubClient; } catch (MqttException e) { e.printStackTrace(); } return null; }
Example 7
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 8
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 9
Source File: MqttMain.java From Ardulink-1 with Apache License 2.0 | 5 votes |
private MqttConnectOptions mqttConnectOptions() { MqttConnectOptions options = new MqttConnectOptions(); String clientInfoTopic = publishClientInfoTopic; if (!nullOrEmpty(clientInfoTopic)) { options.setWill(clientInfoTopic, FALSE.toString().getBytes(), 0, RETAINED); } return options; }
Example 10
Source File: ApplozicMqttService.java From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License | 5 votes |
private MqttConnectOptions getConnectionOptions() { MobiComUserPreference userPreference = MobiComUserPreference.getInstance(context); String authToken = userPreference.getUserAuthToken(); MqttConnectOptions connOpts = new MqttConnectOptions(); if (!TextUtils.isEmpty(authToken)) { connOpts.setUserName(getApplicationKey(context)); connOpts.setPassword(authToken.toCharArray()); } connOpts.setConnectionTimeout(60); connOpts.setWill(STATUS, (userPreference.getSuUserKeyString() + "," + userPreference.getDeviceKeyString() + "," + "0").getBytes(), 0, true); return connOpts; }
Example 11
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 12
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 13
Source File: SparkplugRaspberryPiExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
/** * Establish an MQTT Session with Sparkplug defined Death Certificate. It may not be * Immediately intuitive that the Death Certificate is created prior to publishing the * Birth Certificate, but the Death Certificate is actually part of the MQTT Session * establishment. For complete details of the actual MQTT wire protocol refer to the * latest OASyS MQTT V3.1.1 standards at: * http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html * * @return true = MQTT Session Established */ public boolean establishMqttSession() { try { // // Setup the MQTT connection parameters using the Paho MQTT Client. // MqttConnectOptions options = new MqttConnectOptions(); if (USING_REAL_TLS) { SocketFactory sf = SSLSocketFactory.getDefault(); options.setSocketFactory(sf); } // Autoreconnect enable options.setAutomaticReconnect(true); // MQTT session parameters Clean Start = true options.setCleanSession(true); // Session connection attempt timeout period in seconds options.setConnectionTimeout(10); // MQTT session parameter Keep Alive Period in Seconds options.setKeepAliveInterval(30); // MQTT Client Username options.setUserName(username); // MQTT Client Password options.setPassword(password.toCharArray()); // // Build up the Death Certificate MQTT Payload. Note that the Death // Certificate payload sequence number // is not tied to the normal message sequence numbers. // SparkplugBPayload payload = new SparkplugBPayloadBuilder(getNextSeqNum()) .setTimestamp(new Date()) .addMetric(new MetricBuilder("bdSeq", MetricDataType.Int64, bdSeq) .createMetric()) .createPayload(); byte[] bytes = new SparkplugBPayloadEncoder().getBytes(payload); // // Setup the Death Certificate Topic/Payload into the MQTT session // parameters // options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, bytes, 0, false); // // Create a new Paho MQTT Client // client = new MqttClient(serverUrl, clientId); // // Using the parameters set above, try to connect to the define MQTT // server now. // System.out.println("Trying to establish an MQTT Session to the MQTT Server @ :" + serverUrl); client.connect(options); System.out.println("MQTT Session Established"); client.setCallback(this); // // With a successful MQTT Session in place, now issue subscriptions // for the EoN Node and Device "Command" Topics of 'NCMD' and 'DCMD' // defined in Sparkplug // client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0); client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0); } catch (Exception e) { System.out.println("Error Establishing an MQTT Session:"); e.printStackTrace(); return false; } return true; }
Example 14
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 15
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 16
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(); } }