Java Code Examples for org.eclipse.paho.client.mqttv3.MqttMessage#getPayload()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttMessage#getPayload() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UartModeFragment.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
@MainThread
@Override
public void onMqttMessageArrived(String topic, @NonNull MqttMessage mqttMessage) {
    if (!(mUartData instanceof UartPacketManager)) {
        Log.e(TAG, "Error send with invalid uartData class");
        return;
    }
    if (mBlePeripheralsUart.size() == 0) {
        Log.e(TAG, "mBlePeripheralsUart not initialized");
        return;
    }

    BlePeripheralUart blePeripheralUart = mBlePeripheralsUart.get(0);
    final String message = new String(mqttMessage.getPayload());

    ((UartPacketManager) mUartData).send(blePeripheralUart, message, true);          // Don't republish to mqtt something received from mqtt

    /*
    mMainHandler.post(new Runnable() {
        @Override
        public void run() {

        }
    })*/
}
 
Example 2
Source File: SubscriberActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 6 votes vote down vote up
/**
 * 运行在主线程
 * @param event
 */
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
    String string = event.getString();
    /**接收到服务器推送的信息,显示在右边*/
    if("".equals(string)){
        String topic = event.getTopic();
        MqttMessage mqttMessage = event.getMqttMessage();
        String s = new String(mqttMessage.getPayload());
        topic=topic+" : "+s;
        subcriberAdapter.addListDate(new Message(topic,false));
    /**接收到订阅成功的通知,订阅成功,显示在左边*/
    }else{
        subcriberAdapter.addListDate(new Message("Me : "+string,true));
    }


}
 
Example 3
Source File: PublishActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 6 votes vote down vote up
/**
 * 运行在主线程
 * @param event
 */
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
    String string = event.getString();
    /**接收到服务器推送的信息,显示在右边*/
    if("".equals(string)){
        String topic = event.getTopic();
        MqttMessage mqttMessage = event.getMqttMessage();
        String s = new String(mqttMessage.getPayload());
        topic=topic+" : "+s;
        subcriberAdapter.addListDate(new Message(topic,false));
        /**接收到订阅成功的通知,订阅成功,显示在左边*/
    }else{
        subcriberAdapter.addListDate(new Message("Me : "+string,true));
    }
}
 
Example 4
Source File: ChatActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 6 votes vote down vote up
/**
 * 运行在主线程
 * @param event
 */
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
    String string = event.getString();
    /**接收到服务器推送的信息,显示在右边*/
    if("".equals(string)){
        String topic = event.getTopic();
        MqttMessage mqttMessage = event.getMqttMessage();
        String s = new String(mqttMessage.getPayload());
        topic=topic+" : "+s;
        subcriberAdapter.addListDate(new Message(topic,false));
        /**接收到订阅成功的通知,订阅成功,显示在左边*/
    }else{
        subcriberAdapter.addListDate(new Message("Me : "+string,true));
    }
}
 
Example 5
Source File: ClientCallback.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void messageArrived(String topic, MqttMessage message) {
    byte[] payload = message.getPayload();
    logger.trace("Received message on topic '{}' : {}", topic, new String(payload));
    List<MqttMessageSubscriber> matches = new ArrayList<>();
    synchronized (subscribers) {
        subscribers.values().forEach(subscriberList -> {
            if (topic.matches(subscriberList.regexMatchTopic)) {
                logger.trace("Topic match for '{}' using regex {}", topic, subscriberList.regexMatchTopic);
                subscriberList.forEach(consumer -> matches.add(consumer));
            } else {
                logger.trace("No topic match for '{}' using regex {}", topic, subscriberList.regexMatchTopic);

            }
        });

    }
    try {
        matches.forEach(subscriber -> subscriber.processMessage(topic, payload));
    } catch (Exception e) {
        logger.error("MQTT message received. MqttMessageSubscriber#processMessage() implementation failure", e);
    }
}
 
