Search in sources :

Example 1 with MqttAndroidClient

use of org.eclipse.paho.android.service.MqttAndroidClient in project android-mdm-agent by flyve-mdm.

the class MqttModel method connect.

@Override
public void connect(final Context context, final MqttCallback callback) {
    // if the device is connected exit
    if (getMqttClient() != null && getMqttClient().isConnected()) {
        setStatus(context, callback, true);
        return;
    }
    MqttData cache = new MqttData(context);
    final String mBroker = cache.getBroker();
    final String mPort = cache.getPort();
    final String mUser = cache.getMqttUser();
    final String mPassword = cache.getMqttPasswd();
    final String mTopic = cache.getTopic();
    final String mTLS = cache.getTls();
    final StringBuilder connectionInformation = new StringBuilder();
    connectionInformation.append("\n\nBroker: ").append(mBroker).append("\n");
    connectionInformation.append("Port: ").append(mPort).append("\n");
    connectionInformation.append("User: ").append(mUser).append("\n");
    connectionInformation.append("Topic: ").append(mTopic).append("\n");
    connectionInformation.append("TLS: ").append(mTLS).append("\n");
    Log.d("MQTT", connectionInformation.toString());
    Helpers.storeLog("MQTT", "Connection Information", connectionInformation.toString());
    String protocol = "tcp";
    // TLS is active change protocol
    if (mTLS.equals("1")) {
        protocol = "ssl";
    }
    String clientId;
    MqttConnectOptions options;
    if (client == null) {
        try {
            clientId = MqttClient.generateClientId();
            client = new MqttAndroidClient(context, protocol + "://" + mBroker + ":" + mPort, clientId);
        } catch (ExceptionInInitializerError ex) {
            showDetailError(context, CommonErrorType.MQTT_IN_INITIALIZER_ERROR, ex.getMessage());
            reconnect(context, callback);
            return;
        }
        client.setCallback(callback);
    }
    try {
        options = new MqttConnectOptions();
        options.setPassword(mPassword.toCharArray());
        options.setUserName(mUser);
        options.setCleanSession(true);
        options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
        options.setConnectionTimeout(MqttConnectOptions.CONNECTION_TIMEOUT_DEFAULT);
        options.setKeepAliveInterval(MqttConnectOptions.KEEP_ALIVE_INTERVAL_DEFAULT);
        options.setAutomaticReconnect(true);
        // Create a testament to send when MQTT connection is down
        String will = "{ \"online\": false }";
        options.setWill(mTopic + "/Status/Online", will.getBytes(), 0, true);
        // If TLS is active needs ssl connection option
        if (mTLS.equals("1")) {
            try {
                // load ssl certificate from broker and put it in file
                // need to be done in anothger
                new MqttDownloadSSL().execute(mBroker, Integer.valueOf(mPort), context);
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                caKeyStore.load(null, null);
                CertificateFactory certificationFactory = CertificateFactory.getInstance("X.509");
                // load certificate file previously loaded from broker
                FileInputStream inputStream;
                inputStream = context.openFileInput("broker_cert");
                X509Certificate ca = (X509Certificate) certificationFactory.generateCertificate(inputStream);
                String alias = ca.getSubjectX500Principal().getName();
                // Set proper alias name
                caKeyStore.setCertificateEntry(alias, ca);
                trustManagerFactory.init(caKeyStore);
                FlyveLog.v("Certificate Owner: %s", ca.getSubjectDN().toString());
                FlyveLog.v("Certificate Issuer: %s", ca.getIssuerDN().toString());
                FlyveLog.v("Certificate Serial Number: %s", ca.getSerialNumber().toString());
                FlyveLog.v("Certificate Algorithm: %s", ca.getSigAlgName());
                FlyveLog.v("Certificate Version: %s", ca.getVersion());
                FlyveLog.v("Certificate OID: %s", ca.getSigAlgOID());
                Enumeration<String> aliasesCA = caKeyStore.aliases();
                for (; aliasesCA.hasMoreElements(); ) {
                    String o = aliasesCA.nextElement();
                    FlyveLog.v("Alias: %s isKeyEntry:%s isCertificateEntry:%s", o, caKeyStore.isKeyEntry(o), caKeyStore.isCertificateEntry(o));
                }
                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("X509");
                keyManagerFactory.init(null, null);
                // SSL
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
                options.setSocketFactory(sslContext.getSocketFactory());
            } catch (Exception ex) {
                // restart connection
                setStatus(context, callback, false);
                showDetailError(context, CommonErrorType.MQTT_CONNECTION, ex.getMessage());
            }
        }
    } catch (Exception ex) {
        showDetailError(context, CommonErrorType.MQTT_OPTIONS, ex.getMessage());
        return;
    }
    // set all the topics on database to unconnected
    new TopicsData(context).clearTopics();
    try {
        IMqttToken token = client.connect(options);
        token.setActionCallback(new IMqttActionListener() {

            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Helpers.storeLog("MQTT", "Connection Success", "");
                // Everything ready waiting for message
                policiesController = new MqttController(context, client);
                // We are connected
                setStatus(context, callback, true);
                // set the reconnection counter to 0
                reconnectionCounter = 0;
                // main topic
                String topic = mTopic + "/#";
                policiesController.subscribe(topic);
                // subscribe to manifest
                policiesController.subscribe("FlyvemdmManifest/Status/Version");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable ex) {
                setStatus(context, callback, false);
                String messageError;
                if (ex.getCause() != null) {
                    messageError = ex.getCause().toString();
                } else {
                    messageError = ex.getMessage();
                }
                showDetailError(context, CommonErrorType.MQTT_ACTION_CALLBACK, messageError);
            }
        });
    } catch (Exception ex) {
        setStatus(context, callback, false);
        showDetailError(context, CommonErrorType.MQTT_CONNECTION, ex.getMessage());
    }
}
Also used : MqttData(org.flyve.mdm.agent.data.database.MqttData) IMqttActionListener(org.eclipse.paho.client.mqttv3.IMqttActionListener) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) MqttAndroidClient(org.eclipse.paho.android.service.MqttAndroidClient) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TopicsData(org.flyve.mdm.agent.data.database.TopicsData) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Example 2 with MqttAndroidClient

