Esempio n. 1
0
  /**
   * Publish data to the IBM Internet of Things Foundation.<br>
   * This method allows QoS to be passed as an argument
   *
   * @param event Name of the dataset under which to publish the data
   * @param data Object to be added to the payload as the dataset
   * @param qos Quality of Service - should be 0, 1 or 2
   * @return Whether the send was successful.
   */
  public boolean publishEvent(String event, Object data, int qos) {
    if (!isConnected()) {
      return false;
    }
    final String METHOD = "publishEvent(2)";
    JsonObject payload = new JsonObject();

    String timestamp = ISO8601_DATE_FORMAT.format(new Date());
    payload.addProperty("ts", timestamp);

    JsonElement dataElement = gson.toJsonTree(data);
    payload.add("d", dataElement);

    String topic = "iot-2/evt/" + event + "/fmt/json";

    LoggerUtility.fine(CLASS_NAME, METHOD, "Topic   = " + topic);
    LoggerUtility.fine(CLASS_NAME, METHOD, "Payload = " + payload.toString());

    MqttMessage msg = new MqttMessage(payload.toString().getBytes(Charset.forName("UTF-8")));
    msg.setQos(qos);
    msg.setRetained(false);

    try {
      mqttAsyncClient.publish(topic, msg).waitForCompletion();
    } catch (MqttPersistenceException e) {
      e.printStackTrace();
      return false;
    } catch (MqttException e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }
 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());
   }
 }
Esempio n. 3
0
  public void publish(String topic, byte[] payload) {

    if (androidClient.isConnected()) {
      try {
        androidClient.publish(topic, payload, qualityOfService, false);
      } catch (MqttPersistenceException e) {
        Log.i(DEBUG_TAG, e.getLocalizedMessage());
      } catch (MqttException e) {
        Log.i(DEBUG_TAG, e.getLocalizedMessage());
      }
    } else {
      Log.i(DEBUG_TAG, "Could not publish. Client is not connected. Please connect first.");
    }
  }
  public void handleDelivery(
      String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
      throws java.io.IOException {

    String msg = new String(body);
    System.out.println("Received: " + msg);
    if (mqttClientInterface != null)
      try {
        System.out.println("Sending to MQTT...");
        mqttClientInterface.PublishToMQTTserver(body);
        System.out.println("Message Sent!");
      } catch (MqttPersistenceException e) {
        e.printStackTrace();
      } catch (MqttException e) {
        e.printStackTrace();
      }
  }