當前位置: 首頁>>代碼示例>>Java>>正文


Java MqttConnectOptions.setWill方法代碼示例

本文整理匯總了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;
}
 
開發者ID:emqtt,項目名稱:EMQ-Android-Toolkit,代碼行數:21,代碼來源:Connection.java

示例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;
}
 
開發者ID:aws,項目名稱:aws-iot-device-sdk-java,代碼行數:24,代碼來源:AwsIotMqttConnection.java

示例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);
    }
}
 
開發者ID:Cirrus-Link,項目名稱:Sparkplug,代碼行數:23,代碼來源:MainActivity.java

示例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;
	}
}
 
開發者ID:dcsolutions,項目名稱:kalinka,代碼行數:37,代碼來源:MqttClient.java

示例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;
}
 
開發者ID:Cirrus-Link,項目名稱:Sparkplug,代碼行數:81,代碼來源:SparkplugRaspberryPiExample.java

示例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();
	}
}
 
開發者ID:Cirrus-Link,項目名稱:Sparkplug,代碼行數:62,代碼來源:SparkplugExample.java

示例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();
	}
}
 
開發者ID:Cirrus-Link,項目名稱:Sparkplug,代碼行數:57,代碼來源:SparkplugExample.java

示例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();
    }
}
 
開發者ID:EnMasseProject,項目名稱:enmasse,代碼行數:33,代碼來源:DisconnectionTest.java

示例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();
        }
    }
 
開發者ID:EnMasseProject,項目名稱:enmasse,代碼行數:30,代碼來源:DisconnectionTest.java

示例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();
        }
    }
 
開發者ID:EnMasseProject,項目名稱:enmasse,代碼行數:28,代碼來源:ConnectionTest.java


注:本文中的org.eclipse.paho.client.mqttv3.MqttConnectOptions.setWill方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。