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

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttMessage#setQos() . 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: AsyncClient.java    From mqtt-jmeter with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void publish(String topicName, int qos, byte[] payload, boolean isRetained) throws MqttException {
    // Construct the message to send
    MqttMessage message = new MqttMessage(payload);
    message.setRetained(isRetained);
    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.info("Published");
}
 
Example 2
Source File: MqttClientHandler.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private int publish(String strTopic, byte[] contents) throws Exception {
		
		log.debug("PUBLISH] topic=" + strTopic + ", contents=" + new String(contents, "UTF-8"));
		
//		MqttTopic mqttTopic = mqttClient.getTopic(strTopic);

		MqttMessage message = new MqttMessage(contents);
		message.setQos(pubQoS);
		message.setRetained(false);

		mqttClient.publish(strTopic, message);
		
		return 1;
		
//		MqttDeliveryToken token = null;
//		token = mqttTopic.publish(message);
//		token.waitForCompletion();
//
//		log.debug("[MqttClientHandler.publish] publish. topic : " + strTopic);
//		
//		return token.getMessageId();
	}
 
Example 3
Source File: MqttClusterMQ.java    From dew with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doPublish(String topic, String message, Optional<Map<String, Object>> header, boolean confirm) {
    try {
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        if (confirm) {
            mqttMessage.setQos(1);
        } else {
            mqttMessage.setQos(0);
        }
        mqttAdapter.getClient().publish(topic, mqttMessage);
        return true;
    } catch (MqttException e) {
        logger.error("[MQ] Mqtt publish error.", e);
        return false;
    }
}
 
Example 4
Source File: MQTT_PVConn.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
public void publishTopic(String topicStr, String pubMsg, int pubQoS, boolean retained) throws Exception
{
    if (!connect())
    {
        PV.logger.log(Level.WARNING, "Could not publish to mqtt topic \"" + topicStr
                + "\" due to no broker connection");
        throw new Exception("MQTT publish failed: no broker connection");
    }

    MqttTopic topic = myClient.getTopic(topicStr);
    MqttMessage message = new MqttMessage(pubMsg.getBytes());
    message.setQos(pubQoS);
    message.setRetained(retained);

    MqttDeliveryToken token = null;
    try {
        // publish message to broker
        token = topic.publish(message);
        // Wait until the message has been delivered to the broker
        token.waitForCompletion();
        Thread.sleep(100);
    } catch (Exception ex) {
        throw new Exception("Failed to publish message to broker", ex);
    }
}
 