use of org.eclipse.paho.android.service.MqttAndroidClient in project yoo_home_Android by culturer.

the class MQTTService method initMQ.

// 初始化MQ服务
private void initMQ() {
    // 服务器地址(协议+地址+端口号)
    client = new MqttAndroidClient(this, host, clientId);
    // 设置MQTT监听并且接受消息
    client.setCallback(mqttCallback);
    conOpt = new MqttConnectOptions();
    // 清除缓存
    conOpt.setCleanSession(false);
    // 设置超时时间,单位:秒
    conOpt.setConnectionTimeout(0);
    // 心跳包发送间隔,单位:秒
    conOpt.setKeepAliveInterval(10);
    // 用户名
    conOpt.setUserName(userName);
    // 密码
    conOpt.setPassword(passWord.toCharArray());
    // last will message
    boolean doConnect = true;
    String message = "{\"terminal_uid\":\"" + clientId + "\"}";
    String topic = myTopic;
    Integer qos = 0;
    Boolean retained = false;
    // 存在内存泄露???
    if ((!message.equals("")) || (!topic.equals(""))) {
        // 最后的遗嘱
        try {
            conOpt.setWill(topic, message.getBytes(), qos, retained);
        } catch (Exception e) {
            Log.i(TAG, "Exception Occured", e);
            doConnect = false;
            iMqttActionListener.onFailure(null, e);
        }
    }
    if (doConnect) {
        doClientConnection();
    }
}
Also used : MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttAndroidClient(org.eclipse.paho.android.service.MqttAndroidClient) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 3 with MqttAndroidClient

use of org.eclipse.paho.android.service.MqttAndroidClient in project android-mdm-agent by flyve-mdm.

the class MQTTService method connect.

/**
 * This function connect the agent with MQTT server
 */
