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

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttClient#publish() . 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: MQTTClient.java    From amazon-mq-workshop with Apache License 2.0 6 votes vote down vote up
private static void sendMessages(MqttClient client, MqttConnectOptions options, String destination, String name, int interval, WrapInt count) throws Exception {
    client.connect(options);
    System.out.println(String.format("Successfully connected to %s", client.getServerURI()));

    while (true) {
        count.v++;

        String message = String.format("[topic://%s] [%s] Message number %s", destination.replace('/', '.'), name, count.v);
        client.publish(destination, message.getBytes(StandardCharsets.UTF_8), 1, false);

        if (interval > 0) {
            System.out.println(String.format("%s - Sender: sent '%s'", df.format(new Date()), message));
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                System.out.println(String.format("Error: %s", e.getMessage()));
                System.exit(1);
            }
        }
    }
}
 
Example 2
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 3
Source File: Producer.java    From jmqtt with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws MqttException, InterruptedException {
    MqttClient pubClient = getMqttClient();
    for(int i = 0; i < 3; i++){
        MqttMessage mqttMessage = getMqttMessage();
        pubClient.publish(topic,mqttMessage);
        System.out.println("Send message success.");
    }
}
 
Example 4
Source File: MqttIndegoAdapter.java    From iot-device-bosch-indego-controller with Apache License 2.0 5 votes vote down vote up
/**
 * Publishes a single topic on the MQTT broker
 * 
 * @param mqttClient the broker connection
 * @param topic the topic to publish (relative to configured topic root)
 * @param data the data to publish
 * @param retained if the data should be retained
 * @throws MqttPersistenceException
 * @throws MqttException
 */
private void publish (MqttClient mqttClient, String topic, String data, boolean retained) throws MqttPersistenceException, MqttException
{
    if ( LOG.isDebugEnabled() ) {
        LOG.debug(String.format("Publishing '%s' to topic '%s' (retained = %s)", data, topic, retained));
    }

    MqttMessage msg = new MqttMessage(data.getBytes());
    msg.setQos(configuration.getMqttQos());
    msg.setRetained(retained);
    mqttClient.publish(configuration.getMqttTopicRoot() + topic, msg);
}
 
