Java Code Examples for org.eclipse.paho.client.mqttv3.MqttClient#setCallback()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttClient#setCallback() . 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: SparkplugListener.java    From Sparkplug with Eclipse Public License 1.0 6 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(5000);						// short timeout on failure to connect
		client.connect(options);
		client.setCallback(this);
		
		// Just listen to all DDATA messages on spAv1.0 topics and wait for inbound messages
		client.subscribe("spBv1.0/#", 0);
	} catch(Exception e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: WildcardSubscriber.java    From paho-wildcard-subscriber with Apache License 2.0 6 votes vote down vote up
public void start() {
    log.info("Starting Wilcard subscriber");
    try {
        final String clientId = MqttClient.generateClientId();
        final MqttClient mqttClient = new MqttClient(BROKER_URL, clientId, new MemoryPersistence());

        mqttClient.setCallback(new SubscribeCallback(mqttClient));

        log.info("Connecting to {} with clientID {}", BROKER_URL, clientId);
        mqttClient.connect();

        //We subscribe to wildcard
        log.info("Subscribing to {}", TOPIC_SUBSCRIPTION);
        mqttClient.subscribe(TOPIC_SUBSCRIPTION, QUALITY_OF_SERVICE_LEVEL);

    } catch (MqttException e) {
        log.error("An unexpected error occured. Exiting", e);
        System.exit(1);
    }
}
 
Example 3
Source File: TestMqttAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private MqttClient receive(final List<MqttMessage> received) throws MqttException, MqttSecurityException {
    MqttClient client = new MqttClient(SERVER, "test");
    MqttCallback callback = new MqttCallback() {
        
        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            received.add(message);
            System.out.println(message);
        }
        
        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }
        
        @Override
        public void connectionLost(Throwable cause) {
            cause.printStackTrace();
        }
    };
    client.connect();
    client.subscribe(TOPIC);
    client.setCallback(callback);
    return client;
}
 
Example 4
Source File: MQTTTestClient.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a MQTT client with given parameters
 *
 * @param brokerURL url of MQTT provider
 * @param userName username to connect to MQTT provider
 * @param password password to connect to MQTT provider
 * @param clientId unique id for the publisher/subscriber client
 * @throws MqttException in case of issue of connect/publish/consume
 */
public MQTTTestClient(String brokerURL, String userName, char[] password, String clientId) throws MqttException {
    this.brokerURL = brokerURL;
    //Store messages until server fetches them
    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(JAVA_TMP_DIR + "/" + clientId);
    mqttClient = new MqttClient(brokerURL, clientId, dataStore);
    SimpleMQTTCallback callback = new SimpleMQTTCallback();
    mqttClient.setCallback(callback);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    connectOptions.setUserName(userName);
    connectOptions.setPassword(password);
    connectOptions.setCleanSession(true);
    mqttClient.connect(connectOptions);

    log.info("MQTTTestClient successfully connected to broker at " + this.brokerURL);
}
 
Example 5
Source File: ManualReceive.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private void receive() throws Exception {
    MqttClient client = new MqttClient(SERVER, "test");
    MqttCallback callback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            System.out.println(message);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }

        @Override
        public void connectionLost(Throwable cause) {
            cause.printStackTrace();
        }
    };
    client.connect();
    client.subscribe(TOPIC_FILTER);
    client.setCallback(callback);
    System.in.read();
    client.disconnect();
    client.close();
}
 
Example 6
Source File: MQTTTestClient.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a MQTT client with given parameters
 *
 * @param brokerURL url of MQTT provider
 * @param userName  username to connect to MQTT provider
 * @param password  password to connect to MQTT provider
 * @param clientId  unique id for the publisher/subscriber client
 * @throws MqttException in case of issue of connect/publish/consume
 */
public MQTTTestClient(String brokerURL, String userName, char[] password, String clientId) throws MqttException {
    this.brokerURL = brokerURL;
    //Store messages until server fetches them
    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(JAVA_TMP_DIR + "/" + clientId);
    mqttClient = new MqttClient(brokerURL, clientId, dataStore);
    SimpleMQTTCallback callback = new SimpleMQTTCallback();
    mqttClient.setCallback(callback);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    connectOptions.setUserName(userName);
    connectOptions.setPassword(password);
    connectOptions.setCleanSession(true);
    mqttClient.connect(connectOptions);

    log.info("MQTTTestClient successfully connected to broker at " + this.brokerURL);
}
 
