/**
   * Publish / send a message to an MQTT server
   *
   * @param topicName the name of the topic to publish to
   * @param qos the quality of service to delivery the message at (0,1,2)
   * @param payload the set of bytes to send to the MQTT server
   * @throws MqttException
   */
  public void publish(String topicName, int qos, byte[] payload, String configId)
      throws MqttException {

    if (!connected) {
      LOG.info("Trying to re-connect");
      if (!connect(SystemConfig.getMqttConfigProperties())) {
        LOG.log(
            Level.WARNING,
            "Could not connect and publish {0} to topic {1}",
            new Object[] {new String(payload), topicName});
        return;
      }
    }

    String instantiatedTopicName = topicName.replace("$clientid", clientId);
    instantiatedTopicName = instantiatedTopicName.replace("$configid", configId);

    String time = new Timestamp(System.currentTimeMillis()).toString();
    LOG.log(
        Level.INFO,
        "Publishing at: {0} to topic \"{1}\" qos {2}",
        new Object[] {time, instantiatedTopicName, qos});

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

    // Send the message to the server, control is not returned until
    // it has been delivered to the server meeting the specified
    // quality of service.
    client.publish(instantiatedTopicName, message);
  }
  /**
   * Publish / send a message to an MQTT server
   *
   * @param topicName the name of the topic to publish to
   * @param qos the quality of service to delivery the message at (0,1,2)
   * @param payload the set of bytes to send to the MQTT server
   * @throws MqttException
   */
  public void publish(String topicName, int qos, byte[] payload) throws MqttException {

    // Connect to the MQTT server
    // issue a non-blocking connect and then use the token to wait until the
    // connect completes. An exception is thrown if connect fails.
    log("Connecting to " + brokerUrl + " with client ID " + client.getClientId());
    IMqttToken conToken = client.connect(conOpt, null, null);
    conToken.waitForCompletion();
    log("Connected");

    String time = new Timestamp(System.currentTimeMillis()).toString();
    log("Publishing at: " + time + " to topic \"" + topicName + "\" qos " + qos);

    // Construct the message to send
    MqttMessage message = new MqttMessage(payload);
    message.setQos(qos);

    // Send the message to the server, control is returned as soon
    // as the MQTT client has accepted to deliver the message.
    // Use the delivery token to wait until the message has been
    // delivered
    IMqttDeliveryToken pubToken = client.publish(topicName, message, null, null);
    pubToken.waitForCompletion();
    log("Published");

    // Disconnect the client
    // Issue the disconnect and then use a token to wait until
    // the disconnect completes.
    log("Disconnecting");
    IMqttToken discToken = client.disconnect(null, null);
    discToken.waitForCompletion();
    log("Disconnected");
  }
예제 #3
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;
  }
예제 #4
0
 private void doPublish(
     String name,
     Object val,
     String src,
     String dpt,
     String textual,
     long updateTime,
     long lastChange) {
   JsonObject jso = new JsonObject();
   jso.add("ts", updateTime).add("lc", lastChange).add("knx_src_addr", src).add("knx_dpt", dpt);
   if (textual != null) jso.add("knx_textual", textual);
   if (val instanceof Integer) jso.add("val", ((Integer) val).intValue());
   else if (val instanceof Number) jso.add("val", ((Number) val).doubleValue());
   else jso.add("val", val.toString());
   String txtmsg = jso.toString();
   MqttMessage msg = new MqttMessage(jso.toString().getBytes(StandardCharsets.UTF_8));
   msg.setQos(0);
   msg.setRetained(true);
   try {
     String fullTopic = topicPrefix + "status/" + name;
     mqttc.publish(fullTopic, msg);
     L.finer("Published " + txtmsg + " to " + fullTopic);
   } catch (MqttException e) {
     L.log(Level.WARNING, "Error when publishing message " + txtmsg, e);
   }
 }