Example 5
Source File: MqttServerSslTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void connection(TestContext context) {

  this.async = context.async();

  try {

    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("ssl://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_TLS_PORT), "12345", persistence);

    MqttConnectOptions options = new MqttConnectOptions();
    options.setSocketFactory(this.getSocketFactory("/tls/client-truststore-root-ca.jks", null));
    client.connect(options);

    client.publish(MQTT_TOPIC, MQTT_MESSAGE.getBytes(), 0, false);

    this.async.await();

    client.disconnect();

    context.assertTrue(true);

  } catch (MqttException e) {
    e.printStackTrace();
    context.assertTrue(false);
  } catch (Exception e1) {
    e1.printStackTrace();
    context.assertTrue(false);
  }
}
 
Example 6
Source File: MqttCollectorTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void sendDecanterMessage() throws Exception {
    DispatcherMock dispatcherMock = new DispatcherMock();
    ComponentContext componentContext = new ComponentContextMock();
    componentContext.getProperties().put("server.uri", "tcp://localhost:11883");
    componentContext.getProperties().put("client.id", "decanter");
    componentContext.getProperties().put("topic", "decanter");
    JsonUnmarshaller unmarshaller = new JsonUnmarshaller();
    MqttCollector collector = new MqttCollector();
    collector.dispatcher = dispatcherMock;
    collector.unmarshaller = unmarshaller;
    collector.activate(componentContext);

    MqttClient mqttClient = new MqttClient("tcp://localhost:11883", "client");
    mqttClient.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload("{ \"foo\" : \"bar\" }".getBytes());
    mqttClient.publish("decanter", message);
    mqttClient.disconnect();

    Thread.sleep(200L);

    Assert.assertEquals(1, dispatcherMock.getPostEvents().size());
    Event event = dispatcherMock.getPostEvents().get(0);
    Assert.assertEquals("bar", event.getProperty("foo"));
    Assert.assertEquals("mqtt", event.getProperty("type"));
}
 
Example 7
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Detaches a bound device from the Gateway. */
protected static void detachDeviceFromGateway(MqttClient client, String deviceId)
    throws MqttException, UnsupportedEncodingException {
  // [START iot_detach_device]
  final String detachTopic = String.format("/devices/%s/detach", deviceId);
  System.out.println(String.format("Detaching: %s", detachTopic));
  String attachPayload = "{}";
  MqttMessage message = new MqttMessage(attachPayload.getBytes(StandardCharsets.UTF_8.name()));
  message.setQos(1);
  client.publish(detachTopic, message);
  // [END iot_detach_device]
}
 
Example 8
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
protected static void attachDeviceToGateway(MqttClient client, String deviceId)
    throws MqttException, UnsupportedEncodingException {
  // [START iot_attach_device]
  final String attachTopic = String.format("/devices/%s/attach", deviceId);
  System.out.println(String.format("Attaching: %s", attachTopic));
  String attachPayload = "{}";
  MqttMessage message = new MqttMessage(attachPayload.getBytes(StandardCharsets.UTF_8.name()));
  message.setQos(1);
  client.publish(attachTopic, message);
  // [END iot_attach_device]
}
 
Example 9
Source File: MqttCollectorTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void test() throws Exception {
    // install decanter
    System.out.println(executeCommand("feature:install decanter-collector-mqtt", new RolePrincipal("admin")));

    Thread.sleep(500);

    // create event handler
    List<Event> received = new ArrayList();
    EventHandler eventHandler = new EventHandler() {
        @Override
        public void handleEvent(Event event) {
            received.add(event);
        }
    };
    Hashtable serviceProperties = new Hashtable();
    serviceProperties.put(EventConstants.EVENT_TOPIC, "decanter/collect/*");
    bundleContext.registerService(EventHandler.class, eventHandler, serviceProperties);

    // send MQTT message
    MqttClient client = new MqttClient("tcp://localhost:1883", "d:decanter:collector:test");
    client.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload("This is a test".getBytes(StandardCharsets.UTF_8));
    client.publish("decanter", message);

    System.out.println("Waiting messages ...");
    while (received.size() == 0) {
        Thread.sleep(500);
    }

    Assert.assertEquals(1, received.size());

    Assert.assertEquals("decanter/collect/mqtt/decanter", received.get(0).getTopic());
    Assert.assertTrue(((String) received.get(0).getProperty("payload")).contains("This is a test"));
    Assert.assertEquals("root", received.get(0).getProperty("karafName"));
    Assert.assertEquals("mqtt", received.get(0).getProperty("type"));

}
 
Example 10
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 11
Source File: PahoMQTTQOS2SecurityTest.java    From activemq-artemis with Apache License 2.0 4 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");
   MqttConnectOptions conOpt = new MqttConnectOptions();
   conOpt.setCleanSession(true);
   conOpt.setUserName(user1);
   conOpt.setPassword(password1.toCharArray());
   consumer.connect(conOpt);
   consumer.subscribe(getQueueName(), 2);
   final boolean[] failed = new boolean[1];
   consumer.setCallback(new MqttCallback() {


      @Override
      public void connectionLost(Throwable cause) {
         cause.printStackTrace();
         failed[0] = true;
         latch.countDown();
      }

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

      @Override
      public void deliveryComplete(IMqttDeliveryToken token) {

      }
   });

   producer.connect(conOpt);
   producer.publish(getQueueName(), "hello".getBytes(), 2, false);

   waitForLatch(latch);
   producer.disconnect();
   producer.close();
   Assert.assertFalse(failed[0]);
}
 
Example 12
Source File: DeviceTypeManagementJMeterTestCase.java    From product-iots with Apache License 2.0 4 votes vote down vote up
@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods =
        {"DeviceTypeManagementTest"} )
