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

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttConnectOptions#setKeepAliveInterval() . 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: 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 2
Source File: AbstractMqttClient.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * 连接mqtt server,并返回一个客户端对象,如果连接失败,那么返回null
 */
public MqttAsyncClient connectBroker() {
    LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 准备建立连接,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName));
    try {
        sampleClient = new MqttAsyncClient("tcp://overriddenByMqttConnectOptions.setServerURIs:1883", getMqttClientId(), persistence);
        connOpts = new MqttConnectOptions();
        connOpts.setAutomaticReconnect(true);
        connOpts.setServerURIs(serverURIs);
        connOpts.setUserName(userName);
        connOpts.setPassword(getPwd());
        connOpts.setCleanSession(cleanSession);
        connOpts.setMaxInflight(1000 /**默认的值是10,对于我们来说这个值太小!*/);
        connOpts.setKeepAliveInterval(keepAliveInterval);
        sampleClient.setCallback(getCallback(this));
        sampleClient.connect(connOpts).waitForCompletion(60 * 1000);
        LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 建立连接完成,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName));
        return sampleClient;
    } catch (MqttException me) {
        throw new RuntimeException(String.format("mqtt=======客户端%s与rabbitMQ server: %s 连接失败!!! userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName), me);
    }
}
 
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: 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 5
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 6
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 7
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 8
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 9
Source File: ToxiproxyConnectivityITCase.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Ignore
@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 10
Source File: MQTT_PVConn.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
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 11
Source File: MqttConfig.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
@Bean
public MqttConnectOptions getMqttConnectOptions() {
    MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
    mqttConnectOptions.setUserName(mqttProperty.getUsername());
    mqttConnectOptions.setPassword(mqttProperty.getPassword().toCharArray());
    mqttConnectOptions.setServerURIs(new String[]{mqttProperty.getUrl()});
    mqttConnectOptions.setKeepAliveInterval(mqttProperty.getKeepAlive());
    return mqttConnectOptions;
}
 
Example 12
Source File: BlockingClient.java    From mqtt-jmeter with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance of the sample client wrapper
 *
 * @param brokerUrl    the url of the server to connect to
 * @param clientId     the client id to connect with
 * @param cleanSession clear state at end of connection or not (durable or non-durable subscriptions)
 * @param userName     the username to connect with
 * @param password     the password for the user
 * @throws MqttException
 */
public BlockingClient(String brokerUrl, String clientId, boolean cleanSession, String userName,
                      String password, int keepAlive) throws MqttException {
    this.brokerUrl = brokerUrl;
    String testPlanFileDir = System.getProperty("java.io.tmpdir") + File.separator + "mqtt" + File.separator +
                             clientId + File.separator + Thread.currentThread().getId();
    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(testPlanFileDir);

    // Construct the connection options object that contains connection parameters
    // such as cleanSession and LWT
    MqttConnectOptions conOpt = new MqttConnectOptions();
    conOpt.setCleanSession(cleanSession);
    if (password != null && !password.isEmpty()) {
        conOpt.setPassword(password.toCharArray());
    }
    if (userName != null && !userName.isEmpty()) {
        conOpt.setUserName(userName);
    }

    // Setting keep alive time
    conOpt.setKeepAliveInterval(keepAlive);

    // Construct an MQTT blocking mode client
    client = new MqttClient(this.brokerUrl, clientId, dataStore);

    // Set this wrapper as the callback handler
    client.setCallback(this);

    // Connect to the MQTT server
    log.info("Connecting to " + brokerUrl + " with client ID '" + client.getClientId() + "' and cleanSession is " +
                                                            String.valueOf(cleanSession) + " as a blocking client");
    client.connect(conOpt);
    log.info("Connected");
}
 
Example 13
Source File: MqttSubscriberClient.java    From product-iots with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param serverAddress Mqtt broker address
 * @param clientId Client ID
 * @param topicName Topic Name
 * @throws MqttException Mqtt Exception
 */
public MqttSubscriberClient(String serverAddress, String clientId, String topicName, String accessToken) throws
        MqttException {
    mqttMessages = new ArrayList<>();
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(serverAddress, clientId, persistence);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    client.setCallback(this);
    connectOptions.setUserName(accessToken);
    connectOptions.setPassword("".toCharArray());
    connectOptions.setCleanSession(true);
    connectOptions.setKeepAliveInterval(300);
    client.connect(connectOptions);
    client.subscribe(topicName);
}
 
Example 14
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 15
Source File: MoquetteConnectivityTest.java    From rxmqtt with Apache License 2.0 4 votes vote down vote up
/**
* This test is unreliable because the subscriptions
* don't always arrive.
* Need to investigate why this is and reinstate.
*/

@Ignore
@Test
public void whenAutoReconnectAndCleanSessionFalseThenNoNeedToResubscribe() throws Throwable {
	
	// Create a latch and a way to count subscription receipts
	CountDownLatch latch = new CountDownLatch(2);
	List<SubscribeMessage> subscribes = new ArrayList<>();
    
    // Create client with re-connect and dirty sessions
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(true);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    // Topic
    String topic = "topical";
    
    // Create clients
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
    MqttAsyncClient publisher = new MqttAsyncClient(proxyUrl, "test-publisher-id", new MemoryPersistence(), new TimerPingSender());
    MqttAsyncClient subscriber = new MqttAsyncClient(proxyUrl, "test-subscriber-id", new MemoryPersistence(), new TimerPingSender());
    ObservableMqttClient publisherObs = observableClient(publisher, options);
    ObservableMqttClient subscriberObs = observableClient(subscriber, options);
    
    // Connect, subscribe, publish test message
    publisherObs.connect().blockingAwait();
    subscriberObs.connect().blockingAwait();
    Assert.assertTrue(subscriberObs.isConnected());
    Assert.assertTrue(publisherObs.isConnected());
    subscriberObs.subscribe(topic, 1).subscribe(m -> {
    	System.out.println(m);
    	subscribes.add(m);
    	latch.countDown();
    });
    publisherObs.publish(topic, PublishMessage.create("Test Message 1".getBytes(), 1, false)).blockingGet();
    Assert.assertEquals(1, broker.getMessages().size());
    
    // Stop the proxy, wait, check status
    brokerProxy.disable();
    Thread.sleep(3000);
    Assert.assertFalse(publisherObs.isConnected());
    Assert.assertFalse(subscriberObs.isConnected());
 
    // Restart the broker, wait, check status
    brokerProxy.enable();
    Thread.sleep(10000);
    Assert.assertTrue(publisherObs.isConnected());
    Assert.assertTrue(subscriberObs.isConnected());
    
    // Publish and check for subscription
    publisherObs.publish(topic, PublishMessage.create("Test Message 2".getBytes(), 1, false)).blockingGet();
    Assert.assertEquals(2, broker.getMessages().size());
    
    // Check we got all the messages on the subscription
    latch.await(3, TimeUnit.SECONDS);	
    Assert.assertEquals(2, subscribes.size());
}
 
Example 16
Source File: MQTTClientBuilder.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private MqttConnectOptions getOptions() {
  MqttConnectOptions options = new MqttConnectOptions();

  if ( isSecure ) {
    setSSLProps( options );
  }
  if ( !StringUtil.isEmpty( username ) ) {
    options.setUserName( username );
  }
  if ( !StringUtil.isEmpty( password ) ) {
    options.setPassword( password.toCharArray() );
  }

  if ( !StringUtil.isEmpty( keepAliveInterval ) ) {
    options.setKeepAliveInterval( Integer.parseInt( keepAliveInterval ) );
  }

  if ( !StringUtil.isEmpty( maxInflight ) ) {
    options.setMaxInflight( Integer.parseInt( maxInflight ) );
  }

  if ( !StringUtil.isEmpty( connectionTimeout ) ) {
    options.setConnectionTimeout( Integer.parseInt( connectionTimeout ) );
  }

  if ( !StringUtil.isEmpty( cleanSession ) ) {
    options.setCleanSession( BooleanUtils.toBoolean( cleanSession ) );
  }

  if ( !StringUtil.isEmpty( serverUris ) ) {
    options.setServerURIs(
      Arrays.stream( serverUris.split( ";" ) ).map( uri -> getProtocol() + uri ).toArray( String[]::new ) );
  }

  if ( !StringUtil.isEmpty( mqttVersion ) ) {
    options.setMqttVersion( Integer.parseInt( mqttVersion ) );
  }

  if ( !StringUtil.isEmpty( automaticReconnect ) ) {
    options.setAutomaticReconnect( BooleanUtils.toBoolean( automaticReconnect ) );
  }

  return options;
}
 
Example 17
Source File: AsyncClient.java    From mqtt-jmeter with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs an instance of the sample client wrapper
 *
 * @param brokerUrl    the url to connect to
 * @param clientId     the client id to connect with
 * @param cleanSession clear state at end of connection or not (durable or non-durable subscriptions)
 * @param userName     the username to connect with
 * @param password     the password for the user
 * @throws MqttException
 */
public AsyncClient(String brokerUrl, String clientId, boolean cleanSession,
                   String userName, String password, int keepAlive) throws MqttException {
    this.brokerUrl = brokerUrl;

    String testPlanFileDir = System.getProperty("java.io.tmpdir") + File.separator + "mqtt" + File.separator +
                                                        clientId + File.separator + Thread.currentThread().getId();
    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(testPlanFileDir);

    try {
        // Construct the connection options object that contains connection parameters
        // such as cleanSession and LWT
        MqttConnectOptions conOpt = new MqttConnectOptions();
        conOpt.setCleanSession(cleanSession);
        if (password != null && !password.isEmpty()) {
            conOpt.setPassword(password.toCharArray());
        }
        if (userName != null && !userName.isEmpty()) {
            conOpt.setUserName(userName);
        }

        // Setting keep alive time
        conOpt.setKeepAliveInterval(keepAlive);

        // Construct a non-blocking MQTT client instance
        client = new MqttAsyncClient(this.brokerUrl, clientId, dataStore);

        // Set this wrapper as the callback handler
        client.setCallback(this);

        // Connect to the MQTT server
        // issue a non-blocking connect and then use the token to wait until the
        // connect completes. An exception is thrown if connect fails.
        log.info("Connecting to " + brokerUrl + " with client ID '" + client.getClientId() + "' and cleanSession " +
                 "                                  is " + String.valueOf(cleanSession) + " as an async clientt");
        IMqttToken conToken = client.connect(conOpt, null, null);
        conToken.waitForCompletion();
        log.info("Connected");

    } catch (MqttException e) {
        log.info("Unable to set up client: " + e.toString());
    }
}
 
Example 18
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 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(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 20
Source File: MqttClientHandler.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void connect(String brokerURL, String userName, String password, 
			boolean ssl, boolean cleanSession) throws Exception {
		MqttConnectOptions connOpt = new MqttConnectOptions();

		connOpt.setCleanSession(cleanSession);
		connOpt.setKeepAliveInterval(keepAliveInterval);

		if (userName != null) {
			connOpt.setUserName(userName);
		}
		if  (password != null) {
			connOpt.setPassword(password.toCharArray());
		}

		if(ssl) {
//			SSLContext sslContext = SSLContext.getInstance("TLS");
//			TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//			KeyStore keyStore = KeyStore.getInstance("JKS");
//			InputStream in = new FileInputStream(KEY_STORE_LOCATION);
//			keyStore.load(in, KEY_STORE_PASSWORD.toCharArray());
//			
//			trustManagerFactory.init(keyStore);
//			sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
//			 
//			connOpt.setSocketFactory(sslContext.getSocketFactory());
			
			
//			connOpt.setSocketFactory(SSLSocketFactory.getDefault());
		}
		
		
//		mqttClient = new MqttAsyncClient(brokerURL, clientID);
		mqttClient = new MqttClient(brokerURL, clientID);
		mqttClient.setCallback(this);
		mqttClient.connect(connOpt);
//		mqttClient.connect(connOpt, new IMqttActionListener() {
//
//			@Override
//			public void onSuccess(IMqttToken asyncActionToken) {
//				// TODO Auto-generated method stub
//				try {
//					setSubscribe();
//				} catch (Exception e) {
//					log.error("Subscription exception: ", e);
//				}
//			}
//
//			@Override
//			public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//		});
		log.debug("MQTT] connected to mqtt borker.");
	
//		pingSender = new TimerPingSender();
//		pingSender.schedule((keepAliveInterval-5)*1000);
//		pingSender.start();
		
//		MqttDeliveryToken token = new MqttDeliveryToken(getClientId());
//		MqttPingReq pingMsg = new MqttPingReq();
//		mqttClient. sendNoWait(pingMsg, token);
		
	}