Пример #1
0
    @Override
    protected Object doInBackground(Object... params) {

      log("create connection");
      String mqttConnSpec = "tcp://" + brokerHostName + "@" + MQTT_BROKER_PORT_NUM;
      // Create the client and connect
      try {
        mqttClient = MqttClient.createMqttClient(mqttConnSpec, MQTT_PERSISTENCE);

        String clientID = MQTT_CLIENT_ID + "/" + mPrefs.getString(PREF_DEVICE_ID, "");

        mqttClient.connect(clientID, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);
        // register this client app has being able to receive messages
        mqttClient.registerSimpleHandler(this);
        // Subscribe to an initial topic, which is combination of client
        // ID
        // and device ID.
        initTopic = MQTT_CLIENT_ID + "/" + initTopic;
        subscribeToTopic(initTopic);
      } catch (MqttException e) {
        e.printStackTrace();
      }
      log("Connection established to " + brokerHostName + " on topic " + initTopic);

      // Save start time
      mStartTime = System.currentTimeMillis();
      // Star the keep-alives
      startKeepAlives();
      return null;
    }
Пример #2
0
 /*
  * Sends a message to the message broker, requesting that it be
  * published to the specified topic.
  */
 private void publishToTopic(String topicName, String message) throws MqttException {
   if ((mqttClient == null) || (mqttClient.isConnected() == false)) {
     // quick sanity check - don't try and publish if we don't have
     // a connection
     log("No connection to public to");
   } else {
     mqttClient.publish(
         topicName, message.getBytes(), MQTT_QUALITY_OF_SERVICE, MQTT_RETAINED_PUBLISH);
   }
 }
Пример #3
0
    /*
     * Send a request to the message broker to be sent messages published
     * with the specified topic name. Wildcards are allowed.
     */
    private void subscribeToTopic(String topicName) throws MqttException {

      if ((mqttClient == null) || (mqttClient.isConnected() == false)) {
        // quick sanity check - don't try and subscribe if we don't have
        // a connection
        log("Connection error" + "No connection");
      } else {
        String[] topics = {topicName};
        mqttClient.subscribe(topics, MQTT_QUALITIES_OF_SERVICE);
      }
    }
Пример #4
0
 // Disconnect
 public void disconnect() {
   try {
     stopKeepAlives();
     if (mqttClient != null) {
       mqttClient.disconnect();
     }
   } catch (MqttPersistenceException e) {
     log("MqttException" + (e.getMessage() != null ? e.getMessage() : " NULL"), e);
   }
 }