Search in sources :

Example 1 with MqttTopic

use of org.eclipse.paho.client.mqttv3.MqttTopic in project openhab1-addons by openhab.

the class MqttBrokerConnection method startProducer.

/**
     * Start a registered producer, so that it can start sending messages.
     * 
     * @param publisher
     *            to start.
     */
private void startProducer(MqttMessageProducer publisher) {
    logger.trace("Starting message producer for broker '{}'", name);
    publisher.setSenderChannel(new MqttSenderChannel() {

        @Override
        public void publish(String topic, byte[] payload) throws Exception {
            if (!started) {
                logger.warn("Broker connection not started. Cannot publish message to topic '{}'", topic);
                return;
            }
            // Create and configure a message
            MqttMessage message = new MqttMessage(payload);
            message.setQos(qos);
            message.setRetained(retain);
            // publish message asynchronously
            MqttTopic mqttTopic = client.getTopic(topic);
            MqttDeliveryToken deliveryToken = mqttTopic.publish(message);
            logger.debug("Publishing message {} to topic '{}'", deliveryToken.getMessageId(), topic);
            if (!async) {
                // wait for publish confirmation
                deliveryToken.waitForCompletion(10000);
                if (!deliveryToken.isComplete()) {
                    logger.error("Did not receive completion message within timeout limit whilst publishing to topic '{}'", topic);
                }
            }
        }
    });
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttTopic(org.eclipse.paho.client.mqttv3.MqttTopic) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) MqttDeliveryToken(org.eclipse.paho.client.mqttv3.MqttDeliveryToken) MqttSenderChannel(org.openhab.io.transport.mqtt.MqttSenderChannel) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 2 with MqttTopic

use of org.eclipse.paho.client.mqttv3.MqttTopic in project transporter by wang4ever.

the class MqttProducer method configure.