예제 #5
0
 public void publishMQTT(String topic, byte[] data) {
   MqttMessage message = new MqttMessage(data);
   message.setQos(2);
   try {
     this.mqttClient.publish(topic, message);
   } catch (MqttException e) {
     getLogger().warn("Publish MQTT Topic", e);
   }
 }
  public static void main(String[] args) {
    // The quality of service for the sent message.
    int qualityOfService = 1;

    // Memory persistence for client message deliver. Store it in a file in case
    // lose connections to the broker.
    MqttClientPersistence persistence = new MqttDefaultFilePersistence();

    try {
      Properties credentials = new Properties();
      credentials.load(new FileInputStream(new File("/Users/keith/mqtt.properties")));

      MqttClient client =
          new MqttClient(
              "ssl://smartspaces.io:8883", "/mqtt/publisher/credentialed/ssl", persistence);

      client.setCallback(
          new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
              System.out.println("Lost connection");
              cause.printStackTrace();
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
              System.out.println("Got delivery token " + token.getResponse());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
              // Not needed since not subscribing.
            }
          });

      MqttConnectOptions options = new MqttConnectOptions();
      options.setCleanSession(true);
      options.setUserName(credentials.getProperty("mqtt.username"));
      options.setPassword(credentials.getProperty("mqtt.password").toCharArray());
      options.setSocketFactory(configureSSLSocketFactory(credentials));

      System.out.println("Connecting to broker: " + client.getServerURI());
      client.connect(options);
      System.out.println("Connected");

      byte[] content = "Hello, world!".getBytes();
      MqttMessage message = new MqttMessage(content);
      message.setQos(qualityOfService);
      client.publish("/greeting", message);
      System.out.println("Message published");

      client.disconnect();
      System.out.println("Disconnected");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #7
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();
    }
  }
예제 #8
0
 @Override
 public void onSuccess(IMqttToken asyncActionToken) {
   Log.d(TAG, "onSuccess");
   try {
     MqttMessage message = new MqttMessage(new String(client.getClientId()).getBytes());
     message.setQos(qos);
     message.setRetained(true);
     client.publish("/users", message);
     client.subscribe("/users", qos);
   } catch (MqttException e) {
     e.printStackTrace();
   }
 }
예제 #9
0
 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 MqttMessage fromMessage(Message<?> message, Class<?> targetClass) {
   byte[] payloadBytes = messageToMqttBytes(message);
   MqttMessage mqttMessage = new MqttMessage(payloadBytes);
   Object header = message.getHeaders().get(MqttHeaders.RETAINED);
   Assert.isTrue(
       header == null || header instanceof Boolean,
       MqttHeaders.RETAINED + " header must be Boolean");
   mqttMessage.setRetained(header == null ? this.defaultRetained : (Boolean) header);
   header = message.getHeaders().get(MqttHeaders.QOS);
   Assert.isTrue(
       header == null || header instanceof Integer, MqttHeaders.QOS + " header must be Integer");
   mqttMessage.setQos(header == null ? this.defaultQos : (Integer) header);
   return mqttMessage;
 }
