/**
   * 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");
  }
示例#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;
  }
示例#3
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);
   }
 }
  /**
   * 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);
  }
 /**
  * Subclasses can override this method to convert the byte[] to a payload. The default
  * implementation creates a String (default) or byte[].
  *
  * @param mqttMessage The inbound message.
  * @return The payload for the Spring integration message
  * @throws Exception Any.
  */
 protected Object mqttBytesToPayload(MqttMessage mqttMessage) throws Exception {
   if (this.payloadAsBytes) {
     return mqttMessage.getPayload();
   } else {
     return new String(mqttMessage.getPayload(), this.charset);
   }
 }
  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 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);
   }
 }
 @Override
 public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
   Log.i(DEBUG_TAG, "Topic: " + topic + " Message: " + new String(mqttMessage.getPayload()));
   Intent intent = new Intent();
   intent.setAction(MESSAGE_RECEIVED);
   intent.putExtra("topic", topic);
   intent.putExtra("message", mqttMessage.getPayload());
   context.sendBroadcast(intent);
 }
示例#9
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 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();
   }
 }
 /** @see MqttCallback#messageArrived(String, MqttMessage) */
 public void messageArrived(String topic, MqttMessage message) throws MqttException {
   // Called when a message arrives from the server that matches any
   // subscription made by the client
   String time = new Timestamp(System.currentTimeMillis()).toString();
   System.out.println(
       "Time:\t"
           + time
           + "  Topic:\t"
           + topic
           + "  Message:\t"
           + new String(message.getPayload())
           + "  QoS:\t"
           + message.getQos());
 }
  @Override
  public void messageArrived(String topic, MqttMessage message) throws Exception {
    LOG.log(
        Level.INFO,
        "Message arrived for topic: {0}, QoS: {1}, message: {2}",
        new Object[] {topic, message.getQos(), new String(message.getPayload())});

    for (String tPattern : listeners.keySet()) {
      if (matchesTopic(tPattern, topic)) {
        // Notify the listener of the incoming message
        listeners.get(tPattern).notify(message);
      }
    }
  }
示例#14
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);
 }
 @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;
 }
  @Override
  public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
    try {
      String msgText = mqttMessage.toString();
      if (log.isDebugEnabled()) {
        log.debug(msgText);
      }
      PrivilegedCarbonContext.startTenantFlow();
      PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);

      if (log.isDebugEnabled()) {
        log.debug("Event received in MQTT Event Adapter - " + msgText);
      }

      if (contentValidator != null && contentTransformer != null) {
        ContentInfo contentInfo;
        Map<String, Object> dynamicProperties = new HashMap<>();
        dynamicProperties.put(MQTTEventAdapterConstants.TOPIC, topic);
        msgText = (String) contentTransformer.transform(msgText, dynamicProperties);
        contentInfo = contentValidator.validate(msgText, dynamicProperties);
        if (contentInfo != null && contentInfo.isValidContent()) {
          eventAdapterListener.onEvent(contentInfo.getMessage());
        }
      } else {
        eventAdapterListener.onEvent(msgText);
      }
    } finally {
      PrivilegedCarbonContext.endTenantFlow();
    }
  }