Example 6
Source File: Connection.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
public void messageArrived(String topic, MqttMessage message){
    ReceivedMessage msg = new ReceivedMessage(topic, message);
    messageHistory.add(0, msg);
    if(subscriptions.containsKey(topic)){
        subscriptions.get(topic).setLastMessage(new String(message.getPayload()));
        if(subscriptions.get(topic).isEnableNotifications()){
            //create intent to start activity
            Intent intent = new Intent();
            intent.setClassName(context, activityClass);
            intent.putExtra("handle", clientHandle);

            //format string args
            Object[] notifyArgs = new String[3];
            notifyArgs[0] = this.getId();
            notifyArgs[1] = new String(message.getPayload());
            notifyArgs[2] = topic;

            //notify the user
            //Notify.notifcation(context, context.getString(R.string.notification, notifyArgs), intent, R.string.notifyTitle);
            Notify.notifcation(context, "Message arrived on " + topic, intent, R.string.notifyTitle);
        }
    }

    for(IReceivedMessageListener listener : receivedMessageListeners){
        listener.onMessageReceived(msg);
    }
}
 
Example 7
Source File: Utf8Codec.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Utf8Message decode(MqttMessage msg) throws MalformedMessageException {
	String data;
	try {
		data = new String(msg.getPayload(), "UTF8");
	} catch (UnsupportedEncodingException e) {
		throw new MalformedMessageException("Unable to decode string as UTF-8: " + e.toString());
	}
	return new Utf8Message(data, null);
}
 
Example 8
Source File: Bridge.java    From MQTTKafkaBridge with Apache License 2.0 5 votes vote down vote up
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
	
	byte[] payload = message.getPayload();
	System.out.println(new String(message.getPayload()));
	//Updated based on Kafka v0.8.1.1
	KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, new String(message.getPayload()));
	kafkaProducer.send(data);
}
 
Example 9
Source File: EmqMessage.java    From EMQ-Android-Toolkit with Apache License 2.0 5 votes vote down vote up
public EmqMessage(String topic, MqttMessage mqttMessage) {
    this.topic = topic;
    this.mqttMessage = mqttMessage;
    this.updateTime = StringUtil.formatNow();

    if (mqttMessage != null) {
        this.dup = mqttMessage.isDuplicate();
        this.payload = new String(mqttMessage.getPayload());
        this.qos = mqttMessage.getQos();
        this.messageId = mqttMessage.getId();
        this.retained = mqttMessage.isRetained();
    }


}
 
Example 10
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Attaches the callback used when configuration changes occur. */
protected static void attachCallback(MqttClient client, String deviceId)
    throws MqttException, UnsupportedEncodingException {
  mCallback =
      new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
          // Do nothing...
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) {
          try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8.name());
            System.out.println("Payload : " + payload);
            // TODO: Insert your parsing / handling of the configuration message here.
            //
          } catch (UnsupportedEncodingException uee) {
            System.err.println(uee);
          }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
          // Do nothing;
        }
      };

  String commandTopic = String.format("/devices/%s/commands/#", deviceId);
  System.out.println(String.format("Listening on %s", commandTopic));

  String configTopic = String.format("/devices/%s/config", deviceId);
  System.out.println(String.format("Listening on %s", configTopic));

  client.subscribe(configTopic, 1);
  client.subscribe(commandTopic, 1);
  client.setCallback(mCallback);
}
 
Example 11
Source File: TrainLocationClient.java    From osgi.iot.contest.sdk with Apache License 2.0 5 votes vote down vote up
@Override
        public void messageArrived(String topic, MqttMessage msg) throws Exception {
//            info("messageArrived on topic=<{}>: {}", topic, msg);

            byte[] payload = msg.getPayload();
            String json = new String(payload);

            if (!json.startsWith("{")) {
                // json: TRAIN1=DisConnected
                String[] split = json.split("=", 2);
                info("connection: train={}, status={}", split[0], split[1]);
                return;
            }

            // json: {"train":"TRAIN1","location":"010E9EF905","time":"432"}
            @SuppressWarnings("unchecked")
            Map<String, Object> map = dtos.decoder(Map.class).get(new ByteArrayInputStream(payload));
            info("location: {}", map);

            String trainId = (String) map.get("train");
            String location = (String) map.get("location");

            if (location != null) {
                String tag = location.toString();
                Integer code = tag2code.get(tag);
                if (code == null || code == 0) {
                    warn("unknown tag <{}>", tag);
                } else {
                    String segment = code2segment.get(code);
                    if (segment == null) {
                        warn("no segment defined for code <{}>", code);
                    } else {
                        trigger(trainId, segment);
                    }
                }
            }
        }
 
