/**
  * 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);
   }
 }
Exemplo n.º 2
0
 @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);
 }
  @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));
      }
    }
  }
Exemplo n.º 4
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 + ")");
    }
  }
  @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
          }
        });
  }
  @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);
      }
    }
  }
 /** @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 mqttMessage) throws Exception {
    s_logger.info(
        "mqtt message arrived. message "
            + topic
            + ":'"
            + new String(mqttMessage.getPayload())
            + "' qos="
            + mqttMessage.getQos()
            + " retained="
            + mqttMessage.isRetained());

    final String message = new String(mqttMessage.getPayload());
    final int qos = mqttMessage.getQos();
    final boolean retained = mqttMessage.isRetained();
    final Date received = new Date();

    if (m_session != null) {
      // prevent blocking of modal thread
      new ClientAsyncJob("mqtt message arrived (async wrapper)", m_session, true) {
        @Override
        protected void runVoid(IProgressMonitor monitor) throws Exception {
          // implement ui changes in a sync job
          new ClientSyncJob("mqtt message arrived", m_session) {
            @Override
            protected void runVoid(IProgressMonitor monitor1) throws Throwable {
              MessageHandlingService service = SERVICES.getService(MessageHandlingService.class);
              service.handleMessage(topic, message, qos, retained, received);
            }
          }.schedule();
        }
      }.schedule();
    } else {
      s_logger.error("client session is null");
    }
  }
Exemplo n.º 9
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;
  }
Exemplo n.º 11
0
 @Override
 public void messageArrived(String topic, MqttMessage message) throws Exception {
   if (topic.equals(currentTopic)) {
     String msg = new String(message.getPayload());
     Log.v(LOG_TAG, "mqtt message arrived: " + msg);
     // process message
     JSONObject o = new JSONObject(msg);
     String sender = o.optString("sender", null);
     // ignore our own messages, so check sender
     if (sender != null && !sender.equals(clientId)) {
       // somebody else sent their viruses
       JSONArray a = o.getJSONArray("viruses");
       for (int i = 0; i < a.length(); i++) {
         Virus v = VirusFactory.fromJSON(a.getJSONObject(i));
         addVirus(v);
       }
       // was the other user just entering our region?
       if (o.optString("entering", null) != null) {
         // send our infection
         sendInfectionMessage(false);
       }
     }
   }
 }
Exemplo n.º 12
0
  @Override
  public void messageArrived(String topic, MqttMessage message) {
    try {

      Stopwatch sw = Stopwatch.createStarted();

      String msg = new String(message.getPayload());
      JsonParser parser = new JsonParser();
      JsonObject object = parser.parse(msg).getAsJsonObject();

      // XXX: workaround for demo!!!!
      String sensorId = topic;
      String[] segments = topic.split("/");
      if (segments.length > 2) {
        sensorId = segments[1] + segments[2];
      }

      long elapsed = sw.elapsed(TimeUnit.MILLISECONDS);
      if (elapsed > 5) {
        System.out.println("Phase parse: " + elapsed);
      }
      sw.reset();

      // Use IncQuery Base Indexer to find the sensor
      Sensor selectedSensor =
          (Sensor) navigationHelper.findByAttributeValue(sensorId).iterator().next().getEObject();

      elapsed = sw.elapsed(TimeUnit.MILLISECONDS);
      if (elapsed > 10) {
        System.out.println("Phase indexer: " + elapsed);
      }

      Payload sensorPayload = selectedSensor.getLastReceivedPayload();

      NavigationHelper paramNavHelper =
          IncQueryBaseFactory.getInstance().createNavigationHelper(sensorPayload, true, null);
      // Get parameters from model using the JSON file content
      for (Entry<String, JsonElement> parameter : object.entrySet()) {
        // Use IncQuery Base Indexer to find parameter
        Set<Setting> settings = paramNavHelper.findByAttributeValue(parameter.getKey());
        if (settings.isEmpty()) continue;

        DataParameter paramValue = (DataParameter) settings.iterator().next().getEObject();
        // Get the parameter new value from the message
        JsonElement newValue = parameter.getValue();
        // Find parameter type, and set the new value
        if (paramValue.getType().equals("int")) {
          ((IntParameter) paramValue).setValue(newValue.getAsInt());
        } else if (paramValue.getType().equals("double")) {
          ((DoubleParameter) paramValue).setValue(newValue.getAsDouble());
        } else if (paramValue.getType().equals("string")) {
          ((StringParameter) paramValue).setValue(newValue.getAsString());
        } else if (paramValue.getType().equals("boolean")) {
          ((BooleanParameter) paramValue).setValue(newValue.getAsBoolean());
        } else if (paramValue.getType().equals("long")) {
          ((LongParameter) paramValue).setValue(newValue.getAsLong());
        }
      }

      elapsed = sw.elapsed(TimeUnit.MILLISECONDS);
      if (elapsed > 10) {
        System.out.println("Phase update: " + elapsed);
      }

    } catch (Exception e) {
      LOGGER.error(e.getMessage());
    }
  }
 /**
  * @see org.eclipse.paho.client.mqttv3.MqttCallback#messageArrived(java.lang.String,
  *     org.eclipse.paho.client.mqttv3.MqttMessage)
  */
 @Override
 public void messageArrived(String topic, MqttMessage message) throws Exception {
   String msg_payload = new String(message.getPayload());
   String toast_msg = "Message Arrived -> " + topic + " : " + msg_payload;
   Notify.toast(context, toast_msg, Toast.LENGTH_LONG);
 }
