Java Code Examples for org.eclipse.paho.client.mqttv3.MqttConnectOptions#setConnectionTimeout()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttConnectOptions#setConnectionTimeout() . 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: MqttService.java    From PresencePublisher with MIT License 6 votes vote down vote up
public void sendMessages(List<Message> messages) throws MqttException {
    HyperLog.i(TAG, "Sending " + messages.size() + " messages to server");
    boolean tls = sharedPreferences.getBoolean(USE_TLS, false);
    String clientCertAlias = sharedPreferences.getString(CLIENT_CERTIFICATE, null);
    String login = sharedPreferences.getString(USERNAME, "");
    String password = securePreferences.getString(PASSWORD, "");

    MqttClient mqttClient = new MqttClient(getMqttUrl(tls), Settings.Secure.ANDROID_ID, new MemoryPersistence());
    MqttConnectOptions options = new MqttConnectOptions();
    options.setConnectionTimeout(5);
    if (!login.isEmpty() && !password.isEmpty()) {
        options.setUserName(login);
        options.setPassword(password.toCharArray());
    }
    if (tls) {
        options.setSocketFactory(factory.getSslSocketFactory(clientCertAlias));
    }
    mqttClient.connect(options);
    for (Message message : messages) {
        mqttClient.publish(message.getTopic(), message.getContent().getBytes(Charset.forName("UTF-8")), 1, false);
    }
    mqttClient.disconnect(5);
    mqttClient.close(true);
    HyperLog.i(TAG, "Sending messages was successful");
}
 
Example 2
Source File: AwsIotMqttConnection.java    From aws-iot-device-sdk-java with Apache License 2.0 6 votes vote down vote up
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 3
Source File: DeviceConfig.java    From iot-java with Eclipse Public License 1.0 6 votes vote down vote up
public MqttConnectOptions getMqttConnectOptions() throws NoSuchAlgorithmException, KeyManagementException {
	MqttConnectOptions connectOptions = new MqttConnectOptions();

	connectOptions.setConnectionTimeout(DEFAULT_CONNECTION_TIMEMOUT);

	if (getMqttPassword() != null) {
		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);

	if (!Arrays.asList(1883, 80).contains(options.mqtt.port)) {
		SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
		sslContext.init(null, null, null);

		connectOptions.setSocketFactory(sslContext.getSocketFactory());
	}

	return connectOptions;
}
 
Example 4
Source File: SocketProxyTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenPahoConnectToBrokerViaProxyThenItWorks() throws Throwable {
    
    // Wait a second
    Thread.sleep(1000);
    
    // Create the client
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(false);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
    MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    
    // Connect, publish, disconnect
    AsyncPahoUtils.connect(asyncClient);
    AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes());
    AsyncPahoUtils.disconnect(asyncClient);
    
    // Check we received a message
    Assert.assertEquals(1, broker.getMessages().size());
    
}
 
Example 5
Source File: ApplicationConfig.java    From iot-java with Eclipse Public License 1.0 6 votes vote down vote up
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 6
Source File: VenvyMqttClientHelper.java    From VideoOS-Android-SDK with GNU General Public License v3.0 6 votes vote down vote up
private MqttConnectOptions initMqttOption() {
    // MQTT的连接设置

    MqttConnectOptions connectOption = new MqttConnectOptions();// MQTT参数
    // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
    connectOption.setCleanSession(false);
    // 设置连接的用户名
    connectOption.setUserName(socketKey);
    connectOption.setServerURIs(new String[]{serverUrl});
    // 设置连接的密码
    connectOption.setPassword(socketPassword.toCharArray());
    // 设置超时时间 单位为秒
    connectOption.setConnectionTimeout(15);
    // 设置会话心跳时间 单位为秒 服务器会每隔2*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
    connectOption.setKeepAliveInterval(40);
    return connectOption;
}
 
Example 7
Source File: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectWithDefaultVersion() {
    try {
        String clientId = UUID.randomUUID().toString();
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setConnectionTimeout(this.actionTimeout);
        mqttClient.connect(connOpts);

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 8
Source File: SocketProxyTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenAutoReconnectThenPahoReconnectsAfterProxyDisable() throws Throwable {
    
    // Create the client
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(true);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
    MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    
    // Connect, publish
    AsyncPahoUtils.connect(asyncClient, options);
    AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes());
    AsyncPahoUtils.subscribe(asyncClient, "topical2", (t, m) -> {});
    Assert.assertEquals(1, broker.getMessages().size());
    
    // Disable proxy
    brokerProxy.disable();
    Thread.sleep(5000);
    
    // Check disconnected
    Assert.assertFalse(asyncClient.isConnected());
    
    // Re-enable
    brokerProxy.enable();
    Thread.sleep(10000);
    AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes());
    
    
    // Check connected
    Assert.assertTrue(asyncClient.isConnected());
    
}
 
Example 9
Source File: SocketProxyTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenProxyDisabledThenPahoDisconnect() throws Throwable {
    
    // Wait a second
    Thread.sleep(1000);
    
    // Create the client
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(false);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
    MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    
    // Connect, publish
    AsyncPahoUtils.connect(asyncClient, options);
    AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes());
    AsyncPahoUtils.subscribe(asyncClient, "topical2", (t, m) -> {});
    Assert.assertEquals(1, broker.getMessages().size());
    
    // Disable proxy
    brokerProxy.disable();
    Thread.sleep(3000);
    
    // Check disconnected
    Assert.assertFalse(asyncClient.isConnected());
    
}
 
