use of com.aware.utils.SSLUtils in project aware-client by denzilferreira.
the class Mqtt method initializeMQTT.
private void initializeMQTT() {
String server = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_SERVER);
if (server == null || server.length() == 0)
return;
if (server.contains("http") || server.contains("https")) {
Uri serverUri = Uri.parse(server);
server = serverUri.getHost();
}
MQTT_SERVER = server;
MQTT_PORT = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_PORT);
MQTT_USERNAME = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_USERNAME);
MQTT_PASSWORD = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_PASSWORD);
MQTT_KEEPALIVE = (Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_KEEP_ALIVE).length() > 0 ? Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_KEEP_ALIVE) : "600");
MQTT_QoS = Aware.getSetting(getApplicationContext(), Aware_Preferences.MQTT_QOS);
if (Integer.parseInt(MQTT_PORT) == 1883)
MQTT_PROTOCOL = "tcp";
if (Integer.parseInt(MQTT_PORT) == 8883)
MQTT_PROTOCOL = "ssl";
String MQTT_URL = MQTT_PROTOCOL + "://" + MQTT_SERVER + ":" + MQTT_PORT;
if (MQTT_MESSAGES_PERSISTENCE == null)
MQTT_MESSAGES_PERSISTENCE = new MemoryPersistence();
MqttConnectOptions MQTT_OPTIONS = new MqttConnectOptions();
// resume pending messages from server
MQTT_OPTIONS.setCleanSession(false);
// add 10 seconds to keep alive as options timeout
MQTT_OPTIONS.setConnectionTimeout(Integer.parseInt(MQTT_KEEPALIVE) + 10);
MQTT_OPTIONS.setKeepAliveInterval(Integer.parseInt(MQTT_KEEPALIVE));
MQTT_OPTIONS.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
MQTT_OPTIONS.setAutomaticReconnect(true);
if (MQTT_USERNAME.length() > 0)
MQTT_OPTIONS.setUserName(MQTT_USERNAME);
if (MQTT_PASSWORD.length() > 0)
MQTT_OPTIONS.setPassword(MQTT_PASSWORD.toCharArray());
if (MQTT_PROTOCOL.equalsIgnoreCase("ssl")) {
try {
SocketFactory factory = new SSLUtils(this).getSocketFactory(MQTT_SERVER);
MQTT_OPTIONS.setSocketFactory(factory);
MQTT_CLIENT = new MqttClient(MQTT_URL, String.valueOf(Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID).hashCode()), MQTT_MESSAGES_PERSISTENCE);
MQTT_CLIENT.setCallback(this);
new MQTTAsync().execute(MQTT_OPTIONS);
} catch (NullPointerException e) {
Log.e(Mqtt.TAG, "Unable to create SSL factory. Certificate missing?");
} catch (MqttException | IllegalArgumentException e) {
if (Aware.DEBUG)
Log.e(TAG, "Failed: " + e.getMessage());
}
}
}
Aggregations