Java Code Examples for org.eclipse.paho.client.mqttv3.MqttException#REASON_CODE_SERVER_CONNECT_ERROR

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttException#REASON_CODE_SERVER_CONNECT_ERROR . 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: IotCoreClient.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
/**
 * Determine whether the mqttException is an error that may be resolved by retrying or whether
 * the error cannot be resolved. Determined according to guidance from Cloud IoT Core's
 * <a href="https://cloud.google.com/iot/docs/how-tos/errors">documentation</a>.
 *
 * @return Returns true if the MQTT client should resend the message. Returns false otherwise.
 */
private boolean isRetryableError(MqttException mqttException) {
    // Retry using exponential backoff in cases where appropriate. Otherwise, log
    // the failure.
    switch (mqttException.getReasonCode()) {
        // Retry cases:
        case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
        case MqttException.REASON_CODE_WRITE_TIMEOUT:
        case MqttException.REASON_CODE_CLIENT_NOT_CONNECTED:
        case MqttException.REASON_CODE_CLIENT_TIMEOUT:
            return true;
        case MqttException.REASON_CODE_CLIENT_EXCEPTION:
            // This case happens when there is no internet connection. Unfortunately, Paho
            // doesn't provide a better way to get that information.
            if (mqttException.getCause() instanceof UnknownHostException) {
                return true;
            }
        case MqttException.REASON_CODE_CONNECTION_LOST:
            // If the MqttException's cause is an EOFException, then the client or Cloud IoT
            // Core closed the connection. If mRunBackgroundThread is true, then we know the
            // client didn't close the connection and the connection was likely closed because
            // the client was publishing device state updates too quickly. Mark this as a
            // "retryable" error so the message that caused the exception isn't discarded.
            if (mqttException.getCause() instanceof EOFException
                    && mRunBackgroundThread.get()) {
                return true;
            }
        default:
            return false;
    }
}
 
Example 2
Source File: MqttExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Connects the gateway to the MQTT bridge. */
protected static MqttClient startMqtt(
    String mqttBridgeHostname,
    int mqttBridgePort,
    String projectId,
    String cloudRegion,
    String registryId,
    String gatewayId,
    String privateKeyFile,
    String algorithm)
    throws NoSuchAlgorithmException, IOException, MqttException, InterruptedException,
        InvalidKeySpecException {
  // [START iot_gateway_start_mqtt]

  // 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", mqttBridgeHostname, 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",
          projectId, cloudRegion, registryId, gatewayId);

  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");

  if ("RS256".equals(algorithm)) {
    connectOptions.setPassword(createJwtRsa(projectId, privateKeyFile).toCharArray());
  } else if ("ES256".equals(algorithm)) {
    connectOptions.setPassword(createJwtEs(projectId, privateKeyFile).toCharArray());
  } else {
    throw new IllegalArgumentException(
        "Invalid algorithm " + algorithm + ". Should be one of 'RS256' or 'ES256'.");
  }

  System.out.println(String.format("%s", mqttClientId));

  // 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 ((totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) && !client.isConnected()) {
    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, gatewayId);

  // The topic gateways receive error updates on. QoS must be 0.
  String errorTopic = String.format("/devices/%s/errors", gatewayId);
  System.out.println(String.format("Listening on %s", errorTopic));

  client.subscribe(errorTopic, 0);

  return client;
  // [END iot_gateway_start_mqtt]
}
 
Example 3
Source File: MqttPahoClient.java    From joynr with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribe(String topic) {
    boolean subscribed = false;
    while (!subscribed && !shutdown.get()) {
        logger.debug("{}: Checking for subscription to: {}", clientInformation, topic);
        long stamp = mqttClientLock.readLock();
        try {
            synchronized (subscribedTopics) {
                if (!subscribedTopics.contains(topic)) {
                    logger.info("{}: Attempting to subscribe to: {}", clientInformation, topic);
                    if (mqttClient == null) {
                        throw new MqttException(MqttException.REASON_CODE_CLIENT_NOT_CONNECTED);
                    }
                    mqttClient.subscribe(topic);
                    subscribedTopics.add(topic);
                    logger.info("{}: Subscribed to: {}", clientInformation, topic);
                }
                subscribed = true;
            }
        } catch (MqttException mqttError) {
            logger.debug("{}: Subscribe to {} failed: {}. Error code {}",
                         clientInformation,
                         topic,
                         mqttError.getMessage(),
                         mqttError.getReasonCode(),
                         mqttError);
            switch (mqttError.getReasonCode()) {
            case MqttException.REASON_CODE_CLIENT_EXCEPTION:
            case MqttException.REASON_CODE_BROKER_UNAVAILABLE:
            case MqttException.REASON_CODE_CLIENT_TIMEOUT:
            case MqttException.REASON_CODE_CONNECT_IN_PROGRESS:
            case MqttException.REASON_CODE_MAX_INFLIGHT:
            case MqttException.REASON_CODE_NO_MESSAGE_IDS_AVAILABLE:
            case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
            case MqttException.REASON_CODE_SUBSCRIBE_FAILED:
            case MqttException.REASON_CODE_UNEXPECTED_ERROR:
            case MqttException.REASON_CODE_WRITE_TIMEOUT:
            case MqttException.REASON_CODE_CONNECTION_LOST:
            case MqttException.REASON_CODE_CLIENT_NOT_CONNECTED:
            case MqttException.REASON_CODE_CLIENT_DISCONNECTING:
                throw new JoynrIllegalStateException("Unexpected exception while subscribing to " + topic
                        + ", error: " + mqttError, mqttError);
            default:
                throw new JoynrIllegalStateException("Unexpected exception while subscribing to " + topic
                        + ", error: " + mqttError);
            }

        } catch (Exception e) {
            throw new JoynrRuntimeException("Unable to start MqttPahoClient", e);
        } finally {
            mqttClientLock.unlockRead(stamp);
        }
    }
}