예제 #11
0
 private void publish(JsonObject jsonPubMsg) throws MqttException, UnsupportedEncodingException {
   final String METHOD = "publish1";
   String topic = jsonPubMsg.get("topic").getAsString();
   int qos = jsonPubMsg.get("qos").getAsInt();
   JsonObject payload = jsonPubMsg.getAsJsonObject("payload");
   LoggerUtility.log(
       Level.FINE,
       CLASS_NAME,
       METHOD,
       ": Topic(" + topic + ") qos=" + qos + " payload (" + payload.toString() + ")");
   MqttMessage message = new MqttMessage();
   message.setPayload(payload.toString().getBytes("UTF-8"));
   message.setQos(qos);
   publish(DeviceTopic.get(topic), message);
 }
  public void publish(int qos, String payload) {
    try {
      // Create and configure a message
      MqttMessage message = new MqttMessage(payload.getBytes());
      message.setQos(qos);

      // Send the message to the server, control is not returned until
      // it has been delivered to the server meeting the specified
      // quality of service.
      mqttClient.publish(topic, message);
    } catch (MqttException e) {
      log.error(
          "Error occurred when publishing message for MQTT server : " + mqttClient.getServerURI());
      handleException(e);
    }
  }
  /**
   * {@inheritDoc} VirtualFirealarm device-type specific implementation to publish data to the
   * device. This method calls the {@link #publishToQueue(String, MqttMessage)} method of the
   * "MQTTTransportHandler" class.
   */
  @Override
  public void publishDeviceData(String... publishData) throws TransportHandlerException {
    if (publishData.length != 4) {
      String errorMsg =
          "Incorrect number of arguments received to SEND-MQTT Message. "
              + "Need to be [owner, deviceId, resource{BULB/TEMP}, state{ON/OFF or null}]";
      log.error(errorMsg);
      throw new TransportHandlerException(errorMsg);
    }

    String deviceOwner = publishData[0];
    String deviceId = publishData[1];
    String resource = publishData[2];
    String state = publishData[3];

    MqttMessage pushMessage = new MqttMessage();
    String publishTopic = "wso2/" + VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId;

    try {
      PublicKey devicePublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId);
      PrivateKey serverPrivateKey = SecurityManager.getServerPrivateKey();

      String actualMessage = resource + ":" + state;
      String encryptedMsg =
          VirtualFireAlarmServiceUtils.prepareSecurePayLoad(
              actualMessage, devicePublicKey, serverPrivateKey);

      pushMessage.setPayload(encryptedMsg.getBytes(StandardCharsets.UTF_8));
      pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
      pushMessage.setRetained(false);

      publishToQueue(publishTopic, pushMessage);

    } catch (VirtualFireAlarmException e) {
      String errorMsg =
          "Preparing Secure payload failed for device - ["
              + deviceId
              + "] of owner - "
              + "["
              + deviceOwner
              + "].";
      log.error(errorMsg);
      throw new TransportHandlerException(errorMsg, e);
    }
  }
예제 #14
0
  /**
   * Turns the given list of LoggedMqttMessages into ReceivedMqttMessages.
   *
   * @param list List of logged messages to progress
   * @param progress The progress updater to call with updated progress
   * @param current Current progress
   * @param max Maximum progress value
   * @return List of MQTT message objects (ReceivedMqttMessage)
   */
  public static List<BaseMqttMessage> processMessageLog(
      final List<LoggedMqttMessage> list,
      final ProgressUpdater progress,
      final long current,
      final long max) {
    final List<BaseMqttMessage> mqttMessageList = new ArrayList<BaseMqttMessage>();
    long item = 0;

    // Process the messages
    for (final LoggedMqttMessage loggedMessage : list) {
      if (progress != null) {
        item++;
        if (item % 1000 == 0) {
          progress.update(current + item, max);
        }
      }

      final MqttMessage mqttMessage = new MqttMessage();

      if (logger.isTraceEnabled()) {
        logger.trace("Processing message with payload {}", loggedMessage.getValue());
      }

      if (Boolean.TRUE.equals(loggedMessage.isEncoded())) {
        mqttMessage.setPayload(Base64.decodeBase64(loggedMessage.getValue()));
      } else {
        mqttMessage.setPayload(ConversionUtils.stringToArray(loggedMessage.getValue()));
      }

      mqttMessage.setQos(loggedMessage.getQos() == null ? 0 : loggedMessage.getQos());
      mqttMessage.setRetained(
          loggedMessage.isRetained() == null ? false : loggedMessage.isRetained());

      mqttMessageList.add(
          new BaseMqttMessage(
              loggedMessage.getId(),
              loggedMessage.getTopic(),
              mqttMessage,
              new Date(loggedMessage.getTimestamp())));
    }
    logger.info("Message log - processed {} MQTT messages", list.size());

    return mqttMessageList;
  }
예제 #15
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();
     }
   }
 }