public void testMqttFlow() throws Exception {
    String deviceId = "123422578912";
    String deviceType = "firealarmmqtt";
    String payload = "{\"deviceIdentifiers\":[123422578912],\"operation\":{\"code\":\"ring\",\"type\":\"CONFIG\"," +
            "\"payLoad\":\"volume:30%\"}}";
    String topic = automationContext.getContextTenant().getDomain() + "/"+deviceType+"/" + deviceId + "/operation/#";
    String clientId = deviceId + ":firealarmmqtt";
    MqttSubscriberClient mqttDeviceSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken);
    restClient.post("/api/device-mgt/v1.0/devices/" + deviceType + "/operations", payload);

    // Allow some time for message delivery
    Thread.sleep(10000);
    ArrayList<MqttMessage> mqttMessages = mqttDeviceSubscriberClient.getMqttMessages();
    Assert.assertEquals("listener did not received mqtt messages ", 1, mqttMessages.size());

    String topicPub = automationContext.getContextTenant().getDomain() + "/"+deviceType+"/"+deviceId+"/events";
    int qos = 2;
    String clientIdPub = deviceId + ":firealarmmqttpub";
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientIdPub, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(false);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    for (int i = 0; i < 100; i++) {
        payload = "{\"temperature\":%d,\"status\":\"workingh\",\"humidity\":20}";
        MqttMessage message = new MqttMessage(String.format(payload, i).getBytes());
        message.setQos(qos);
        sampleClient.publish(topicPub, message);
        log.info("Message is published to Mqtt Client");
        Thread.sleep(1000);
    }
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    // Allow some time for message delivery
    HttpResponse response = restClient.get("/api/device-mgt/v1.0/events/last-known/" + deviceType + "/" + deviceId);
    Assert.assertEquals("No published event found (mqtt)", HttpStatus.SC_OK,
                        response.getResponseCode());
    log.error(response.getData());
    JsonElement jsonElement = new JsonParser().parse(response.getData()).getAsJsonObject().get("count");
    int count = jsonElement.getAsInt();
    Assert.assertTrue("Event count does not match published event count, " + response.getData(),
                      count > 0);

}
 
Example 13
Source File: AndroidSenseEnrollment.java    From product-iots with Apache License 2.0 4 votes vote down vote up
@Test(description = "Test an Android sense device data publishing.", dependsOnMethods = {"testEnrollment"})
    public void testEventPublishing() throws Exception {
        String DEVICE_TYPE = "android_sense";
        String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + DEVICE_ID + "/data";
        int qos = 2;
        String broker = "tcp://localhost:1886";
        String clientId = DEVICE_ID + ":" + DEVICE_TYPE;
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName(accessToken);
        connOpts.setPassword("".toCharArray());
        connOpts.setKeepAliveInterval(120);
        connOpts.setCleanSession(true);
        log.info("Connecting to broker: " + broker);
        sampleClient.connect(connOpts);
        log.info("Connected");
        MqttMessage message = new MqttMessage(PayloadGenerator
                .getJsonArray(Constants.AndroidSenseEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME,
                        Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION).toString().getBytes());
        message.setQos(qos);
        for (int i = 0; i< 100 ; i++) {
            sampleClient.publish(topic, message);
            log.info("Message is published to Mqtt Client");
            Thread.sleep(1000);
        }
        sampleClient.disconnect();

        HttpResponse response = analyticsClient
                .get(Constants.AndroidSenseEnrollment.IS_TABLE_EXIST_CHECK_URL + "?table="
                        + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME);
        Assert.assertEquals("ORG_WSO2_IOT_ANDROID_BATTERY_STATS table does not exist. Problem with the android sense "
                                    + "analytics", HttpStatus.SC_OK, response.getResponseCode());
        // Allow some time to perform the analytics tasks.

        log.info("Mqtt Client is Disconnected");

        String url = Constants.AndroidSenseEnrollment.RETRIEVER_ENDPOINT
                + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME + "/";
        Timestamp timestamp = new Timestamp(System.currentTimeMillis() - 3600000);
        url += timestamp.getTime() + "/" + new Timestamp(System.currentTimeMillis()).getTime() + "/0/100";
        response = analyticsClient.get(url);
        JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonArray();
        //TODO: temporarily commenting out untill new changes are merged
//        Assert.assertEquals(
//                "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
//                HttpStatus.SC_OK, response.getResponseCode());
//        Assert.assertTrue(
//                "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
//                jsonArray.size() > 0);
    }
 
