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

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttClient#subscribe() . 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: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized void subscribeToCustomTopic(String customTopic, boolean useEncrypted) {
    try {
        String userKeyString = MobiComUserPreference.getInstance(context).getSuUserKeyString();
        if (TextUtils.isEmpty(userKeyString)) {
            return;
        }
        final MqttClient client = connect();
        if (client != null && client.isConnected()) {
            String topic = (useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + SUPPORT_GROUP_TOPIC + getApplicationKey(context);
            Utils.printLog(context, TAG, "Subscribing to support group topic : " + topic);
            client.subscribe(topic, 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 2
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 3
Source File: ProtobufMqttProtocolHandler.java    From diozero with MIT License 6 votes vote down vote up
public ProtobufMqttProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
	super(deviceFactory);

	String mqtt_url = PropertyUtil.getProperty(MQTT_URL_PROP, null);
	if (mqtt_url == null) {
		throw new RuntimeIOException("Property '" + MQTT_URL_PROP + "' must be set");
	}

	try {
		mqttClient = new MqttClient(mqtt_url, MqttClient.generateClientId(), new MemoryPersistence());
		mqttClient.setCallback(this);
		MqttConnectOptions con_opts = new MqttConnectOptions();
		con_opts.setAutomaticReconnect(true);
		con_opts.setCleanSession(true);
		mqttClient.connect(con_opts);
		Logger.debug("Connected to {}", mqtt_url);

		// Subscribe
		Logger.debug("Subscribing to response and notification topics...");
		mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
		mqttClient.subscribe(MqttProviderConstants.GPIO_NOTIFICATION_TOPIC);
		Logger.debug("Subscribed");
	} catch (MqttException e) {
		throw new RuntimeIOException(e);
	}
}
 
Example 4
Source File: MqttTestClient.java    From diozero with MIT License 6 votes vote down vote up
public MqttTestClient(String mqttUrl) throws MqttException {
	mqttClient = new MqttClient(mqttUrl, MqttClient.generateClientId(), new MemoryPersistence());
	mqttClient.setCallback(this);
	MqttConnectOptions con_opts = new MqttConnectOptions();
	con_opts.setAutomaticReconnect(true);
	con_opts.setCleanSession(true);
	mqttClient.connect(con_opts);
	Logger.debug("Connected to {}", mqttUrl);

	lock = new ReentrantLock();
	conditions = new HashMap<>();
	responses = new HashMap<>();

	// Subscribe
	Logger.debug("Subscribing to {}...", MqttProviderConstants.RESPONSE_TOPIC);
	mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
	Logger.debug("Subscribed");
}
 
Example 5
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized void subscribeToSupportGroup(boolean useEncrypted) {
    try {
        String userKeyString = MobiComUserPreference.getInstance(context).getSuUserKeyString();
        if (TextUtils.isEmpty(userKeyString)) {
            return;
        }
        final MqttClient client = connect();
        if (client != null && client.isConnected()) {
            String topic = (useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + SUPPORT_GROUP_TOPIC + getApplicationKey(context);
            Utils.printLog(context, TAG, "Subscribing to support group topic : " + topic);
            client.subscribe(topic, 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
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 7
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized void subscribeToTypingTopic(Channel channel) {
    try {
        String currentId = null;
        if (channel != null) {
            currentId = String.valueOf(channel.getKey());
        } else {
            MobiComUserPreference mobiComUserPreference = MobiComUserPreference.getInstance(context);
            currentId = mobiComUserPreference.getUserId();
        }

        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }

        client.subscribe("typing-" + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId), 0);
        Utils.printLog(context, TAG, "Subscribed to topic: " + "typing-" + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: MqttServerUnsubscribeTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void unsubscribe(TestContext context) {

  this.subscribeAsync = context.async();
  this.unsubscribeAsync = context.async();

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();

    String[] topics = new String[]{MQTT_TOPIC};
    int[] qos = new int[]{0};
    client.subscribe(topics, qos);

    this.subscribeAsync.await();

    client.unsubscribe(topics);

    this.unsubscribeAsync.await();

    context.assertTrue(true);

  } catch (MqttException e) {

    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
Source File: EngineTemperatureSensorLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenSendMultipleMessages_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);
    

    publisher.connect(options);        
    subscriber.connect(options);
    
    CountDownLatch receivedSignal = new CountDownLatch(10);
    
    subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> {
        byte[] payload = msg.getPayload();
        log.info("[I82] Message received: topic={}, payload={}", topic, new String(payload));
        receivedSignal.countDown();
    });
    
    
    Callable<Void> target = new EngineTemperatureSensor(publisher);
    
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(() -> {
          try {
              target.call();
          }
          catch(Exception ex) {
              throw new RuntimeException(ex);
          }
      }, 1, 1, TimeUnit.SECONDS);
    

    receivedSignal.await(1, TimeUnit.MINUTES);
    executor.shutdown();
    
    assertTrue(receivedSignal.getCount() == 0 , "Countdown should be zero");

    log.info("[I105] Success !");
}
 
Example 18
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Connects the gateway to the MQTT bridge. */
protected static MqttClient startMqtt(
    String mqttBridgeHostname,
    int mqttBridgePort,
    String projectId,
    String cloudRegion,
    String registryId,
    String gatewayId,
    String privateKeyFile,
    String algorithm)
    throws NoSuchAlgorithmException, IOException, MqttException, InterruptedException,
        InvalidKeySpecException {
  // [START iot_gateway_start_mqtt]

  // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
  // connections are accepted. For server authentication, the JVM's root certificates
  // are used.
  final String mqttServerAddress =
      String.format("ssl://%s:%s", mqttBridgeHostname, mqttBridgePort);

  // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
  // Google Cloud IoT Core, it must be in the format below.
  final String mqttClientId =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, gatewayId);

  MqttConnectOptions connectOptions = new MqttConnectOptions();
  // Note that the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
  // explictly set this. If you don't set MQTT version, the server will immediately close its
  // connection to your device.
  connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

  Properties sslProps = new Properties();
  sslProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
  connectOptions.setSSLProperties(sslProps);

  // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
  // Paho client library to send the password field. The password field is used to transmit a JWT
  // to authorize the device.
  connectOptions.setUserName("unused");

  if ("RS256".equals(algorithm)) {
    connectOptions.setPassword(createJwtRsa(projectId, privateKeyFile).toCharArray());
  } else if ("ES256".equals(algorithm)) {
    connectOptions.setPassword(createJwtEs(projectId, privateKeyFile).toCharArray());
  } else {
    throw new IllegalArgumentException(
        "Invalid algorithm " + algorithm + ". Should be one of 'RS256' or 'ES256'.");
  }

  System.out.println(String.format("%s", mqttClientId));

  // Create a client, and connect to the Google MQTT bridge.
  MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());

  // Both connect and publish operations may fail. If they do, allow retries but with an
  // exponential backoff time period.
  long initialConnectIntervalMillis = 500L;
  long maxConnectIntervalMillis = 6000L;
  long maxConnectRetryTimeElapsedMillis = 900000L;
  float intervalMultiplier = 1.5f;

  long retryIntervalMs = initialConnectIntervalMillis;
  long totalRetryTimeMs = 0;

  while ((totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) && !client.isConnected()) {
    try {
      client.connect(connectOptions);
    } catch (MqttException e) {
      int reason = e.getReasonCode();

      // If the connection is lost or if the server cannot be connected, allow retries, but with
      // exponential backoff.
      System.out.println("An error occurred: " + e.getMessage());
      if (reason == MqttException.REASON_CODE_CONNECTION_LOST
          || reason == MqttException.REASON_CODE_SERVER_CONNECT_ERROR) {
        System.out.println("Retrying in " + retryIntervalMs / 1000.0 + " seconds.");
        Thread.sleep(retryIntervalMs);
        totalRetryTimeMs += retryIntervalMs;
        retryIntervalMs *= intervalMultiplier;
        if (retryIntervalMs > maxConnectIntervalMillis) {
          retryIntervalMs = maxConnectIntervalMillis;
        }
      } else {
        throw e;
      }
    }
  }

  attachCallback(client, gatewayId);

  // The topic gateways receive error updates on. QoS must be 0.
  String errorTopic = String.format("/devices/%s/errors", gatewayId);
  System.out.println(String.format("Listening on %s", errorTopic));

  client.subscribe(errorTopic, 0);

  return client;
  // [END iot_gateway_start_mqtt]
}
 
Example 19
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 !");
}
 
Example 20
Source File: MqttSubscriber.java    From quarks with Apache License 2.0 2 votes vote down vote up
/**
 * To be called on initial connection and reconnects
 * @param client the MqttClient
 * @throws MqttException
 */
void connected(MqttClient client) throws MqttException {
    logger.info("{} subscribe({}, {})", id(), topicFilter, qos);
    client.subscribe(topicFilter, qos);
}