예제 #16
0
  /**
   * Publish / send a message to an MQTT server
   *
   * @param topicName the name of the topic to publish to
   * @param qos the quality of service to delivery the message at (0,1,2)
   * @param payload the set of bytes to send to the MQTT server
   * @throws MqttException
   */
  public void publish(String topicName, int qos, byte[] payload) throws MqttException {

    // Connect to the MQTT server
    log("Connecting to " + brokerUrl + " with client ID " + client.getClientId());
    client.connect(conOpt);
    log("Connected");

    String time = new Timestamp(System.currentTimeMillis()).toString();
    log("Publishing at: " + time + " to topic \"" + topicName + "\" qos " + qos);

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

    // Send the message to the server, control is not returned until
    // it has been delivered to the server meeting the specified
    // quality of service.
    client.publish(topicName, message);

    // Disconnect the client
    client.disconnect();
    log("Disconnected");
  }
  @Override
  public void publish(String topic, String content, Integer qos, Boolean retained)
      throws ProcessingException {
    checkConnection();

    try {
      MqttMessage message = new MqttMessage(content.getBytes());

      if (qos != null) {
        message.setQos(qos);
      }

      if (retained != null) {
        message.setRetained(retained);
      }

      m_mqttClient.publish(topic, message);
    } catch (Exception e) {
      throw new ProcessingException(TEXTS.get("publishError"), e);
    }

    s_logger.info("message " + topic + ":'" + content + "' successfully published");
  }
예제 #18
0
  /**
   * Send the message and waits for the response from IBM IoT Foundation
   *
   * <p>
   *
   * <p>This method is used by the library to send following messages to IBM IoT Foundation
   *
   * <ul class="simple">
   *   <li>Manage
   *   <li>Unmanage
   *   <li>Location update
   *   <li>Diagnostic update/clear
   * </ul>
   *
   * @param topic Topic where the message to be sent
   * @param jsonPayload The message
   * @param timeout How long to wait for the resonse
   * @return response in Json format
   * @throws MqttException
   */
  public JsonObject sendAndWait(DeviceTopic topic, JsonObject jsonPayload, long timeout)
      throws MqttException {

    final String METHOD = "sendAndWait";

    String uuid = UUID.randomUUID().toString();
    jsonPayload.add("reqId", new JsonPrimitive(uuid));

    LoggerUtility.fine(
        CLASS_NAME,
        METHOD,
        "Topic (" + topic + ") payload (" + jsonPayload.toString() + ") reqId (" + uuid + ")");

    if (responseSubscription == null) {
      responseSubscription = ServerTopic.RESPONSE;
      subscribe(responseSubscription, 1, this);
    }

    MqttMessage message = new MqttMessage();
    try {
      message.setPayload(jsonPayload.toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      LoggerUtility.log(
          Level.SEVERE, CLASS_NAME, METHOD, "Error setting payload for topic: " + topic, e);
      return null;
    }

    message.setQos(1);

    requests.put(uuid, message);

    publish(topic, message);

    JsonObject jsonResponse = null;
    while (jsonResponse == null) {
      try {
        jsonResponse = queue.poll(timeout, TimeUnit.MILLISECONDS);
        if (jsonResponse == null) {
          break;
        }
        if (jsonResponse.get("reqId").getAsString().equals(uuid)) {
          LoggerUtility.fine(
              CLASS_NAME, METHOD, "" + "This response is for me reqId:" + jsonResponse.toString());
          break;
        } else {
          // This response is not for our request, put it back to the queue.
          LoggerUtility.warn(
              CLASS_NAME, METHOD, "This response is NOT for me reqId:" + jsonResponse.toString());
          queue.add(jsonResponse);
          jsonResponse = null;
        }
      } catch (InterruptedException e) {
        break;
      }
    }
    if (jsonResponse == null) {
      LoggerUtility.warn(
          CLASS_NAME, METHOD, "NO RESPONSE from IoTF for request: " + jsonPayload.toString());
      LoggerUtility.warn(CLASS_NAME, METHOD, "Connected(" + isConnected() + ")");
    }
    return jsonResponse;
  }