Java 类org.eclipse.paho.client.mqttv3.MqttTopic 实例源码

项目:EMQ-Android-Toolkit    文件:SubscriptionActivity.java   
@OnClick(R.id.btn_subscribe)
public void onViewClicked() {
    String topic = mTopic.getText().toString().trim();
    try {
        MqttTopic.validate(topic, true/*allow wildcards*/);
    } catch (IllegalArgumentException e) {
        TipUtil.showSnackbar(mLinearLayout, e.getMessage());
        return;
    }

    int qos = mQoSLayout.getQoS();

    Subscription subscription = new Subscription(topic, qos);

    Intent intent = new Intent();
    intent.putExtra(Constant.ExtraConstant.EXTRA_SUBSCRIPTION, subscription);
    setResult(RESULT_OK, intent);
    finish();

}
项目:EMQ-Android-Toolkit    文件:PublicationActivity.java   
@OnClick(R.id.btn_publish)
public void onViewClicked() {
    String topic = mTopic.getText().toString().trim();

    try{
        MqttTopic.validate(topic, false/*wildcards NOT allowed*/);
    }catch (IllegalArgumentException e){
        TipUtil.showSnackbar(mLinearLayout, e.getMessage());
        return;
    }
    int qos = mQoSChooseLayout.getQoS();
    String payload = mPayload.getText().toString().trim();
    boolean isRetained = mRetainedSwitch.isChecked();

    Publication publication = new Publication(topic, payload, qos, isRetained);

    Intent intent = new Intent();
    intent.putExtra(Constant.ExtraConstant.EXTRA_PUBLICATION, publication);
    setResult(RESULT_OK, intent);
    finish();
}
项目:hestia-engine-dev    文件:MqttTopicTest.java   
@Test
public void testValidTopicFilterWildcards() throws Exception {
  String methodName = Utility.getMethodName();
  LoggingUtilities.banner(log, cclass, methodName);
  String[] topics = new String[] { 
          "+", "+/+", "+/foo", 
          "+/tennis/#",
          "foo/+", "foo/+/bar", 
          "/+", "/+/sport/+/player1",
          "#", "/#",
          "sport/#",
          "sport/tennis/#"
   };

  for(String topic:topics){
      MqttTopic.validate(topic, true);
  }
}
项目:hestia-engine-dev    文件:LiveTakeOverTest.java   
void repeatedlyPub() {
  String methodName = Utility.getMethodName();

  int i = 0;
  while (mqttClient.isConnected()) {
    try {
      if (i > 999999) {
        i = 0;
      }
      byte[] payload = ("Message payload " + getClass().getName() + ".publish" + (i++)).getBytes();
      MqttTopic mqttTopic = mqttClient.getTopic(FirstSubTopicString);
      log.info("Publishing to..." + FirstSubTopicString);
      mqttTopic.publish(payload, 1, false);

    }
    catch (Exception exception) {
      log.fine("Caught exception:" + exception);
      // Don't fail - we are going to get an exception as we disconnected during takeOver
      // Its likely the publish rate is too high i.e. inflight window is full
    }
  }
}
项目:EMQ-Android-Toolkit    文件:DashboardActivity.java   
@Override
public void onAddSubscription(Subscription subscription) {
    try {
        MqttTopic.validate(subscription.getTopic(),true);
    }catch (IllegalArgumentException e){
        TipUtil.showSnackbar(mCoordinatorLayout,e.getMessage());
        return;
    }
    subscription.setConnectionId(mConnection.getId());
    mSubscription = subscription;
    RealmHelper.getInstance().addSubscription(mSubscription);
    subscribe(subscription);
}
项目:mqttserver    文件:PubWebMessage.java   
public static void pubMsg(String tcpUrl, String clientId, String topicName,
            String message) throws MqttException, UnsupportedEncodingException {
        MqttClient client = new MqttClient(tcpUrl, clientId);
        MqttConnectOptions mqcConf = new MqttConnectOptions();
        mqcConf.setConnectionTimeout(300);
        mqcConf.setKeepAliveInterval(1200);
        client.connect(mqcConf);

        MqttTopic topic = client.getTopic(topicName);
        topic.publish(message.getBytes("utf8"), 1, false);

//      client.close();
    }