Example 7
Source File: MqttJsonServer.java    From diozero with MIT License 5 votes vote down vote up
public MqttJsonServer(String mqttUrl) throws UnknownHostException, MqttException {
	mqttClient = new MqttClient(mqttUrl, CLIENT_ID_PREFIX + InetAddress.getLocalHost().getHostName(),
			new MemoryPersistence());
	mqttClient.setCallback(this);
	MqttConnectOptions con_opts = new MqttConnectOptions();
	con_opts.setAutomaticReconnect(true);
	con_opts.setCleanSession(true);
	Logger.debug("Connecting to {}...", mqttUrl);
	mqttClient.connect(con_opts);
	Logger.debug("Connected to {}", mqttUrl);
}
 
Example 8
Source File: TrainLocationClient.java    From osgi.iot.contest.sdk with Apache License 2.0 5 votes vote down vote up
@Activate
void activate(LocationConfig config) {

    initConfig(config.code2tag());

    BiFunction<String, String, String> getOrDefault = (t, u) -> t != null ? t : u;

    try {
        String brokerUrl = getOrDefault.apply(config.brokerUrl(), BROKER_URL);
        String username = getOrDefault.apply(config.username(), USERNAME);
        String password = getOrDefault.apply(config.password(), PASSWORD);

        MqttConnectOptions options = new MqttConnectOptions();
        if (!username.isEmpty()) {
            options.setUserName(username);
            options.setPassword(password.toCharArray());
        }

        // Connect and start the session
        info("Connecting to MQTT broker <{}>", brokerUrl);
        mqttClient = new MqttClient(brokerUrl, CLIENT_ID);
        mqttClient.setCallback(new MyCallbackHandler());
        mqttClient.connect(options);

        // Subscribe
        String topic = "TrainDemo/#";
        info("Subscribing to topic <{}>", topic);
        mqttClient.subscribe(topic);
    } catch (Exception e) {
        error(e.toString());
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: MQTTInputConnector.java    From mqtt-client-connector with Eclipse Public License 1.0 5 votes vote down vote up
@Override
  public void start() throws MbException  {
      writeServiceTraceEntry(clsName, "start", "Entry");
      
      try {
	String clientId = getProperties().getProperty("clientId");
	String clientName = clientId;
	if (clientId == null) {
		clientName = getConnectorFactory().getContainerServices()
				.containerName() + getName();
	}
	if (clientName.length() > 23) {
		clientName = clientName.substring(clientName.length() - 23);
	}
	try {
		dataStore = ((MQTTConnectorFactory)getConnectorFactory()).getClientPersistence();
		client = new MqttClient(connectionUrl, clientName, dataStore);
		client.setCallback(this);
		connectClient();
              writeActivityLog("12066", 	new String[] {connectionUrl, clientId},
				activityLogTag);
	} catch (MqttException e) {
		if (failedToConnect == false) {
			failedToConnect = true;

			writeActivityLog("12067", new String[] { connectionUrl + " when starting " + client.getClientId() },
					activityLogTag);
			writeActivityLog("12071", new String[] { connectionUrl },
					activityLogTag);
		}
		getConnectorFactory().getContainerServices()
		.throwMbRecoverableException("12067",
				new String[] { connectionUrl + " when starting " + client.getClientId() });
	}
	writeActivityLog("12063", new String[] { connectionUrl },
			activityLogTag);
} finally {
	writeServiceTraceExit(clsName, "start", "Exit");
}
  }
 
Example 10
Source File: ManagerMQTT.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
@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 11
Source File: MQTTEventAdapter.java    From osgi.iot.contest.sdk with Apache License 2.0 5 votes vote down vote up
@Activate	
void activate(Config config, BundleContext context) throws Exception {
	id = context.getProperty(Constants.FRAMEWORK_UUID).toString();
	try {
		mqtt = new MqttClient(config.broker(), id);
		mqtt.connect();
		mqtt.setCallback(this);
		for(String topic : config.mqtt_topics()){
			mqtt.subscribe(topic.replaceAll("\\*", "#"));
		}
	} catch(Exception e){
		System.err.println("Error connecting to MQTT broker "+config.broker());
		throw e;
	}
}
 
Example 12
Source File: MqttTestApp.java    From diozero with MIT License 5 votes vote down vote up
public MqttTestApp() throws UnknownHostException, MqttException {
	mqttClient = new MqttClient(mqttUrl, CLIENT_ID_PREFIX + InetAddress.getLocalHost().getHostName(),
			new MemoryPersistence());
	mqttClient.setCallback(this);
	MqttConnectOptions con_opts = new MqttConnectOptions();
	con_opts.setAutomaticReconnect(true);
	con_opts.setCleanSession(true);
	Logger.debug("Connecting to {}...", mqttUrl);
	mqttClient.connect(con_opts);
	Logger.debug("Connected to {}", mqttUrl);

	mqttClient.subscribe("outTopic");
	mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
}
 
Example 13
Source File: PahoMQTTTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 300000)
public void testSendAndReceiveMQTT() throws Exception {
   final CountDownLatch latch = new CountDownLatch(1);

   MqttClient consumer = createPahoClient("consumerId");
   MqttClient producer = createPahoClient("producerId");

   consumer.connect();
   consumer.subscribe("test");
   consumer.setCallback(new MqttCallback() {
      @Override
      public void connectionLost(Throwable cause) {

      }

      @Override
      public void messageArrived(String topic, MqttMessage message) throws Exception {
         latch.countDown();
      }

      @Override
      public void deliveryComplete(IMqttDeliveryToken token) {

      }
   });

   producer.connect();
   producer.publish("test", "hello".getBytes(), 1, false);

   waitForLatch(latch);
   producer.disconnect();
   producer.close();
}
 
Example 14
Source File: MqttListener.java    From diozero with MIT License 5 votes vote down vote up
public MqttListener() {
	try {
		mqttClient = new MqttClient(mqttServer, MqttClient.generateClientId(), new MemoryPersistence());
		mqttClient.setCallback(this);
		MqttConnectOptions con_opts = new MqttConnectOptions();
		con_opts.setCleanSession(true);
		mqttClient.connect(con_opts);
		System.out.println("Connected to '" + mqttServer + "'");
	} catch (MqttException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 15
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Attaches the callback used when configuration changes occur. */
protected static void attachCallback(MqttClient client, String deviceId)
    throws MqttException, UnsupportedEncodingException {
  mCallback =
      new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
          // Do nothing...
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) {
          try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8.name());
            System.out.println("Payload : " + payload);
            // TODO: Insert your parsing / handling of the configuration message here.
            //
          } catch (UnsupportedEncodingException uee) {
            System.err.println(uee);
          }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
          // Do nothing;
        }
      };

  String commandTopic = String.format("/devices/%s/commands/#", deviceId);
  System.out.println(String.format("Listening on %s", commandTopic));

  String configTopic = String.format("/devices/%s/config", deviceId);
  System.out.println(String.format("Listening on %s", configTopic));

  client.subscribe(configTopic, 1);
  client.subscribe(commandTopic, 1);
  client.setCallback(mCallback);
}
 
