Пример #1
0
  public static void main(String[] args) {
    String topic = "/group/1ffb66a0-304e-11e5-a2cb-0800200c9a66/send_data";
    String contentStr = "Message from KC";
    int qos = 2;
    String broker = "tcp://isplanet.dyndns-office.com:1883";
    String clientId = "JavaSample";
    MemoryPersistence persistence = new MemoryPersistence();

    Content content = new Content();
    content.setDevID("80:C1:6E:F3:E7:6B");
    content.setDevName("KC");
    content.setGroupID("1ffb66a0-304e-11e5-a2cb-0800200c9a66");
    content.setSendTimestamp(String.valueOf(System.currentTimeMillis()));

    Shot shot = new Shot();
    shot.setMessage("Test");
    shot.setImageUrl("http://ab.unayung.cc/uploads/photo/file/000/000/030/LN07_005.jpg");
    shot.setPosition(new GeoPoint(25.042299, 121.507695));

    content.setShot(shot);
    contentStr = JsonDataFactory.getJson(content);

    // System.exit(0);

    try {
      MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
      MqttConnectOptions connOpts = new MqttConnectOptions();
      connOpts.setCleanSession(true);
      System.out.println("Connecting to broker: " + broker);

      sampleClient.connect(connOpts);
      System.out.println("Connected");
      System.out.println("Publishing message: " + contentStr);

      MqttMessage message = new MqttMessage(contentStr.getBytes());
      message.setQos(qos);
      sampleClient.publish(topic, message);
      System.out.println("Message published");

      sampleClient.disconnect();
      System.out.println("Disconnected");

      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();
    }
  }
  /**
   * The main entry point of the sample.
   *
   * <p>This method handles parsing the arguments specified on the command-line before performing
   * the specified action.
   */
  public static void main(String[] args) {

    // Default settings:
    boolean quietMode = false;
    String action = "publish";
    String topic = "";
    String message = "Message from async waiter Paho MQTTv3 Java client sample";
    int qos = 2;
    String broker = "m2m.eclipse.org";
    int port = 1883;
    String clientId = null;
    String subTopic = "Sample/#";
    String pubTopic = "Sample/Java/v3";
    boolean cleanSession = true; // Non durable subscriptions
    boolean ssl = false;
    String userName = null;
    String password = null;

    // Parse the arguments -
    for (int i = 0; i < args.length; i++) {
      // Check this is a valid argument
      if (args[i].length() == 2 && args[i].startsWith("-")) {
        char arg = args[i].charAt(1);
        // Handle arguments that take no-value
        switch (arg) {
          case 'h':
          case '?':
            printHelp();
            return;
          case 'q':
            quietMode = true;
            continue;
        }

        // Now handle the arguments that take a value and
        // ensure one is specified
        if (i == args.length - 1 || args[i + 1].charAt(0) == '-') {
          System.out.println("Missing value for argument: " + args[i]);
          printHelp();
          return;
        }
        switch (arg) {
          case 'a':
            action = args[++i];
            break;
          case 't':
            topic = args[++i];
            break;
          case 'm':
            message = args[++i];
            break;
          case 's':
            qos = Integer.parseInt(args[++i]);
            break;
          case 'b':
            broker = args[++i];
            break;
          case 'p':
            port = Integer.parseInt(args[++i]);
            break;
          case 'i':
            clientId = args[++i];
            break;
          case 'c':
            cleanSession = Boolean.valueOf(args[++i]).booleanValue();
            break;
          case 'k':
            System.getProperties().put("javax.net.ssl.keyStore", args[++i]);
            break;
          case 'w':
            System.getProperties().put("javax.net.ssl.keyStorePassword", args[++i]);
            break;
          case 'r':
            System.getProperties().put("javax.net.ssl.trustStore", args[++i]);
            break;
          case 'v':
            ssl = Boolean.valueOf(args[++i]).booleanValue();
            break;
          case 'u':
            userName = args[++i];
            break;
          case 'z':
            password = args[++i];
            break;
          default:
            System.out.println("Unrecognised argument: " + args[i]);
            printHelp();
            return;
        }
      } else {
        System.out.println("Unrecognised argument: " + args[i]);
        printHelp();
        return;
      }
    }

    // Validate the provided arguments
    if (!action.equals("publish") && !action.equals("subscribe")) {
      System.out.println("Invalid action: " + action);
      printHelp();
      return;
    }
    if (qos < 0 || qos > 2) {
      System.out.println("Invalid QoS: " + qos);
      printHelp();
      return;
    }
    if (topic.equals("")) {
      // Set the default topic according to the specified action
      if (action.equals("publish")) {
        topic = pubTopic;
      } else {
        topic = subTopic;
      }
    }

    String protocol = "tcp://";

    if (ssl) {
      protocol = "ssl://";
    }

    String url = protocol + broker + ":" + port;

    if (clientId == null || clientId.equals("")) {
      clientId = "SampleJavaV3_" + action;
    }

    // With a valid set of arguments, the real work of
    // driving the client API can begin
    try {
      // Create an instance of this class
      SampleAsyncWait sampleClient =
          new SampleAsyncWait(url, clientId, cleanSession, quietMode, userName, password);

      // Perform the specified action
      if (action.equals("publish")) {
        sampleClient.publish(topic, qos, message.getBytes());
      } else if (action.equals("subscribe")) {
        sampleClient.subscribe(topic, qos);
      }
    } catch (MqttException me) {
      // Display full details of any exception that occurs
      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();
    }
  }
Пример #3
0
  public void publish(String publishClientId, String publishTopic, byte[] payload)
      throws DeviceControllerException {

    if (mqttEnabled) {
      MqttClient client;
      MqttConnectOptions options;

      if (publishClientId.length() > 24) {
        String errorString =
            "No of characters '"
                + publishClientId.length()
                + "' for ClientID: '"
                + publishClientId
                + "' is invalid (should be less than 24, hence please provide a "
                + "simple "
                + "'owner' tag)";
        log.error(errorString);
        throw new DeviceControllerException(errorString);
      } else {
        log.info(
            "No of Characters "
                + publishClientId.length()
                + " for ClientID : '"
                + publishClientId
                + "' is acceptable");
      }

      try {
        client = new MqttClient(mqttEndpoint, publishClientId);
        options = new MqttConnectOptions();
        options.setWill("device/clienterrors", "crashed".getBytes(UTF_8), 2, true);
        client.setCallback(this);
        client.connect(options);

        client.publish(publishTopic, payload, 0, true);

        if (log.isDebugEnabled()) {
          log.debug(
              "MQTT Client successfully published to topic: "
                  + publishTopic
                  + ", with payload - "
                  + payload);
        }
        client.disconnect();
      } catch (MqttException ex) {
        String errorMsg =
            "MQTT Client Error"
                + "\n\tReason:  "
                + ex.getReasonCode()
                + "\n\tMessage: "
                + ex.getMessage()
                + "\n\tLocalMsg: "
                + ex.getLocalizedMessage()
                + "\n\tCause: "
                + ex.getCause()
                + "\n\tException: "
                + ex;

        log.error(errorMsg, ex);
        throw new DeviceControllerException(errorMsg, ex);
      }
    } else {
      log.warn("MQTT <Enabled> set to false in 'device-mgt-config.xml'");
    }
  }