Exemple #1
0
  private void doConnect() {
    L.info(
        "Connecting to MQTT broker "
            + mqttc.getServerURI()
            + " with CLIENTID="
            + mqttc.getClientId()
            + " and TOPIC PREFIX="
            + topicPrefix);

    MqttConnectOptions copts = new MqttConnectOptions();
    copts.setWill(topicPrefix + "connected", "0".getBytes(), 1, true);
    copts.setCleanSession(true);
    copts.setUserName("emonpi");
    copts.setPassword("emonpimqtt2016".toCharArray());
    try {
      mqttc.connect(copts);
      sendConnectionState();
      L.info("Successfully connected to broker, subscribing to " + topicPrefix + "(set|get)/#");
      try {
        mqttc.subscribe(topicPrefix + "set/#", 1);
        mqttc.subscribe(topicPrefix + "get/#", 1);
        shouldBeConnected = true;
      } catch (MqttException mqe) {
        L.log(Level.WARNING, "Error subscribing to topic hierarchy, check your configuration", mqe);
        throw mqe;
      }
    } catch (MqttException mqe) {
      L.log(
          Level.WARNING,
          "Error while connecting to MQTT broker, will retry: " + mqe.getMessage(),
          mqe);
      queueConnect(); // Attempt reconnect
    }
  }
 public void disconnect() {
   if (client != null) {
     try {
       client.disconnect();
     } catch (MqttException e) {
       log.warn(e.getMessage());
     }
   }
 }
  private boolean registerDevice(long lifetime) {
    final String METHOD = "registerDevice";
    boolean success = false;
    String organization = getOrgId();
    if (organization == null || ("quickstart").equals(organization)) {
      LoggerUtility.log(
          Level.SEVERE,
          CLASS_NAME,
          METHOD,
          "Unable to create ManagedClient instance.  "
              + "QuickStart devices do not support device management");

      throw new RuntimeException(
          "Unable to create ManagedClient instance.  "
              + "QuickStart devices do not support device management");
    }
    try {
      success = this.manage(lifetime);
      if (success) {
        LoggerUtility.log(Level.INFO, CLASS_NAME, METHOD, "Device is connected as managed device");
      } else {
        LoggerUtility.log(
            Level.WARNING, CLASS_NAME, METHOD, "Device is failed to connect as managed device");
      }
    } catch (MqttException ex) {
      LoggerUtility.log(
          Level.SEVERE,
          CLASS_NAME,
          METHOD,
          "Connecting the device as managed device "
              + "operation is Failed, Exception: "
              + ex.getMessage());

      RuntimeException e =
          new RuntimeException(
              "Connecting the device as managed device "
                  + "operation is Failed, Exception: "
                  + ex.getMessage());
      e.initCause(ex);
      throw e;
    }
    return success;
  }
Exemple #4
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();
    }
  }
 public void sendMessage(String message) {
   MqttMessage mqttMsg = new MqttMessage(message.getBytes());
   mqttMsg.setQos(this.qos);
   mqttMsg.setRetained(this.retained);
   try {
     log.info("Publishing message: " + mqttMsg + " to topic \"" + this.topic + "\"");
     client.publish(this.topic, mqttMsg);
   } catch (MqttPersistenceException e) {
     log.error(e.getMessage());
   } catch (MqttException e) {
     log.error(e.getMessage());
   }
 }
 @Override
 public void run() {
   while (!connectionSucceeded) {
     try {
       Thread.sleep(3000);
       startListener();
       connectionSucceeded = true;
       log.info("MQTT Connection successful");
     } catch (InterruptedException e) {
       log.error(e.getMessage(), e);
     } catch (MqttException e) {
       log.error(e.getMessage(), e);
     }
   }
 }
  public boolean connect(
      String serverURI, String topic, String clientId, int qos, boolean retained) {
    this.serverURI = serverURI;
    this.topic = topic;
    this.clientId = clientId;
    this.qos = qos;
    this.retained = retained;

    try {
      client = new MqttClient(this.serverURI, this.clientId);
      client.connect();
    } catch (MqttException e) {
      log.error(e.getMessage());
    }

    if (client.isConnected()) {
      log.info("Connected to Mqtt server " + serverURI);
      return true;
    }
    return false;
  }
