Search in sources :

Example 1 with MqttConnectResult

use of org.thingsboard.mqtt.MqttConnectResult in project thingsboard by thingsboard.

the class TbMqttNode method initClient.

protected MqttClient initClient(TbContext ctx) throws Exception {
    MqttClientConfig config = new MqttClientConfig(getSslContext());
    if (!StringUtils.isEmpty(this.mqttNodeConfiguration.getClientId())) {
        config.setClientId(this.mqttNodeConfiguration.isAppendClientIdSuffix() ? this.mqttNodeConfiguration.getClientId() + "_" + ctx.getServiceId() : this.mqttNodeConfiguration.getClientId());
    }
    config.setCleanSession(this.mqttNodeConfiguration.isCleanSession());
    prepareMqttClientConfig(config);
    MqttClient client = MqttClient.create(config, null);
    client.setEventLoop(ctx.getSharedEventLoop());
    Future<MqttConnectResult> connectFuture = client.connect(this.mqttNodeConfiguration.getHost(), this.mqttNodeConfiguration.getPort());
    MqttConnectResult result;
    try {
        result = connectFuture.get(this.mqttNodeConfiguration.getConnectTimeoutSec(), TimeUnit.SECONDS);
    } catch (TimeoutException ex) {
        connectFuture.cancel(true);
        client.disconnect();
        String hostPort = this.mqttNodeConfiguration.getHost() + ":" + this.mqttNodeConfiguration.getPort();
        throw new RuntimeException(String.format("Failed to connect to MQTT broker at %s.", hostPort));
    }
    if (!result.isSuccess()) {
        connectFuture.cancel(true);
        client.disconnect();
        String hostPort = this.mqttNodeConfiguration.getHost() + ":" + this.mqttNodeConfiguration.getPort();
        throw new RuntimeException(String.format("Failed to connect to MQTT broker at %s. Result code is: %s", hostPort, result.getReturnCode()));
    }
    return client;
}
Also used : MqttClient(org.thingsboard.mqtt.MqttClient) MqttConnectResult(org.thingsboard.mqtt.MqttConnectResult) MqttClientConfig(org.thingsboard.mqtt.MqttClientConfig) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

TimeoutException (java.util.concurrent.TimeoutException)1 MqttClient (org.thingsboard.mqtt.MqttClient)1 MqttClientConfig (org.thingsboard.mqtt.MqttClientConfig)1 MqttConnectResult (org.thingsboard.mqtt.MqttConnectResult)1