public MqttProducer configure() {
    try {
        if (this.client != null) {
            logger.info("The initialized MQTT client producer. {}", this.client);
            return this;
        }
        // host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以文件保存
        this.client = new MqttClient(this.config.getHostUrl(), this.config.getClientId(MQClientId.MQ_P), new MemoryPersistence());
        // MQTT的连接设置
        this.options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
        this.options.setCleanSession(this.config.getProducerConfig().getCleanSession());
        this.options.setUserName(this.config.getUsername());
        this.options.setPassword(this.config.getPassword().toCharArray());
        // 设置超时时间 单位为秒
        this.options.setConnectionTimeout(this.config.getProducerConfig().getConnectionTimeout());
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
        this.options.setKeepAliveInterval(this.config.getProducerConfig().getKeepAliveInterval());
        this.client.setCallback(this.callback);
        this.client.setTimeToWait(this.config.getProducerConfig().getTimeToWait());
    // MqttTopic topic = this.client.getTopic("");
    // // setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
    // this.options.setWill(topic, "close".getBytes(), 0, true);
    } catch (Exception e) {
        logger.error("MQTT client producer initialization failed.", e);
    }
    return this;
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttProducerException(io.transport.mqttclient.exception.MqttProducerException)

Example 3 with MqttTopic

use of org.eclipse.paho.client.mqttv3.MqttTopic in project java-docs-samples by GoogleCloudPlatform.

the class MqttExample method main.

// [END iot_mqtt_configcallback]
/**
 * Parse arguments, configure MQTT, and publish messages.
 */
public static void main(String[] args) throws Exception {
    // [START iot_mqtt_configuremqtt]
    MqttExampleOptions options = MqttExampleOptions.fromFlags(args);
    if (options == null) {
        // Could not parse.
        System.exit(1);
    }
    // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
    // connections are accepted. For server authentication, the JVM's root certificates
    // are used.
    final String mqttServerAddress = String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);
    // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
    // Google Cloud IoT Core, it must be in the format below.
    final String mqttClientId = String.format("projects/%s/locations/%s/registries/%s/devices/%s", options.projectId, options.cloudRegion, options.registryId, options.deviceId);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    // Note that the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
    // explictly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    Properties sslProps = new Properties();
    sslProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
    connectOptions.setSSLProperties(sslProps);
    // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
    // Paho client library to send the password field. The password field is used to transmit a JWT
    // to authorize the device.
    connectOptions.setUserName("unused");
    DateTime iat = new DateTime();
    if (options.algorithm.equals("RS256")) {
        connectOptions.setPassword(createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
    } else if (options.algorithm.equals("ES256")) {
        connectOptions.setPassword(createJwtEs(options.projectId, options.privateKeyFile).toCharArray());
    } else {
        throw new IllegalArgumentException("Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
    }
    // [END iot_mqtt_configuremqtt]
    // [START iot_mqtt_publish]
    // Create a client, and connect to the Google MQTT bridge.
    MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
    // Both connect and publish operations may fail. If they do, allow retries but with an
    // exponential backoff time period.
    long initialConnectIntervalMillis = 500L;
    long maxConnectIntervalMillis = 6000L;
    long maxConnectRetryTimeElapsedMillis = 900000L;
    float intervalMultiplier = 1.5f;
    long retryIntervalMs = initialConnectIntervalMillis;
    long totalRetryTimeMs = 0;
    while (!client.isConnected() && totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) {
        try {
            client.connect(connectOptions);
        } catch (MqttException e) {
            int reason = e.getReasonCode();
            // If the connection is lost or if the server cannot be connected, allow retries, but with
            // exponential backoff.
            System.out.println("An error occurred: " + e.getMessage());
            if (reason == MqttException.REASON_CODE_CONNECTION_LOST || reason == MqttException.REASON_CODE_SERVER_CONNECT_ERROR) {
                System.out.println("Retrying in " + retryIntervalMs / 1000.0 + " seconds.");
                Thread.sleep(retryIntervalMs);
                totalRetryTimeMs += retryIntervalMs;
                retryIntervalMs *= intervalMultiplier;
                if (retryIntervalMs > maxConnectIntervalMillis) {
                    retryIntervalMs = maxConnectIntervalMillis;
                }
            } else {
                throw e;
            }
        }
    }
    attachCallback(client, options.deviceId);
    // Publish to the events or state topic based on the flag.
    String subTopic = options.messageType.equals("event") ? "events" : options.messageType;
    // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
    // required to be in the format below. Note that this is not the same as the device registry's
    // Cloud Pub/Sub topic.
    String mqttTopic = String.format("/devices/%s/%s", options.deviceId, subTopic);
    // Publish numMessages messages to the MQTT bridge, at a rate of 1 per second.
    for (int i = 1; i <= options.numMessages; ++i) {
        String payload = String.format("%s/%s-payload-%d", options.registryId, options.deviceId, i);
        System.out.format("Publishing %s message %d/%d: '%s'\n", options.messageType, i, options.numMessages, payload);
        // Refresh the connection credentials before the JWT expires.
        // [START iot_mqtt_jwt_refresh]
        long secsSinceRefresh = ((new DateTime()).getMillis() - iat.getMillis()) / 1000;
        if (secsSinceRefresh > (options.tokenExpMins * 60)) {
            System.out.format("\tRefreshing token after: %d seconds\n", secsSinceRefresh);
            iat = new DateTime();
            if (options.algorithm.equals("RS256")) {
                connectOptions.setPassword(createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
            } else if (options.algorithm.equals("ES256")) {
                connectOptions.setPassword(createJwtEs(options.projectId, options.privateKeyFile).toCharArray());
            } else {
                throw new IllegalArgumentException("Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
            }
            client.disconnect();
            client.connect();
            attachCallback(client, options.deviceId);
        }
        // [END iot_mqtt_jwt_refresh]
        // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
        // also supports qos=0 for at most once delivery.
        MqttMessage message = new MqttMessage(payload.getBytes());
        message.setQos(1);
        client.publish(mqttTopic, message);
        if (options.messageType.equals("event")) {
            // Send telemetry events every second
            Thread.sleep(1000);
        } else {
            // Note: Update Device state less frequently than with telemetry events
            Thread.sleep(5000);
        }
    }
    // Disconnect the client if still connected, and finish the run.
    if (client.isConnected()) {
        client.disconnect();
    }
    System.out.println("Finished loop successfully. Goodbye!");
// [END iot_mqtt_publish]
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) Properties(java.util.Properties) DateTime(org.joda.time.DateTime) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Aggregations

MqttException (org.eclipse.paho.client.mqttv3.MqttException)3 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)2 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)2 MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)2 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)2 MqttProducerException (io.transport.mqttclient.exception.MqttProducerException)1 Properties (java.util.Properties)1 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)1 MqttDeliveryToken (org.eclipse.paho.client.mqttv3.MqttDeliveryToken)1 MqttTopic (org.eclipse.paho.client.mqttv3.MqttTopic)1 DateTime (org.joda.time.DateTime)1 MqttSenderChannel (org.openhab.io.transport.mqtt.MqttSenderChannel)1