Example #1
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);
   }
 }
Example #2
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());
   }
 }
 @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();
   }
 }
 @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;
 }
  /**
   * {@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);
    }
  }
  /**
   * 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;
  }
  @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");
  }