Example 10
Source File: MainActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 5 votes vote down vote up
private void startConnect(String clientID, String serverIP, String port) {
    //服务器地址
    String  uri ="tcp://";
    uri=uri+serverIP+":"+port;
    Log.d("MainActivity",uri+"  "+clientID);
    /**
     * 连接的选项
     */
    MqttConnectOptions conOpt = new MqttConnectOptions();
    /**设计连接超时时间*/
    conOpt.setConnectionTimeout(3000);
    /**设计心跳间隔时间300秒*/
    conOpt.setKeepAliveInterval(300);
    /**
     * 创建连接对象
     */
     client = new MqttAndroidClient(this,uri, clientID);
    /**
     * 连接后设计一个回调
     */
    client.setCallback(new MqttCallbackHandler(this, clientID));
    /**
     * 开始连接服务器,参数:ConnectionOptions,  IMqttActionListener
     */
    try {
        client.connect(conOpt, null, new ConnectCallBackHandler(this));
    } catch (MqttException e) {
        e.printStackTrace();
    }

}
 
Example 11
Source File: AbstractMQTTProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
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: MoquetteConnectivityTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenBrokerIsStoppedThenClientIsDisconnected() throws Throwable {
    
	// Create client with re-connect and dirty sessions
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(false);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
	MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    ObservableMqttClient observableClient = observableClient(asyncClient, options);
    
    // Connect
    observableClient.connect().blockingAwait();
    Assert.assertTrue(observableClient.isConnected());

    // Stop the broker proxy
    this.brokerProxy.disable();
    Thread.sleep(3000);
    Assert.assertFalse(observableClient.isConnected());
 
    // Restart the broker proxy
    this.brokerProxy.enable();
    Thread.sleep(3000);
    Assert.assertFalse(observableClient.isConnected());
    
}
 
Example 13
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test(expected = MqttException.class)
public void testConnect31ClientTooLong() throws MqttException {
    // client id must less then 23 bytes in 3.1
    String clientId = UUID.randomUUID().toString();
    MqttClient mqttClient = new MqttClient(this.url, clientId, null);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setConnectionTimeout(this.actionTimeout);
    connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
    mqttClient.connect(connOpts);

    Assert.assertTrue(true);
}
 
Example 14
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectWithDefaultVersion() {
    try {
        String clientId = UUID.randomUUID().toString();
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setConnectionTimeout(this.actionTimeout);
        mqttClient.connect(connOpts);

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example 15
Source File: SparkplugExample.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
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 16
Source File: MqttPahoClient.java    From joynr with Apache License 2.0 5 votes vote down vote up
private MqttConnectOptions getConnectOptions() {
    MqttConnectOptions options = new MqttConnectOptions();
    if (username != null && !username.isEmpty()) {
        if (password == null || password.isEmpty()) {
            throw new JoynrIllegalStateException("MQTT password not configured or empty");
        }
        options.setUserName(username);
        options.setPassword(password.toCharArray());
    }
    options.setAutomaticReconnect(false);
    options.setConnectionTimeout(connectionTimeoutSec);
    options.setKeepAliveInterval(keepAliveTimerSec);
    options.setMaxInflight(maxMsgsInflight);
    options.setCleanSession(cleanSession);

    if (isSecureConnection) {
        // Set global SSL properties for all Joynr SSL clients
        Properties sslClientProperties = new Properties();
        sslClientProperties.setProperty(SSLSocketFactoryFactory.KEYSTORETYPE, keyStoreType);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.KEYSTORE, keyStorePath);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.KEYSTOREPWD, keyStorePWD);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.TRUSTSTORETYPE, trustStoreType);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.TRUSTSTORE, trustStorePath);
        sslClientProperties.setProperty(SSLSocketFactoryFactory.TRUSTSTOREPWD, trustStorePWD);
        options.setSSLProperties(sslClientProperties);
    }

    return options;
}
 
Example 17
Source File: SparkplugExample.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
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 18
Source File: SparkplugRaspberryPiExample.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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 19
Source File: SparkplugExample.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
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 20
Source File: EngineTemperatureSensorLiveTest.java    From tutorials with MIT License 3 votes vote down vote up
@Test
public void whenSendSingleMessage_thenSuccess() throws Exception {

    String publisherId = UUID.randomUUID().toString();
    MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId);
    
    String subscriberId = UUID.randomUUID().toString();
    MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId);
    
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(true);
    options.setCleanSession(true);
    options.setConnectionTimeout(10);
    
    
    subscriber.connect(options);
    publisher.connect(options);
    
    CountDownLatch receivedSignal = new CountDownLatch(1);
    
    subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> {
        byte[] payload = msg.getPayload();
        log.info("[I46] Message received: topic={}, payload={}", topic, new String(payload));
        receivedSignal.countDown();
    });
    
    
    Callable<Void> target = new EngineTemperatureSensor(publisher);
    target.call();

    receivedSignal.await(1, TimeUnit.MINUTES);

    log.info("[I56] Success !");
}