Search in sources :

Example 1 with TopicsData

use of org.flyve.mdm.agent.data.database.TopicsData in project android-mdm-agent by flyve-mdm.

the class MqttController method subscribe.

/**
 * Subscribe to the topic
 * When come from MQTT has a format like this {"subscribe":[{"topic":"/2/fleet/22"}]}
 */
public void subscribe(final String channel) {
    if (channel == null || channel.contains("null")) {
        // case of unsubscribe
        AppDataBase dataBase = AppDataBase.getAppDatabase(context);
        dataBase.TopicsDao().deleteFleets();
        return;
    }
    final List<Topics> topics = new TopicsData(context).setValue(channel, 0);
    // if topic null
    if (topics == null || topics.isEmpty()) {
        return;
    }
    // use List instead array because we need to keep only topic with status 0
    List<String> lstTopics = new ArrayList<>();
    List<Integer> lstQos = new ArrayList<>();
    for (int i = 0; i < topics.size(); i++) {
        // if not subscribed
        if (topics.get(i).status != 1) {
            lstTopics.add(topics.get(i).topic);
            lstQos.add(topics.get(i).qos);
        }
    }
    try {
        String[] arrayTopics;
        arrayTopics = lstTopics.toArray(new String[lstTopics.size()]);
        // transform list of Integer to array of int 'primitive'
        int size = lstQos.size();
        int[] arrayQos = new int[size];
        Integer[] temp = lstQos.toArray(new Integer[size]);
        for (int n = 0; n < size; ++n) {
            arrayQos[n] = temp[n];
        }
        IMqttToken subToken = client.subscribe(arrayTopics, arrayQos);
        subToken.setActionCallback(new IMqttActionListener() {

            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                // The message was published
                for (String topic : asyncActionToken.getTopics()) {
                    new TopicsData(context).setStatusTopic(topic, 1);
                    FlyveLog.d("Subscribe from fleet " + topic);
                    broadcastReceivedLog(" -> " + topic, "Subscribed", String.valueOf(asyncActionToken.getTopics().length));
                }
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                // The subscription could not be performed, maybe the user was not
                // authorized to subscribe on the specified topic e.g. using wildcards
                String errorMessage = " unknown";
                if (exception != null) {
                    errorMessage = exception.getMessage();
                    Log.d("Subscribe", "Error", exception);
                }
                FlyveLog.e(this.getClass().getName() + ", subscribe", "ERROR on subscribe: " + errorMessage);
                broadcastReceivedLog(ERROR, "Error on subscribe", errorMessage);
            }
        });
    } catch (Exception ex) {
        FlyveLog.e(this.getClass().getName() + ", subscribe", ex.getMessage());
    }
}
Also used : IMqttActionListener(org.eclipse.paho.client.mqttv3.IMqttActionListener) Topics(org.flyve.mdm.agent.data.database.entity.Topics) AppDataBase(org.flyve.mdm.agent.data.database.setup.AppDataBase) ArrayList(java.util.ArrayList) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) TopicsData(org.flyve.mdm.agent.data.database.TopicsData)

Example 2 with TopicsData

use of org.flyve.mdm.agent.data.database.TopicsData 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 3 with TopicsData

use of org.flyve.mdm.agent.data.database.TopicsData in project android-mdm-agent by flyve-mdm.

the class FragmentTopics method loadData.

private void loadData(ListView lst) {
    List<Topics> arrTopics = new TopicsData(FragmentTopics.this.getContext()).getAllTopics();
    ArrayList arr = new ArrayList<HashMap<String, Boolean>>();
    if (arrTopics.isEmpty()) {
        HashMap<String, String> map = new HashMap<>();
        map.put("topic", "");
        map.put("status", "");
        arr.add(map);
    } else {
        for (int i = 0; i < arrTopics.size(); i++) {
            HashMap<String, String> map = new HashMap<>();
            map.put("topic", String.valueOf(arrTopics.get(i).topic));
            map.put("status", String.valueOf(arrTopics.get(i).status));
            arr.add(map);
        }
    }
    lst.setAdapter(new TopicsAdapter(FragmentTopics.this.getActivity(), arr));
}
Also used : Topics(org.flyve.mdm.agent.data.database.entity.Topics) TopicsData(org.flyve.mdm.agent.data.database.TopicsData) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TopicsAdapter(org.flyve.mdm.agent.adapter.TopicsAdapter)

Aggregations

TopicsData (org.flyve.mdm.agent.data.database.TopicsData)3 ArrayList (java.util.ArrayList)2 IMqttActionListener (org.eclipse.paho.client.mqttv3.IMqttActionListener)2 IMqttToken (org.eclipse.paho.client.mqttv3.IMqttToken)2 Topics (org.flyve.mdm.agent.data.database.entity.Topics)2 FileInputStream (java.io.FileInputStream)1 KeyStore (java.security.KeyStore)1 CertificateFactory (java.security.cert.CertificateFactory)1 X509Certificate (java.security.cert.X509Certificate)1 HashMap (java.util.HashMap)1 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)1 SSLContext (javax.net.ssl.SSLContext)1 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)1 MqttAndroidClient (org.eclipse.paho.android.service.MqttAndroidClient)1 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)1 TopicsAdapter (org.flyve.mdm.agent.adapter.TopicsAdapter)1 MqttData (org.flyve.mdm.agent.data.database.MqttData)1 AppDataBase (org.flyve.mdm.agent.data.database.setup.AppDataBase)1