Example 16
Source File: TopicSubscriber.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("TopicSubscriber initializing...");

    String host = args[0];
    String username = args[1];
    String password = args[2];

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldSub");
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());
        
        // Connect the client
        System.out.println("Connecting to Solace messaging at "+host);
        mqttClient.connect(connOpts);
        System.out.println("Connected");

        // Latch used for synchronizing b/w threads
        final CountDownLatch latch = new CountDownLatch(1);
        
        // Topic filter the client will subscribe to
        final String subTopic = "T/GettingStarted/pubsub";
        
        // Callback - Anonymous inner-class for receiving messages
        mqttClient.setCallback(new MqttCallback() {

            public void messageArrived(String topic, MqttMessage message) throws Exception {
                // Called when a message arrives from the server that
                // matches any subscription made by the client
                String time = new Timestamp(System.currentTimeMillis()).toString();
                System.out.println("\nReceived a Message!" +
                        "\n\tTime:    " + time + 
                        "\n\tTopic:   " + topic + 
                        "\n\tMessage: " + new String(message.getPayload()) + 
                        "\n\tQoS:     " + message.getQos() + "\n");
                latch.countDown(); // unblock main thread
            }

            public void connectionLost(Throwable cause) {
                System.out.println("Connection to Solace messaging lost!" + cause.getMessage());
                latch.countDown();
            }

            public void deliveryComplete(IMqttDeliveryToken token) {
            }

        });
        
        // Subscribe client to the topic filter and a QoS level of 0
        System.out.println("Subscribing client to topic: " + subTopic);
        mqttClient.subscribe(subTopic, 0);
        System.out.println("Subscribed");

        // Wait for the message to be received
        try {
            latch.await(); // block here until message received, and latch will flip
        } catch (InterruptedException e) {
            System.out.println("I was awoken while waiting");
        }
        
        // Disconnect the client
        mqttClient.disconnect();
        System.out.println("Exiting");

        System.exit(0);
    } catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}
 
Example 17
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);
		
	}
 
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(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 19
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 20
Source File: Subscriber.java    From mqtt-sample-java with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws MqttException {

    System.out.println("== START SUBSCRIBER ==");

    MqttClient client=new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
    client.setCallback( new SimpleMqttCallBack() );
    client.connect();

    client.subscribe("iot_data");

  }