Example 14
Source File: CloudiotPubsubExampleMqttDevice.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Entry point for CLI. */
public static void main(String[] args) throws Exception {
  CloudiotPubsubExampleMqttDeviceOptions options =
      CloudiotPubsubExampleMqttDeviceOptions.fromFlags(args);
  if (options == null) {
    System.exit(1);
  }
  final Device device = new Device(options);
  final String mqttTelemetryTopic = String.format("/devices/%s/events", options.deviceId);
  // This is the topic that the device will receive configuration updates on.
  final String mqttConfigTopic = String.format("/devices/%s/config", options.deviceId);

  final String mqttServerAddress =
      String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);
  final String mqttClientId =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          options.projectId, options.cloudRegion, options.registryId, options.deviceId);
  MqttConnectOptions connectOptions = new MqttConnectOptions();
  connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

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

  connectOptions.setUserName("unused");
  if (options.algorithm.equals("RS256")) {
    System.out.println(options.privateKeyFile);

    connectOptions.setPassword(
        createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
    System.out.println(
        String.format(
            "Creating JWT using RS256 from private key file %s", options.privateKeyFile));
  } else if (options.algorithm.equals("ES256")) {
    connectOptions.setPassword(
        createJwtEs(options.projectId, options.privateKeyFile).toCharArray());
  } else {
    throw new IllegalArgumentException(
        "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
  }

  device.isConnected = true;

  MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());

  try {
    client.setCallback(device);
    client.connect(connectOptions);
  } catch (MqttException e) {
    e.printStackTrace();
  }

  // wait for it to connect
  device.waitForConnection(5);

  client.subscribe(mqttConfigTopic, 1);

  for (int i = 0; i < options.numMessages; i++) {
    device.updateSensorData();

    JSONObject payload = new JSONObject();
    payload.put("temperature", device.temperature);
    System.out.println("Publishing payload " + payload.toString());
    MqttMessage message = new MqttMessage(payload.toString().getBytes());
    message.setQos(1);
    client.publish(mqttTelemetryTopic, message);
    Thread.sleep(1000);
  }
  client.disconnect();

  System.out.println("Finished looping successfully : " + options.mqttBridgeHostname);
}
 
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(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 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: TopicPublisher.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("TopicPublisher initializing...");

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

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldPub");
        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");

        // Create a Mqtt message
        String content = "Hello world from MQTT!";
        MqttMessage message = new MqttMessage(content.getBytes());
        // Set the QoS on the Messages - 
        // Here we are using QoS of 0 (equivalent to Direct Messaging in Solace)
        message.setQos(0);
        
        System.out.println("Publishing message: " + content);
        
        // Publish the message
        mqttClient.publish("T/GettingStarted/pubsub", message);
        
        // Disconnect the client
        mqttClient.disconnect();
        
        System.out.println("Message published. 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 18
Source File: QoS1Producer.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("QoS1Producer initializing...");

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

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldQoS1Producer");
        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");

        // Create a Mqtt message
        String content = "Hello world from MQTT!";
        MqttMessage message = new MqttMessage(content.getBytes());
        // Set the QoS on the Messages - 
        // Here we are using QoS of 1 (equivalent to Persistent Messages in Solace)
        message.setQos(1);

        System.out.println("Publishing message: " + content);

        // Publish the message
        mqttClient.publish("Q/tutorial", message);

        // Disconnect the client
        mqttClient.disconnect();

        System.out.println("Message published. 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 19
Source File: MqttServerClientPublishTest.java    From vertx-mqtt with Apache License 2.0 4 votes vote down vote up
private void publish(TestContext context, String topic, String message, int qos) {

    this.async = 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();

      client.publish(topic, message.getBytes(), qos, false);

      this.async.await();

      context.assertTrue(true);

    } catch (MqttException e) {

      context.assertTrue(false);
      e.printStackTrace();
    }
  }
 
Example 20
Source File: Publisher.java    From mqtt-sample-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MqttException {

    String messageString = "Hello World from Java!";

    if (args.length == 2 ) {
      messageString = args[1];
    }


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


    MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
    client.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload(messageString.getBytes());
    client.publish("iot_data", message);

    System.out.println("\tMessage '"+ messageString +"' to 'iot_data'");

    client.disconnect();

    System.out.println("== END PUBLISHER ==");

  }