Exemple #8
0
 @Override
 public void ping() {
   if (!isActive()) {
     Log.d(TAG, "Can't ping because connection is not active");
     return;
   }
   MqttMessage message = new MqttMessage(Constants.MQTT_KEEP_ALIVE_MESSAGE);
   message.setQos(Constants.MQTT_KEEP_ALIVE_QOS);
   try {
     mqttClient.publish(String.format(keepAliveTopic, mqttClient.getClientId()), message);
     Log.i(TAG, "Successful ping");
   } catch (MqttException e) {
     Log.wtf(
         TAG,
         "Exception during ping. Reason code:"
             + e.getReasonCode()
             + " Message: "
             + e.getMessage());
     for (MqttPingerObserver observer : observers) {
       observer.onFailedPing();
     }
   }
 }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.option_menu_shareTopic_searching:
        alljoyn_wrapper.mBusHandler.sendEmptyMessage(alljoyn_wrapper.mBusHandler.CONNECT);
        mHandler.sendEmptyMessage(alljoyn_wrapper.MESSAGE_ALLJOYN_START_PROGRESS_DIALOG);
        return true;

      case R.id.option_menu_shareTopic_get_topic:
        Message msg =
            alljoyn_wrapper.mBusHandler.obtainMessage(
                AlljoynWrapper.BusHandler.GET_TOPIC, alljoyn_wrapper.keyValue);
        alljoyn_wrapper.mBusHandler.sendMessage(msg);

        return true;

      case R.id.option_menu_inviteShare_genTopic:
        {
          HttpWrapper http_request = new HttpWrapper();
          http_request.topic = topic;
          http_request.setOutputListener(this);
          SettingActivity.cur_command = SettingActivity.COMMAND_INVITESHARE_GEN_PINCODE;
          String url = new String("https://");
          url += inviteSRV + "/generateInvite";
          http_request.execute(url);
        }
        return true;

      case R.id.option_menu_inviteShare_getTopic:
        {
          HttpWrapper http_request = new HttpWrapper();
          http_request.setOutputListener(this);
          SettingActivity.cur_command = SettingActivity.COMMAND_INVITESHARE_GET_TOPIC;

          String url = new String("https://");
          url += inviteSRV + "/getTopic/" + pincode;
          http_request.execute(url);
        }
        return true;

      case R.id.option_menu_setting:
        Intent intent1 = new Intent(this, SettingActivity.class);
        intent1.putExtra(share_invite_srv, inviteSRV);
        intent1.putExtra(share_mqtt_srv, mqttSRV);
        intent1.putExtra(share_topic, topic);
        intent1.putExtra(share_pin, pincode);
        intent1.putExtra(share_key, alljoyn_wrapper.keyValue);
        startActivityForResult(intent1, INTENT_SETTING_RESULT_CODE);
        return true;
      case R.id.option_menu_remoteAccess_get_list: // Get list of menu item
        MqttMessage message = null;
        try {
          message = MQTTMessageWrapper.CreateGetListMsg();
        } catch (JSONException e) {
          e.printStackTrace();
        }
        try {
          MainActivity.client.publish(topic, message);
        } catch (MqttException e) {
          Log.d(MainActivity.TAG, "Publish error with message: " + e.getMessage());
        }

        return true;

      case R.id.option_menu_help:
        return true;

      case R.id.option_menu_wifi_setup_scan:
        Intent intent2 = new Intent(this, ScanWIFIActivity.class);

        startActivity(intent2);

        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }
  /**
   * 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();
    }
  }
  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'");
    }
  }