public void connect() {
    Context mContext = this.getApplicationContext();
    MqttData cache = new MqttData(mContext);
    final String mBroker = cache.getBroker();
    final String mPort = cache.getPort();
    final String mUser = cache.getMqttuser();
    final String mPassword = cache.getMqttpasswd();
    final String mTopic = cache.getTopic();
    final String mTLS = cache.getTls();
    if (mPassword == null) {
        FlyveLog.d(TAG, "Password can't be null");
        return;
    }
    storeLog(Helpers.broadCastMessage(MQTT_LOGIN, "Broker", mBroker));
    storeLog(Helpers.broadCastMessage(MQTT_LOGIN, "Port", mPort));
    storeLog(Helpers.broadCastMessage(MQTT_LOGIN, "User", mUser));
    storeLog(Helpers.broadCastMessage(MQTT_LOGIN, "Topic", mTopic));
    FlyveLog.i("is TLS (0=false;1=true): %s", mTLS);
    String protocol = "tcp";
    // TLS is active change protocol
    if (mTLS.equals("1")) {
        protocol = "ssl";
    }
    String clientId = MqttClient.generateClientId();
    client = new MqttAndroidClient(mContext, protocol + "://" + mBroker + ":" + mPort, clientId);
    client.setCallback(this);
    try {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setPassword(mPassword.toCharArray());
        options.setUserName(mUser);
        options.setCleanSession(true);
        options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
        options.setConnectionTimeout(0);
        options.setAutomaticReconnect(true);
        // Create a testament to send when MQTT connection is down
        String will = "{ online: false }";
        options.setWill("/Status/Online", will.getBytes(), 0, false);
        // If TLS is active needs ssl connection option
        if (mTLS.equals("1")) {
            // SSL
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, null, null);
            options.setSocketFactory(sslContext.getSocketFactory());
        }
        IMqttToken token = client.connect(options);
        token.setActionCallback(new IMqttActionListener() {

            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                // We are connected
                // Everything ready waiting for message
                FlyveLog.d(TAG, "Success we are online!");
                broadcastServiceStatus(true);
                policiesController = new PoliciesController(getApplicationContext(), client);
                // send status online true to MQTT
                policiesController.sendOnlineStatus(true);
                // main channel
                String channel = mTopic + "/#";
                FlyveLog.d(TAG, "MQTT Channel: " + channel);
                policiesController.subscribe("#");
                // subscribe to manifest
                policiesController.subscribe("/FlyvemdmManifest/Status/Version");
                // send inventory on connect
                policiesController.createInventory();
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable ex) {
                // Something went wrong e.g. connection timeout or firewall problems
                String errorMessage = "";
                if (ex.getMessage().equalsIgnoreCase("MqttException")) {
                    errorMessage = ((MqttException) ex).toString();
                } else {
                    errorMessage = ex.getMessage();
                }
                FlyveLog.e(TAG, "Connection fail: " + errorMessage);
                String errorCode;
                try {
                    errorCode = String.valueOf(((MqttException) ex).getReasonCode());
                } catch (Exception exception) {
                    errorCode = "0";
                }
                storeLog(Helpers.broadCastMessage(ERROR, "Error on connect - client.connect", errorMessage));
                broadcastMessage(Helpers.broadCastMessage(ERROR, errorCode, errorMessage));
                broadcastServiceStatus(false);
            }
        });
    } catch (MqttException ex) {
        FlyveLog.e(TAG, ex.getMessage());
        broadcastMessage(Helpers.broadCastMessage(ERROR, String.valueOf(ex.getReasonCode()), ex.getMessage()));
        storeLog(Helpers.broadCastMessage(ERROR, "Error on connect", ex.getMessage()));
    } catch (Exception ex) {
        FlyveLog.e(TAG, ex.getMessage());
        broadcastMessage(Helpers.broadCastMessage(ERROR, "0", mContext.getResources().getString(R.string.MQTT_ERROR_CONNECTION)));
        storeLog(Helpers.broadCastMessage(ERROR, "Error on connect", ex.getMessage()));
    }
}
Also used : Context(android.content.Context) SSLContext(javax.net.ssl.SSLContext) MqttData(org.flyve.mdm.agent.data.MqttData) IMqttActionListener(org.eclipse.paho.client.mqttv3.IMqttActionListener) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) SSLContext(javax.net.ssl.SSLContext) MqttAndroidClient(org.eclipse.paho.android.service.MqttAndroidClient) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Aggregations

MqttAndroidClient (org.eclipse.paho.android.service.MqttAndroidClient)3 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)3 SSLContext (javax.net.ssl.SSLContext)2 IMqttActionListener (org.eclipse.paho.client.mqttv3.IMqttActionListener)2 IMqttToken (org.eclipse.paho.client.mqttv3.IMqttToken)2 MqttException (org.eclipse.paho.client.mqttv3.MqttException)2 Context (android.content.Context)1 FileInputStream (java.io.FileInputStream)1 KeyStore (java.security.KeyStore)1 CertificateFactory (java.security.cert.CertificateFactory)1 X509Certificate (java.security.cert.X509Certificate)1 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)1 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)1 MqttData (org.flyve.mdm.agent.data.MqttData)1 MqttData (org.flyve.mdm.agent.data.database.MqttData)1 TopicsData (org.flyve.mdm.agent.data.database.TopicsData)1