项目:mqttserver    文件:PubMessage.java   
public static void pubMsg(String tcpUrl, String clientId, String topicName)
    throws MqttException, UnsupportedEncodingException {
  MqttClient client = new MqttClient(tcpUrl, clientId);
  MqttConnectOptions mqcConf = new MqttConnectOptions();
  mqcConf.setConnectionTimeout(300);
  mqcConf.setKeepAliveInterval(1200);
  client.connect(mqcConf);

  MqttTopic topic = client.getTopic(topicName);
  for (int i = 0; i < 10; i++) {
    String message = "{\"id\":" + (i+1) + ",\"temp\":12}";
    topic.publish(message.getBytes("utf8"), 1, false);
  }
  client.disconnect();
}
项目:EndUserInteractioion_RequestResponse_Command    文件:MQTTPublisher.java   
public void publish(String topicName, int qos, byte[] payload)
        throws MqttException {
    final MqttTopic topic = client.getTopic(topicName);

    final MqttMessage message = new MqttMessage(payload);
    topic.publish(message);

    System.out.println("Published data. Topic: " + topic.getName()
            + "  Message: " + payload);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:MQTTPublisher.java   
public void publish(String topicName, int qos, byte[] payload)
        throws MqttException {
    final MqttTopic topic = client.getTopic(topicName);

    final MqttMessage message = new MqttMessage(payload);
    topic.publish(message);

    System.out.println("Published data. Topic: " + topic.getName()
            + "  Message: " + payload);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:MQTTPublisher.java   
public void publish(String topicName, int qos, byte[] payload)
        throws MqttException {
    final MqttTopic topic = client.getTopic(topicName);

    final MqttMessage message = new MqttMessage(payload);
    topic.publish(message);

    System.out.println("Published data. Topic: " + topic.getName()
            + "  Message: " + payload);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:MQTTPublisher.java   
public void publish(String topicName, int qos, byte[] payload)
        throws MqttException {
    final MqttTopic topic = client.getTopic(topicName);

    final MqttMessage message = new MqttMessage(payload);
    topic.publish(message);

    System.out.println("Published data. Topic: " + topic.getName()
            + "  Message: " + payload);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:MQTTPublisher.java   
public void publish(String topicName, int qos, byte[] payload)
        throws MqttException {
    final MqttTopic topic = client.getTopic(topicName);

    final MqttMessage message = new MqttMessage(payload);
    topic.publish(message);

    System.out.println("Published data. Topic: " + topic.getName()
            + "  Message: " + payload);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:MQTTPublisher.java   
public void publish(String topicName, int qos, byte[] payload)
        throws MqttException {
    final MqttTopic topic = client.getTopic(topicName);

    final MqttMessage message = new MqttMessage(payload);
    topic.publish(message);

    System.out.println("Published data. Topic: " + topic.getName()
            + "  Message: " + payload);
}
项目:cf-service-tester    文件:MqttTestMessagePublisher.java   
@Override
public void publish() {
    if(mqttClient == null || !mqttClient.isConnected()) {
        log.debug("MQTT client unavailable");
        stateService.setRabbitDown();
        return;
    }

    Date now = new Date();
    String messageId = getMessageId();
    String messagePayload = getMessageBody(messageId, now);

    try {

        MqttTopic topic = mqttClient.getTopic(rabbitQueueName);
        MqttMessage mqttMessage = new MqttMessage(messagePayload.getBytes());
        mqttMessage.setQos(mqttQos);
        MqttDeliveryToken token = topic.publish(mqttMessage);
        if(mqttQos > 0) {
            token.waitForCompletion();
        }

        log.info("{} [{}] {}", instanceName, 
                messageId, messagePayload);

        stateService.setRabbitUp();

    }
    catch(MqttException ex) {
        log.warn("({}) Publish of MQTT message [{}] to RabbitMQ has failed",
                utils.getPublishedKey(consistencyChecker.getIndex()), messageId);

        if( ex.getReasonCode() == 32109 ) {
            log.warn("Connection lost (unsupported QoS mode?)");
        }

        stateService.setRabbitDown();
    }

}
项目:NodeMCU-Energy-Monitor    文件:MQTTClient.java   
public void sendMessageToSensor(String data) {

        if(!isConnected()){
            System.out.println("Not connected, aborting");
            return;
        }

        // setup topic
        MqttTopic topic = mClient.getTopic(sharedPref.getString("pref_sensor", ""));

        int pubQoS = 2;
        MqttMessage message = new MqttMessage(data.getBytes());
        message.setQos(pubQoS);
        message.setRetained(false);

        // Publish the message
        System.out.println("Publishing to topic \"" + topic + "\" qos " + pubQoS + " with message " + message.toString());
        MqttDeliveryToken token = null;
        try {
            // publish message to broker
            token = topic.publish(message);
            // Wait until the message has been delivered to the broker
            token.waitForCompletion();
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
项目:IoTSuite    文件:MQTTPublisher.java   
public void publish(String topicName, int qos, byte[] payload)
        throws MqttException {
    final MqttTopic topic = client.getTopic(topicName);

    final MqttMessage message = new MqttMessage(payload);
    topic.publish(message);

    System.out.println("Published data. Topic: "
            + topic.getName() + "  Message: " + payload);
}
项目:android-mqtt    文件:MqttService.java   
/**
 * Received Message from broker
 */
@Override
public void messageArrived(MqttTopic topic, MqttMessage message)
throws Exception {
        Log.i(DEBUG_TAG,"  Topic:\t" + topic.getName() +
              "  Message:\t" + new String(message.getPayload()) +
              "  QoS:\t" + message.getQos());
}
项目:openhab1-addons    文件:MqttBrokerConnection.java   
/**
 * Start a registered producer, so that it can start sending messages.
 * 
 * @param publisher
 *            to start.
 */
private void startProducer(MqttMessageProducer publisher) {

    logger.trace("Starting message producer for broker '{}'", name);

    publisher.setSenderChannel(new MqttSenderChannel() {

        @Override
        public void publish(String topic, byte[] payload) throws Exception {

            if (!started) {
                logger.warn("Broker connection not started. Cannot publish message to topic '{}'", topic);
                return;
            }

            // Create and configure a message
            MqttMessage message = new MqttMessage(payload);
            message.setQos(qos);
            message.setRetained(retain);

            // publish message asynchronously
            MqttTopic mqttTopic = client.getTopic(topic);
            MqttDeliveryToken deliveryToken = mqttTopic.publish(message);

            logger.debug("Publishing message {} to topic '{}'", deliveryToken.getMessageId(), topic);
            if (!async) {
                // wait for publish confirmation
                deliveryToken.waitForCompletion(10000);
                if (!deliveryToken.isComplete()) {
                    logger.error(
                            "Did not receive completion message within timeout limit whilst publishing to topic '{}'",
                            topic);
                }
            }

        }
    });

}
项目:vaadin.m2m    文件:SubscribeCallback.java   
@Override
public void messageArrived(MqttTopic topic, MqttMessage message) throws Exception {

    System.out.println("Message arrived. Topic: " + topic.getName() + "  Message: " + message.toString());

    if(field != null)
        field.setValue(new String(message.getPayload()));
}
项目:EndUserInteractioion_RequestResponse_Command    文件:PushCallback.java   
@Override
public void messageArrived(MqttTopic topic, MqttMessage message)
        throws Exception {

    pubsub.receiveEvent(topic.toString(), message);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:PushCallback.java   
@Override
public void messageArrived(MqttTopic topic, MqttMessage message)
        throws Exception {

    pubsub.receiveEvent(topic.toString(), message);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:PushCallback.java   
@Override
public void messageArrived(MqttTopic topic, MqttMessage message)
        throws Exception {

    pubsub.receiveEvent(topic.toString(), message);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:PushCallback.java   
@Override
public void messageArrived(MqttTopic topic, MqttMessage message)
        throws Exception {

    pubsub.receiveEvent(topic.toString(), message);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:PushCallback.java   
@Override
public void messageArrived(MqttTopic topic, MqttMessage message)
        throws Exception {

    pubsub.receiveEvent(topic.toString(), message);
}
项目:EndUserInteractioion_RequestResponse_Command    文件:PushCallback.java   
@Override
public void messageArrived(MqttTopic topic, MqttMessage message)
        throws Exception {

    pubsub.receiveEvent(topic.toString(), message);
}
项目:openhab-hdl    文件:MqttBrokerConnection.java   
/**
 * Start a registered producer, so that it can start sending messages.
 * 
 * @param publisher
 *            to start.
 */
private void startProducer(MqttMessageProducer publisher) {

    logger.trace("Starting message producer for broker '{}'", name);

    publisher.setSenderChannel(new MqttSenderChannel() {

        @Override
        public void publish(String topic, byte[] payload) throws Exception {

            if (!started) {
                logger.warn(
                        "Broker connection not started. Cannot publish message to topic '{}'",
                        topic);
                return;
            }

            // Create and configure a message
            MqttMessage message = new MqttMessage(payload);
            message.setQos(qos);
            message.setRetained(retain);

            // publish message asynchronously
            MqttTopic mqttTopic = client.getTopic(topic);
            MqttDeliveryToken deliveryToken = mqttTopic.publish(message);

            logger.debug("Publishing message {} to topic '{}'",
                    deliveryToken.getMessageId(), topic);
            if (!async) {
                // wait for publish confirmation
                deliveryToken.waitForCompletion(10000);
                if (!deliveryToken.isComplete()) {
                    logger.error(
                            "Did not receive completion message within timeout limit whilst publishing to topic '{}'",
                            topic);
                }
            }

        }
    });

}
项目:IoTSuite    文件:PushCallback.java   
@Override
  public void messageArrived(MqttTopic topic, MqttMessage message) throws Exception {

pubsub.receiveEvent(topic.toString(), message);
  }
项目:mqtt-client-android-graphdemo    文件:ZADataGraphDemoActivity.java   
@Override
public void messageArrived(MqttTopic arg0, MqttMessage arg1)
        throws Exception {
    //Log.i("GRAPH", "Got value " + arg1.toString());
    updateText(arg1.toString());
}
项目:LGTV2MQTT    文件:Status.java   
public Status(MqttTopic topic, TVSerialInterface serialInterface, TVState state) {
    this.topic = topic;
    this.serialInterface = serialInterface;
    this.state = state;
}
项目:hestia-engine-dev    文件:BasicTest.java   
/**
 * @throws Exception 
 */
@Test
public void testPubSub() throws Exception {
  String methodName = Utility.getMethodName();
  LoggingUtilities.banner(log, cclass, methodName);

  IMqttClient client = null;
  try {
    String topicStr = "topic" + "_02";
    String clientId = methodName;
    client = clientFactory.createMqttClient(serverURI, clientId);

    log.info("Assigning callback...");
    MessageListener listener = new MessageListener();
    client.setCallback(listener);

    log.info("Connecting...(serverURI:" + serverURI + ", ClientId:" + clientId);
    client.connect();

    log.info("Subscribing to..." + topicStr);
    client.subscribe(topicStr);

    log.info("Publishing to..." + topicStr);
    MqttTopic topic = client.getTopic(topicStr);
    MqttMessage message = new MqttMessage("foo".getBytes());
    topic.publish(message);

    log.info("Checking msg");
    MqttMessage msg = listener.getNextMessage();
    Assert.assertNotNull(msg);
    Assert.assertEquals("foo", msg.toString());

    log.info("getTopic name");
    String topicName = topic.getName();
    log.info("topicName = " + topicName);
    Assert.assertEquals(topicName, topicStr);

    log.info("Disconnecting...");
    client.disconnect();
  }
  finally {
    if (client != null) {
      log.info("Close...");
      client.close();
    }
  }
}
项目:hestia-engine-dev    文件:MqttTopicTest.java   
@Test(expected = IllegalArgumentException.class)
public void testInvalidTopicFilterWildcards1() throws Exception {
  String methodName = Utility.getMethodName();
  LoggingUtilities.banner(log, cclass, methodName);
  MqttTopic.validate("sport/tennis#", true);
}
项目:hestia-engine-dev    文件:MqttTopicTest.java   
@Test(expected = IllegalArgumentException.class)
public void testInvalidTopicFilterWildcards2() throws Exception {
  String methodName = Utility.getMethodName();
  LoggingUtilities.banner(log, cclass, methodName);
  MqttTopic.validate("sport/tennis/#/ranking", true);
}
项目:hestia-engine-dev    文件:MqttTopicTest.java   
@Test(expected = IllegalArgumentException.class)
public void testInvalidTopicFilterWildcards3() throws Exception {
  String methodName = Utility.getMethodName();
  LoggingUtilities.banner(log, cclass, methodName);
  MqttTopic.validate("sport+", true);
}
项目:hestia-engine-dev    文件:MqttTopicTest.java   
@Test(expected = IllegalArgumentException.class)
public void testInvalidTopicFilterWildcards4() throws Exception {
  String methodName = Utility.getMethodName();
  LoggingUtilities.banner(log, cclass, methodName);
  MqttTopic.validate("sport/+aa", true);
}
项目:hestia-engine-dev    文件:MqttTopicTest.java   
@Test(expected = IllegalArgumentException.class)
public void testInvalidTopicFilterWildcards5() throws Exception {
  String methodName = Utility.getMethodName();
  LoggingUtilities.banner(log, cclass, methodName);
  MqttTopic.validate("sport/#/ball/+/aa", true);
}
项目:hestia-engine-dev    文件:SendReceiveTest.java   
/**
 * Test connection using a remote host name for the local host.
 * @throws Exception 
 */
@Test
public void testRemoteConnect() throws Exception {
  final String methodName = Utility.getMethodName();
  LoggingUtilities.banner(log, cclass, methodName);
  log.entering(className, methodName);

  IMqttClient mqttClient = null;
  try {
    mqttClient = clientFactory.createMqttClient(serverURI, methodName);
    log.info("Connecting...(serverURI:" + serverURI + ", ClientId:" + methodName);
    mqttClient.connect();
    log.info("Disconnecting...");
    mqttClient.disconnect();

    MqttV3Receiver mqttV3Receiver = new MqttV3Receiver(mqttClient, LoggingUtilities.getPrintStream());
    log.info("Assigning callback...");
    mqttClient.setCallback(mqttV3Receiver);
    MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
    mqttConnectOptions.setCleanSession(false);
    log.info("Connecting...(serverURI:" + serverURI + ", ClientId:" + methodName + ", cleanSession: false");
    mqttClient.connect(mqttConnectOptions);

    String[] topicNames = new String[]{methodName + "/Topic"};
    int[] topicQos = {0};
    log.info("Subscribing to..." + topicNames[0]);
    mqttClient.subscribe(topicNames, topicQos);

    byte[] payload = ("Message payload " + className + "." + methodName).getBytes();
    MqttTopic mqttTopic = mqttClient.getTopic(topicNames[0]);
    log.info("Publishing to..." + topicNames[0]);
    mqttTopic.publish(payload, 1, false);
    boolean ok = mqttV3Receiver.validateReceipt(topicNames[0], 0, payload);
    if (!ok) {
      Assert.fail("Receive failed");
    }
    log.info("Disconnecting...");
    mqttClient.disconnect();
  }
  catch (Exception exception) {
    log.log(Level.SEVERE, "caught exception:", exception);
    Assert.fail("Failed:" + methodName + " exception=" + exception);
  }
  finally {
    if (mqttClient != null) {
    log.info("Close...");
      mqttClient.close();
    }
  }

  log.exiting(className, methodName);
}
项目:hestia-engine-dev    文件:ClientComms.java   
protected MqttTopic getTopic(String topic) {
    return new MqttTopic(topic, this);
}
项目:hestia-engine-dev    文件:BasicSyncTestCaseMIDP.java   
/**
 * @throws Exception 
 */
public void testPubSub() throws Exception {

  IMqttClient client = null;
  try {
    String topicStr = "topic" + "_02";
    String clientId = "testPubSub";
    client = new MqttClient(serverURI, clientId);

    System.out.println("Assigning callback...");
    MessageListener listener = new MessageListener();
    client.setCallback(listener);

    System.out.println("Connecting...(serverURI:" + serverURI + ", ClientId:" + clientId);
    client.connect();

    System.out.println("Subscribing to..." + topicStr);
    client.subscribe(topicStr);

    System.out.println("Publishing to..." + topicStr);
    MqttTopic topic = client.getTopic(topicStr);
    MqttMessage message = new MqttMessage("foo".getBytes());
    topic.publish(message);

    System.out.println("Checking msg");
    MqttMessage msg = listener.getNextMessage();

    if (msg == null) throw new Exception("message should not be null");
    if (!msg.toString().equals("foo")) throw new Exception("message should equal foo");

    System.out.println("getTopic name");
    String topicName = topic.getName();
    System.out.println("topicName = " + topicName);
    if (!topicName.equals(topicStr)) throw new Exception ("topicName should equal topicStr");

    System.out.println("Disconnecting...");
    client.disconnect();
    System.out.println("testPubSub completed successfully");
  }
  finally {
    if (client != null) {
    System.out.println("Close...");
      client.close();
    }
  }
}
项目:enmasse    文件:DisconnectionTest.java   
@Test
public void disconnection(TestContext context) {

    Async async = context.async();

    this.lwtService.willHandler(b -> {

        async.complete();
    });

    try {

        MemoryPersistence persistence = new MemoryPersistence();

        MqttConnectOptions options = new MqttConnectOptions();
        options.setWill(new MqttTopic(MQTT_WILL_TOPIC, null), MQTT_WILL_MESSAGE.getBytes(), 1, false);

        MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), CLIENT_ID, persistence);
        client.connect(options);

        client.disconnect();

        async.await();

        context.assertTrue(true);

    } catch (MqttException e) {

        context.assertTrue(false);
        e.printStackTrace();
    }
}
项目:enmasse    文件:DisconnectionTest.java   
private void willClient(TestContext context, String topic, String message, int qos) {

        this.async = context.async();

        try {

        MemoryPersistence persistence = new MemoryPersistence();

        MqttConnectOptions options = new MqttConnectOptions();
        options.setWill(new MqttTopic(topic, null), message.getBytes(), qos, false);

        // workaround for testing "brute disconnection" ignoring the DISCONNECT
        // Eclipse Paho doesn't provide a way to close connection without sending DISCONNECT
        // The mock Last Will and Testament Service will not clear the will message for this "ignore-disconnect" client
        MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), WILL_CLIENT_ID, persistence);
        client.connect(options);

        client.disconnect();

        this.async.await();

        context.assertTrue(true);

        } catch (MqttException e) {

            context.assertTrue(false);
            e.printStackTrace();
        }
    }