示例#17
0
  @Override
  public void messageArrived(String topic, MqttMessage message) throws Exception {
    final String METHOD = "messageArrived";
    if (topic.equals(ServerTopic.RESPONSE.getName())) {
      LoggerUtility.log(
          Level.FINE,
          CLASS_NAME,
          METHOD,
          "Received response from IoT Foundation, topic (" + topic + ")");

      String responsePayload = new String(message.getPayload(), "UTF-8");
      JsonObject jsonResponse = new JsonParser().parse(responsePayload).getAsJsonObject();
      try {
        String reqId = jsonResponse.get("reqId").getAsString();
        LoggerUtility.fine(CLASS_NAME, METHOD, "reqId (" + reqId + "): " + jsonResponse.toString());
        MqttMessage sentMsg = requests.remove(reqId);
        if (sentMsg != null) {
          queue.put(jsonResponse);
        }
      } catch (Exception e) {
        if (jsonResponse.get("reqId") == null) {
          LoggerUtility.warn(
              CLASS_NAME,
              METHOD,
              "The response " + "does not contain 'reqId' field (" + responsePayload + ")");
        } else {
          LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Unexpected exception", e);
        }
      }
    } else {
      LoggerUtility.warn(CLASS_NAME, METHOD, "Unknown topic (" + topic + ")");
    }
  }
  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);
    }
  }
  @Override
  public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
    if (topic.equals("Likaci/MqttMap")) {
      String msg = new String(mqttMessage.getPayload());
      JSONObject json = new JSONObject(msg);
      if (!json.getString("id").equals(id)) {
        Point p =
            (Point)
                GeometryEngine.project(
                    new Point(json.getDouble("x"), json.getDouble("y")),
                    SpatialReference.create(4326),
                    SpatialReference.create(3857));

        layer.removeAll();

        SimpleMarkerSymbol markerSymbol =
            new SimpleMarkerSymbol(
                Color.parseColor("#763382"), 15, SimpleMarkerSymbol.STYLE.DIAMOND);
        layer.addGraphic(new Graphic(p, markerSymbol));

        TextSymbol textSymbol =
            new TextSymbol(
                15,
                json.getString("id"),
                Color.parseColor("#763382"),
                TextSymbol.HorizontalAlignment.CENTER,
                TextSymbol.VerticalAlignment.MIDDLE);
        textSymbol.setOffsetY(-15);
        layer.addGraphic(new Graphic(p, textSymbol));
      }
    }
  }
 @Override
 public Message<?> toMessage(String topic, MqttMessage mqttMessage) {
   try {
     AbstractIntegrationMessageBuilder<Object> messageBuilder =
         getMessageBuilderFactory()
             .withPayload(mqttBytesToPayload(mqttMessage))
             .setHeader(MqttHeaders.QOS, mqttMessage.getQos())
             .setHeader(MqttHeaders.DUPLICATE, mqttMessage.isDuplicate())
             .setHeader(MqttHeaders.RETAINED, mqttMessage.isRetained());
     if (topic != null) {
       messageBuilder.setHeader(MqttHeaders.TOPIC, topic);
     }
     return messageBuilder.build();
   } catch (Exception e) {
     throw new MessageConversionException("failed to convert object to Message", 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);
    }
  }
示例#22
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;
  }
示例#23
0
 private void processSetGet(String namePart, MqttMessage msg, boolean set) {
   if (msg.isRetained()) {
     L.finer("Ignoring retained message " + msg + " to " + namePart);
     return;
   }
   // Now translate the topic into a group address
   GroupAddressInfo gai = GroupAddressManager.getGAInfoForName(namePart);
   if (gai == null) {
     L.warning(
         "Unable to translate name "
             + namePart
             + " into a group address, ignoring message "
             + msg);
     return;
   }
   L.fine("Name " + namePart + " translates to GA " + gai.address);
   String data = new String(msg.getPayload(), StandardCharsets.UTF_8);
   if (set) KNXConnector.doGroupWrite(gai.address, data, gai);
   else KNXConnector.doGroupRead(gai.address, data, gai);
 }
  /**
   * Store an MQTT message
   *
   * @param clientHandle identifier for the client storing the message
   * @param topic The topic on which the message was published
   * @param message the arrived MQTT message
   * @return an identifier for the message, so that it can be removed when appropriate
   */
  @Override
  public String storeArrived(String clientHandle, String topic, MqttMessage message) {

    db = mqttDb.getWritableDatabase();

    traceHandler.traceDebug(
        TAG, "storeArrived{" + clientHandle + "}, {" + message.toString() + "}");

    byte[] payload = message.getPayload();
    int qos = message.getQos();
    boolean retained = message.isRetained();
    boolean duplicate = message.isDuplicate();

    ContentValues values = new ContentValues();
    String id = java.util.UUID.randomUUID().toString();
    values.put(MqttServiceConstants.MESSAGE_ID, id);
    values.put(MqttServiceConstants.CLIENT_HANDLE, clientHandle);
    values.put(MqttServiceConstants.DESTINATION_NAME, topic);
    values.put(MqttServiceConstants.PAYLOAD, payload);
    values.put(MqttServiceConstants.QOS, qos);
    values.put(MqttServiceConstants.RETAINED, retained);
    values.put(MqttServiceConstants.DUPLICATE, duplicate);
    values.put(MTIMESTAMP, System.currentTimeMillis());
    try {
      db.insertOrThrow(ARRIVED_MESSAGE_TABLE_NAME, null, values);
    } catch (SQLException e) {
      traceHandler.traceException(TAG, "onUpgrade", e);
      throw e;
    }
    int count = getArrivedRowCount(clientHandle);
    traceHandler.traceDebug(
        TAG,
        "storeArrived: inserted message with id of {"
            + id
            + "} - Number of messages in database for this clientHandle = "
            + count);
    return id;
  }
  @Override
  public void onMqttMessageArrived(String topic, MqttMessage mqttMessage) {
    final String message = new String(mqttMessage.getPayload());

    // Log.d(TAG, "Mqtt messageArrived from topic: " +topic+ " message: "+message);

    runOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            uartSendData(message, true); // Don't republish to mqtt something received from mqtt
          }
        });
  }