Exemplo n.º 14
0
 ParcelableMqttMessage(MqttMessage original) {
   super(original.getPayload());
   setQos(original.getQos());
   setRetained(original.isRetained());
   setDuplicate(original.isDuplicate());
 }
Exemplo n.º 15
0
 @Override
 public void messageArrived(String topic, MqttMessage message) throws Exception {
   Log.d(TAG, "Message arrived in " + topic + ": " + message.getPayload().toString());
 }
Exemplo n.º 16
0
  protected IMqttDeliveryToken publish(DeviceTopic topic, MqttMessage message)
      throws MqttException {
    final String METHOD = "publish";
    IMqttDeliveryToken token = null;
    LoggerUtility.fine(CLASS_NAME, METHOD, "Topic(" + topic + ")");
    while (true) {
      if (isConnected()) {
        try {
          if (this.mqttAsyncClient != null) {
            token = mqttAsyncClient.publish(topic.getName(), message);
          } else if (mqttClient != null) {
            mqttClient.publish(topic.getName(), message);
          }
        } catch (MqttException ex) {
          String payload = null;
          try {
            payload = new String(message.getPayload(), "UTF-8");
          } catch (UnsupportedEncodingException e1) {
          }
          if (this.mqttAsyncClient.isConnected() == false) {
            LoggerUtility.log(
                Level.WARNING,
                CLASS_NAME,
                METHOD,
                " Connection Lost retrying to publish MSG :"
                    + payload
                    + " on topic "
                    + topic
                    + " every 5 seconds");

            // 	wait for 5 seconds and retry
            try {
              Thread.sleep(5 * 1000);
              continue;
            } catch (InterruptedException e) {
            }
          } else {
            throw ex;
          }
        }

        if (isConnected() == false) {
          LoggerUtility.log(
              Level.WARNING,
              CLASS_NAME,
              METHOD,
              "MQTT got disconnected " + "after publish to Topic(" + topic + ")");
        }
        return token;
      } else {
        LoggerUtility.warn(
            CLASS_NAME,
            METHOD,
            ": Will not publish to topic(" + topic + ") because MQTT client is not connected.");
        try {
          Thread.sleep(5 * 1000);
          continue;
        } catch (InterruptedException e) {
        }
      }
    }
  }