Example 12
Source File: MQTTQueueMessage.java    From nifi with Apache License 2.0 5 votes vote down vote up
public MQTTQueueMessage(String topic, MqttMessage message) {
    this.topic = topic;
    payload = message.getPayload();
    qos = message.getQos();
    retained = message.isRetained();
    duplicate = message.isDuplicate();
}
 
Example 13
Source File: MQTTQueueMessage.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public MQTTQueueMessage(String topic, MqttMessage message) {
    this.topic = topic;
    payload = message.getPayload();
    qos = message.getQos();
    retained = message.isRetained();
    duplicate = message.isDuplicate();
}
 
Example 14
Source File: Response.java    From lwm2m_over_mqtt with Eclipse Public License 1.0 5 votes vote down vote up
public Response(MqttMessage message) {
	String msg = null;
	try {
		msg = new String(message.getPayload(), "UTF-8");
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	String[] data = msg.split(" ", 2);
	this.payload = data[1];
	this.responseCode = Float.valueOf(data[0]);
}
 
Example 15
Source File: PushCallback.java    From onenet-iot-project with MIT License 4 votes vote down vote up
@Override
public void messageArrived(String topic, MqttMessage message) throws InvalidProtocolBufferException {
    byte[] payload = message.getPayload();
    OnenetMq.Msg obj = OnenetMq.Msg.parseFrom(payload);
    service.execute(() -> handler.handle(obj.getMsgid(), new String(obj.getData().toByteArray())));
}
 
Example 16
Source File: DatabaseMessageStore.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 17
Source File: MqttConfig.java    From quarks with Apache License 2.0 4 votes vote down vote up
/**
 * Get a Last Will and Testament message's payload.
 * @return the value. may be null.
 */
public byte[] getWillPayload() {
    MqttMessage msg = options.getWillMessage();
    return msg==null ? null : msg.getPayload();
}
 
Example 18
Source File: ParcelableMqttMessage.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
ParcelableMqttMessage(MqttMessage original) {
  super(original.getPayload());
  setQos(original.getQos());
  setRetained(original.isRetained());
  setDuplicate(original.isDuplicate());
}
 
Example 19
Source File: SensorsManager.java    From MQTT-Essentials-A-Lightweight-IoT-Protocol with MIT License 4 votes vote down vote up
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
	String messageText = new String(message.getPayload(), encoding);
	System.out.println(
		String.format("Topic: %s. Payload: %s",
			topic,
			messageText));
	// A message has arrived from the MQTT broker
	// The MQTT broker doesn't send back 
	// an acknowledgment to the server until 
	// this method returns cleanly
	if (!topic.startsWith(boardCommandsTopic)) {
		// The topic for the arrived message doesn't start with boardTopic
		return;
	}
	final boolean isTurnOnMessage = messageText.equals("TURN ON"); 
	final boolean isTurnOffMessage = messageText.equals("TURN OFF");
	boolean isInvalidCommand = false;
	boolean isInvalidTopic = false;
	// Extract the sensor name from the topic
	String sensorName = topic.replaceFirst(boardCommandsTopic, "").replaceFirst(TOPIC_SEPARATOR, "");
	switch (sensorName) {
		case SENSOR_SUNLIGHT:
			if (isTurnOnMessage) {
				isSunlightSensorTurnedOn = true;
			} else if (isTurnOffMessage) {
				isSunlightSensorTurnedOn = false;
			} else {
				isInvalidCommand = true;
			}
			break;
		case SENSOR_EARTH_HUMIDITY:
			if (isTurnOnMessage) {
				isEarthHumiditySensorTurnedOn = true;
			} else if (isTurnOffMessage) {
				isEarthHumiditySensorTurnedOn = false;
			} else {
				isInvalidCommand = true;
			}
			break;
		default:
			isInvalidTopic = true;
	}
	if (!isInvalidCommand && !isInvalidTopic) {
		publishProcessedCommandMessage(sensorName, messageText);	
	}
}
 
Example 20
Source File: MqttData.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public MqttData ( final MqttMessage msg )
{
    super ( msg.getPayload (), null );
    this.message = msg;
}