本文整理汇总了Java中org.eclipse.paho.client.mqttv3.MqttConnectOptions.setWill方法的典型用法代码示例。如果您正苦于以下问题:Java MqttConnectOptions.setWill方法的具体用法?Java MqttConnectOptions.setWill怎么用?Java MqttConnectOptions.setWill使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.eclipse.paho.client.mqttv3.MqttConnectOptions
的用法示例。
在下文中一共展示了MqttConnectOptions.setWill方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getMqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
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;
}
示例2: buildMqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private MqttConnectOptions buildMqttConnectOptions(AbstractAwsIotClient client, SocketFactory socketFactory) {
MqttConnectOptions options = new MqttConnectOptions();
options.setSocketFactory(socketFactory);
options.setCleanSession(true);
options.setConnectionTimeout(client.getConnectionTimeout() / 1000);
options.setKeepAliveInterval(client.getKeepAliveInterval() / 1000);
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;
}
示例3: connect
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
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);
}
}
示例4: doConnectBroker
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private boolean doConnectBroker() {
try {
LOG.debug("{} > connect..", url);
final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setUserName("admin");
mqttConnectOptions.setPassword("admin".toCharArray());
mqttConnectOptions.setCleanSession(true);
mqttConnectOptions.setWill(pubTopic2Mqtt, "Bye, bye Baby!".getBytes(), 0, false);
// client
final String tmpDir = System.getProperty("java.io.tmpdir");
final MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
LOG.info("creating MqttAsyncClient for {} and {}", url, clientId);
mqttAsyncClient = new MqttAsyncClient(url, clientId, dataStore);
// callback
mqttAsyncClient.setCallback(this);
// connect
mqttAsyncClient.connect(mqttConnectOptions).waitForCompletion();
// subscriptions
for (final String subTopic : subTopics) {
LOG.info("client {} subscribing to {}", clientId, subTopic);
mqttAsyncClient.subscribe(subTopic, 0);
}
LOG.info("{} > mqtt connection established for {}.", url, clientId);
return true;
} catch (final Throwable throwable) {
LOG.error("{} > connection failed. ({})", url, throwable.getMessage());
close();
return false;
}
}
示例5: establishMqttSession
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
/**
* 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;
}
示例6: run
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
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();
}
}
示例7: run
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
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();
}
}
示例8: disconnection
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
@Test
public void disconnection(TestContext context) {
Async async = context.async();
this.lwtService.willHandler(b -> {
async.complete();
});
try {
MemoryPersistence persistence = new MemoryPersistence();
MqttConnectOptions options = new MqttConnectOptions();
options.setWill(new MqttTopic(MQTT_WILL_TOPIC, null), MQTT_WILL_MESSAGE.getBytes(), 1, false);
MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), CLIENT_ID, persistence);
client.connect(options);
client.disconnect();
async.await();
context.assertTrue(true);
} catch (MqttException e) {
context.assertTrue(false);
e.printStackTrace();
}
}
示例9: willClient
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private void willClient(TestContext context, String topic, String message, int qos) {
this.async = context.async();
try {
MemoryPersistence persistence = new MemoryPersistence();
MqttConnectOptions options = new MqttConnectOptions();
options.setWill(new MqttTopic(topic, null), message.getBytes(), qos, false);
// workaround for testing "brute disconnection" ignoring the DISCONNECT
// Eclipse Paho doesn't provide a way to close connection without sending DISCONNECT
// The mock Last Will and Testament Service will not clear the will message for this "ignore-disconnect" client
MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), WILL_CLIENT_ID, persistence);
client.connect(options);
client.disconnect();
this.async.await();
context.assertTrue(true);
} catch (MqttException e) {
context.assertTrue(false);
e.printStackTrace();
}
}
示例10: connect
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private void connect(TestContext context, boolean isCleanSession, String clientId, boolean isWill) {
Async async = context.async();
try {
MemoryPersistence persistence = new MemoryPersistence();
MqttConnectOptions options = new MqttConnectOptions();
if (isWill) {
options.setWill(new MqttTopic(MQTT_WILL_TOPIC, null), MQTT_WILL_MESSAGE.getBytes(), 1, false);
}
options.setCleanSession(isCleanSession);
MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), clientId, persistence);
client.connect(options);
context.assertTrue(true);
async.complete();
} catch (MqttException e) {
context.assertTrue(false);
e.printStackTrace();
}
}