Example 5
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized void publishTopic(final String applicationId, final String status, final String loggedInUserId, final String userId) {
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setRetained(false);
        message.setPayload((applicationId + "," + User.getEncodedUserId(loggedInUserId) + "," + status).getBytes());
        message.setQos(0);
        client.publish("typing" + "-" + applicationId + "-" + User.getEncodedUserId(userId), message);
        Utils.printLog(context, TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + User.getEncodedUserId(userId));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: MqttPublisher.java    From quarks with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(T t) {
    // right now, the caller of accept() doesn't do anything to
    // log or tolerate an unwind. address those issues here.
    String topicStr = topic.apply(t);
    try {
        MqttMessage message = new MqttMessage(payload.apply(t));
        message.setQos(qos.apply(t));
        message.setRetained(retain.apply(t));
        logger.trace("{} sending to topic:{}", id(), topicStr);
        connector.notIdle();
        connector.client().publish(topicStr, message);
    } catch (Exception e) {
        logger.error("{} sending to topic:{} failed.", id(), topicStr, e);
    }
}
 
Example 7
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
protected static void sendDataFromDevice(
    MqttClient client, String deviceId, String messageType, String data)
    throws MqttException, UnsupportedEncodingException {
  // [START send_data_from_bound_device]
  if (!"events".equals(messageType) && !"state".equals(messageType)) {
    System.err.println("Invalid message type, must ether be 'state' or events'");
    return;
  }
  final String dataTopic = String.format("/devices/%s/%s", deviceId, messageType);
  MqttMessage message = new MqttMessage(data.getBytes(StandardCharsets.UTF_8.name()));
  message.setQos(1);
  client.publish(dataTopic, message);
  System.out.println("Data sent");
  // [END send_data_from_bound_device]
}
 
Example 8
Source File: MQTTWrapper.java    From lwm2m_over_mqtt with Eclipse Public License 1.0 5 votes vote down vote up
public void publish(String topic, String content) {
	try {
		MqttMessage message = new MqttMessage(content.getBytes());
           message.setQos(QOS);
           LOG.info("publish :: {"+topic+" ["+message+" ]}");
		mqttClient.publish(topic, message);
	} catch (MqttException me) {
		LOG.error("reason "+me.getReasonCode());
		LOG.error("msg "+me.getMessage());
		LOG.error("loc "+me.getLocalizedMessage());
		LOG.error("cause "+me.getCause());
		LOG.error("excep "+me);
           me.printStackTrace();
	}
}
 
Example 9
Source File: MqttAdapterClient.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public boolean send(int qos, final MessageSendTester.Type type, final Buffer json, final Duration timeout) {
    final MqttMessage message = new MqttMessage(json.getBytes());
    message.setQos(qos);
    try {
        final IMqttDeliveryToken token = this.adapterClient.publish(type.type().address(), message);
        if (qos <= 0) {
            return true; // we know nothing with QoS 0
        }
        token.waitForCompletion(timeout.toMillis());
    } catch (Exception e) {
        log.info("Failed to send MQTT message", e);
        return false;
    }
    return true;
}
 
Example 10
Source File: ApplicationClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Publish event, on the behalf of a device, to the IBM Watson IoT Platform.
 * <br>
 * This method will attempt to create a JSON obejct out of the payload
 * 
 * @param typeId   object of String which denotes deviceType
 * @param deviceId object of String which denotes deviceId
 * @param eventId  object of String which denotes event
 * @param data     Payload data
 * @param qos      Quality of Service, in int - can have values 0,1,2
 * 
 * @return Whether the send was successful.
 */
@SuppressWarnings("unchecked")
public boolean publishEvent(String typeId, String deviceId, String eventId, Object data, int qos) {
	if (data == null) {
		throw new NullPointerException("Data object for event publish can not be null");
	}

	// Find the codec for the data class
	@SuppressWarnings("rawtypes")
	MessageCodec codec = messageCodecs.get(data.getClass());

	// Check that a codec is registered
	if (codec == null) {
		LOG.warn("Unable to encode event data of class " + data.getClass().getName());
		return false;
	}

	byte[] payload = codec.encode(data, new DateTime());
	String topic = "iot-2/type/" + typeId + "/id/" + deviceId + "/evt/" + eventId + "/fmt/"
			+ codec.getMessageFormat();
	LOG.debug("Publishing event to " + topic);

	MqttMessage msg = new MqttMessage(payload);
	msg.setQos(qos);
	msg.setRetained(false);

	try {
		mqttAsyncClient.publish(topic, msg);
	} catch (MqttException e) {
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example 11
Source File: Engine.java    From winthing with Apache License 2.0 5 votes vote down vote up
private MqttMessage serialize(final Message message) {
    final byte[] payload;
    if (message.getPayload().isPresent()) {
        payload = gson.toJson(message.getPayload().get()).getBytes(CHARSET);
    } else {
        payload = new byte[0];
    }
    final MqttMessage mqttMessage = new MqttMessage(payload);
    mqttMessage.setQos(message.getQualityOfService().ordinal());
    mqttMessage.setRetained(message.isRetained());
    return mqttMessage;
}
 
Example 12
Source File: MQTTProducer.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private MqttMessage getMessage( Object[] row ) throws KettleStepException {
  MqttMessage mqttMessage = new MqttMessage();
  try {
    mqttMessage.setQos( Integer.parseInt( meta.qos ) );
  } catch ( NumberFormatException e ) {
    throw new KettleStepException(
      getString( PKG, "MQTTProducer.Error.QOS", meta.qos ) );
  }
  //noinspection ConstantConditions
  mqttMessage.setPayload( getFieldData( row, meta.messageField )
    .map( this::dataAsBytes )
    .orElse( null ) ); //allow nulls to pass through
  return mqttMessage;
}
 
Example 13
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
protected static void attachDeviceToGateway(MqttClient client, String deviceId)
    throws MqttException, UnsupportedEncodingException {
  // [START iot_attach_device]
  final String attachTopic = String.format("/devices/%s/attach", deviceId);
  System.out.println(String.format("Attaching: %s", attachTopic));
  String attachPayload = "{}";
  MqttMessage message = new MqttMessage(attachPayload.getBytes(StandardCharsets.UTF_8.name()));
  message.setQos(1);
  client.publish(attachTopic, message);
  // [END iot_attach_device]
}
 
Example 14
Source File: Producer.java    From jmqtt with Apache License 2.0 4 votes vote down vote up
private static MqttMessage getMqttMessage(){
    MqttMessage mqttMessage = new MqttMessage(content.getBytes());
    mqttMessage.setQos(qos);
    return mqttMessage;
}
 
Example 15
Source File: PublishMQTT.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowfile = session.get();
    if (flowfile == null) {
        return;
    }

    if(mqttClient == null || !mqttClient.isConnected()){
        logger.info("Was disconnected from client or was never connected, attempting to connect.");
        try {
            reconnect();
        } catch (MqttException e) {
            context.yield();
            session.transfer(flowfile, REL_FAILURE);
            logger.error("MQTT client is disconnected and re-connecting failed. Transferring FlowFile to fail and yielding", e);
            return;
        }
    }

    // get the MQTT topic
    String topic = context.getProperty(PROP_TOPIC).evaluateAttributeExpressions(flowfile).getValue();

    if (topic == null || topic.isEmpty()) {
        logger.warn("Evaluation of the topic property returned null or evaluated to be empty, routing to failure");
        session.transfer(flowfile, REL_FAILURE);
        return;
    }

    // do the read
    final byte[] messageContent = new byte[(int) flowfile.getSize()];
    session.read(flowfile, new InputStreamCallback() {
        @Override
        public void process(final InputStream in) throws IOException {
            StreamUtils.fillBuffer(in, messageContent, true);
        }
    });

    int qos = context.getProperty(PROP_QOS).evaluateAttributeExpressions(flowfile).asInteger();
    final MqttMessage mqttMessage = new MqttMessage(messageContent);
    mqttMessage.setQos(qos);
    mqttMessage.setPayload(messageContent);
    mqttMessage.setRetained(context.getProperty(PROP_RETAIN).evaluateAttributeExpressions(flowfile).asBoolean());

    try {
        mqttClientConnectLock.readLock().lock();
        final StopWatch stopWatch = new StopWatch(true);
        try {
            /*
             * Underlying method waits for the message to publish (according to set QoS), so it executes synchronously:
             *     MqttClient.java:361 aClient.publish(topic, message, null, null).waitForCompletion(getTimeToWait());
             */
            mqttClient.publish(topic, mqttMessage);
        } finally {
            mqttClientConnectLock.readLock().unlock();
        }

        session.getProvenanceReporter().send(flowfile, broker, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
        session.transfer(flowfile, REL_SUCCESS);
    } catch(MqttException me) {
        logger.error("Failed to publish message.", me);
        session.transfer(flowfile, REL_FAILURE);
    }
}
 
Example 16
Source File: AndroidSenseEnrollment.java    From product-iots with Apache License 2.0 4 votes vote down vote up
@Test(description = "Test an Android sense device data publishing.", dependsOnMethods = {"testEnrollment"})
    public void testEventPublishing() throws Exception {
        String DEVICE_TYPE = "android_sense";
        String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + DEVICE_ID + "/data";
        int qos = 2;
        String broker = "tcp://localhost:1886";
        String clientId = DEVICE_ID + ":" + DEVICE_TYPE;
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName(accessToken);
        connOpts.setPassword("".toCharArray());
        connOpts.setKeepAliveInterval(120);
        connOpts.setCleanSession(true);
        log.info("Connecting to broker: " + broker);
        sampleClient.connect(connOpts);
        log.info("Connected");
        MqttMessage message = new MqttMessage(PayloadGenerator
                .getJsonArray(Constants.AndroidSenseEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME,
                        Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION).toString().getBytes());
        message.setQos(qos);
        for (int i = 0; i< 100 ; i++) {
            sampleClient.publish(topic, message);
            log.info("Message is published to Mqtt Client");
            Thread.sleep(1000);
        }
        sampleClient.disconnect();

        HttpResponse response = analyticsClient
                .get(Constants.AndroidSenseEnrollment.IS_TABLE_EXIST_CHECK_URL + "?table="
                        + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME);
        Assert.assertEquals("ORG_WSO2_IOT_ANDROID_BATTERY_STATS table does not exist. Problem with the android sense "
                                    + "analytics", HttpStatus.SC_OK, response.getResponseCode());
        // Allow some time to perform the analytics tasks.

        log.info("Mqtt Client is Disconnected");

        String url = Constants.AndroidSenseEnrollment.RETRIEVER_ENDPOINT
                + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME + "/";
        Timestamp timestamp = new Timestamp(System.currentTimeMillis() - 3600000);
        url += timestamp.getTime() + "/" + new Timestamp(System.currentTimeMillis()).getTime() + "/0/100";
        response = analyticsClient.get(url);
        JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonArray();
        //TODO: temporarily commenting out untill new changes are merged
//        Assert.assertEquals(
//                "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
//                HttpStatus.SC_OK, response.getResponseCode());
//        Assert.assertTrue(
//                "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
//                jsonArray.size() > 0);
    }
 
Example 17
Source File: MqttAndroidClient.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Publishes a message to a topic on the server.
 * <p>
 * A convenience method, which will create a new {@link MqttMessage} object
 * with a byte array payload, the specified QoS and retained, then publish it.
 * </p>
 * 
 * @param topic
 *            to deliver the message to, for example "finance/stock/ibm".
 * @param payload
 *            the byte array to use as the payload
 * @param qos
 *            the Quality of Service to deliver the message at. Valid values
 *            are 0, 1 or 2.
 * @param retained
 *            whether or not this message should be retained by the server.
 * @param userContext
 *            optional object used to pass context to the callback. Use null
 *            if not required.
 * @param callback
 *            optional listener that will be notified when message delivery
 *            has completed to the requested quality of service
 * @return token used to track and wait for the publish to complete. The
 *         token will be passed to any callback that has been set.
 * @throws MqttPersistenceException
 *             when a problem occurs storing the message
 * @throws IllegalArgumentException
 *             if value of QoS is not 0, 1 or 2.
 * @throws MqttException
 *             for other errors encountered while publishing the message.
 *             For instance client not connected.
 * @see #publish(String, MqttMessage, Object, IMqttActionListener)
 */
@Override
public IMqttDeliveryToken publish(String topic, byte[] payload, int qos,
		boolean retained, Object userContext, IMqttActionListener callback)
		throws MqttException, MqttPersistenceException {

	MqttMessage message = new MqttMessage(payload);
	message.setQos(qos);
	message.setRetained(retained);
	MqttDeliveryTokenAndroid token = new MqttDeliveryTokenAndroid(
			this, userContext, callback, message);
	String activityToken = storeToken(token);
	IMqttDeliveryToken internalToken = mqttService.publish(clientHandle,
			topic, payload, qos, retained, null, activityToken);
	token.setDelegate(internalToken);
	return token;
}
 
Example 18
Source File: SimpleClient4IOT.java    From rpi with Apache License 2.0 4 votes vote down vote up
public void sendMessage(String content) throws MqttException, UnsupportedEncodingException {
//        String content = "{'content':'msg from :" + clientId + "," + System.currentTimeMillis() + "'}";
        MqttMessage message = new MqttMessage(content.getBytes("utf-8"));
        message.setQos(0);
        sampleClient.publish(config.pubTopic, message);
    }
 
Example 19
Source File: PublishMQTT.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowfile = session.get();
    if (flowfile == null) {
        return;
    }

    if (!isConnected()){
        synchronized (this) {
            if (!isConnected()) {
                initializeClient(context);
            }
        }
    }

    // get the MQTT topic
    String topic = context.getProperty(PROP_TOPIC).evaluateAttributeExpressions(flowfile).getValue();

    if (topic == null || topic.isEmpty()) {
        logger.warn("Evaluation of the topic property returned null or evaluated to be empty, routing to failure");
        session.transfer(flowfile, REL_FAILURE);
        return;
    }

    // do the read
    final byte[] messageContent = new byte[(int) flowfile.getSize()];
    session.read(flowfile, new InputStreamCallback() {
        @Override
        public void process(final InputStream in) throws IOException {
            StreamUtils.fillBuffer(in, messageContent, true);
        }
    });

    int qos = context.getProperty(PROP_QOS).evaluateAttributeExpressions(flowfile).asInteger();
    final MqttMessage mqttMessage = new MqttMessage(messageContent);
    mqttMessage.setQos(qos);
    mqttMessage.setPayload(messageContent);
    mqttMessage.setRetained(context.getProperty(PROP_RETAIN).evaluateAttributeExpressions(flowfile).asBoolean());

    try {
        final StopWatch stopWatch = new StopWatch(true);
        /*
         * Underlying method waits for the message to publish (according to set QoS), so it executes synchronously:
         *     MqttClient.java:361 aClient.publish(topic, message, null, null).waitForCompletion(getTimeToWait());
         */
        mqttClient.publish(topic, mqttMessage);

        session.getProvenanceReporter().send(flowfile, broker, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
        session.transfer(flowfile, REL_SUCCESS);
    } catch(MqttException me) {
        logger.error("Failed to publish message.", me);
        session.transfer(flowfile, REL_FAILURE);
    }
}
 
Example 20
Source File: MqttProducer.java    From iot-ocp with Apache License 2.0 3 votes vote down vote up
public void run(String topic, String data) throws MqttPersistenceException, MqttException {
	
	MqttMessage message = new MqttMessage();
	message.setQos(QOS);
	
	message.setPayload(data.getBytes());
	client.publish(topic, message);
			
}