示例#26
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();
     }
   }
 }
示例#27
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");
  }
示例#29
0
  public void doDemo() {
    try {
      client = new MqttClient("tcp://115.28.225.5:1883", "pahomqttpublish1");
      client.connect();
      MqttMessage message = new MqttMessage();
      message.setPayload("A single message".getBytes());
      client.publish("pahodemo", message);
      client.disconnect();

      MqttConnectOptions options = new MqttConnectOptions();
      options.setCleanSession(true);

      //      client = new MqttClient("tcp://115.28.225.5:1883", "pahomqtt2");
      //      client.setCallback(new MqttCallback() {
      //
      //        public void messageArrived(String topic, MqttMessage msg) throws Exception {
      //          System.out.println("get topic : " + topic + " , msg: " + msg);
      //        }
      //
      //        public void deliveryComplete(IMqttDeliveryToken arg0) {
      //          // TODO Auto-generated method stub
      //
      //        }
      //
      //        public void connectionLost(Throwable arg0) {
      //          // TODO Auto-generated method stub
      //
      //        }
      //      });
      //      client.connect(options);
      //      client.subscribe(new String[]{"pahodemo"});
      //      Thread.sleep(3000);
      //      client.disconnect();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Override
  public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {

    if (MQTTMessageWrapper.isMyMessage(mqttMessage.toString())) return;

    String command = MQTTMessageWrapper.getCommand(mqttMessage.toString());
    switch (command) {
      case MQTTMessageWrapper.RcommandGetListDevice:
        // fine-tuning the GUI
        JSONObject jason = new JSONObject(mqttMessage.toString());

        JSONArray deviceList = jason.getJSONArray("devicesList");

        devices = new ArrayList<>();
        adapter.clear();

        for (int i = 0; i < deviceList.length(); i++) {
          JSONObject device = deviceList.getJSONObject(i);

          String friendlyName = (String) device.get("FriendlyName");
          // String index = new String(i + 1);

          devices.add(new Device(i + 1, friendlyName + " " + String.valueOf(i + 1), false, true));

          // Iterate through the elements of the array i.
          // Get thier value.
          // Get the value for the first element and the value for the last element.
        }

        //                String friendlyName = (String) jason.get("FriendlyName");

        // devices.add(new Device(1, "Z-Wave Light Bulb 1", false, true));
        // devices.add(new Device(1, "Z-Wave Light Bulb 2", false, true));

        ListView list = (ListView) findViewById(R.id.list);
        adapter = new Adapter(this, devices);
        list.setAdapter(adapter);

        break;
      case MQTTMessageWrapper.RcommandAddDevice:
        // Add new device
        break;
      default:
        break;
    }

    Log.d(TAG, "Received data from topic: " + topic + ", Mqtt message: " + mqttMessage.toString());
    if (adapter != null) {
      Device device = adapter.getItem(0);
      if (mqttMessage.toString().equals("on")) {
        device.setTurnOn(true);
      } else if (mqttMessage.toString().equals("off")) {
        device.setTurnOn(false);
      }
      adapter.notifyDataSetChanged();
    }
  }