Темы Android Dynamic Mqtt не получают сообщений от брокера - PullRequest
0 голосов
/ 01 октября 2019

Я использую библиотеку Eclipse Paho для соединения с брокером mqtt, где есть несколько разделов динамики, например: new_user / #, где я добавляю UUID к # для его подписки.

ХотяБиблиотека заявляет, что я подписываюсь на темы успешно, служба сообщений Mqtt вообще не получает сообщений от брокера. Пожалуйста, помогите мне!

Вот код:

public void message() {

        publishMessage(Topic1 + IEMINumber, Msg, false, 0, listener);
        mqttHelper = new MqttHelper(getApplicationContext());
        mqttHelper.deviceIEMI(IEMINumber);
        mqttHelper.setCallback(new MqttCallbackExtended() {

            @Override
            public void connectComplete(boolean b, String s) {}

            @Override
            public void connectionLost(Throwable throwable) {}

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Debug", mqttMessage.toString() + "\t" + topic);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
    }

Также класс помощника:

public class MqttHelper {

    public MqttAndroidClient mqttAndroidClient;

    final String serverUri = "tcp://xxx.xxx.xx.xxx:xxxx";

    final String clientId = "ClientID";
    // final String subscriptionTopic = "example_topic";

    final String username = "your_username";
    final String password = "password";
    private String IemiNo;

    public MqttHelper(Context context) {
        mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean b, String s) {
                Log.w("mqtt", s);
            }

            @Override
            public void connectionLost(Throwable throwable) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                Log.w("Mqtt_Connect", mqttMessage.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
        connect();
    }

    public String deviceIEMI(String IEMINo) {
        IemiNo = IEMINo;
        return IEMINo;
    }

    public void setCallback(MqttCallbackExtended callback) {
        mqttAndroidClient.setCallback(callback);
    }


    private void connect() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());

        try {

            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {

                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                    subscribeToTopic();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
                }
            });


        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }


    private void subscribeToTopic() {
        String[] subscriptionTopic = {"topic1/" + IemiNo, "topic2/" + IemiNo};

        try {
            mqttAndroidClient.subscribe(String.valueOf(subscriptionTopic), 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.w("Mqtt", "Subscribed!");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.w("Mqtt", "Subscribed fail!");
                }
            });
        } catch (MqttException ex) {
            System.err.println("Exceptions subscribing");
            ex.printStackTrace();
        }
    }
}

Пожалуйста, дайте мне знать, где я неправ или естьэтот выпуск библиотеки !!

Ответы [ 2 ]

0 голосов
/ 15 октября 2019
**FaceDetection.java:**

    package com.example.yourApp;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.jessicathornsby.facerecog.common.CameraImageGraphic;
import com.jessicathornsby.facerecog.common.FrameMetadata;
import com.jessicathornsby.facerecog.common.GraphicOverlay;
import com.google.android.gms.tasks.Task;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.face.FirebaseVisionFace;
import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetector;
import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@SuppressWarnings("ALL")
public class FaceCapture2 extends VisionProcessorBase<List<FirebaseVisionFace>> {
    private Uri imageUri;
    String getimgname, getimgpath;
    private static final String TAG = "FaceDetectionProcessor";

    private final FirebaseVisionFaceDetector detector;
    //private final Bitmap overlayBitmap;

    private Runnable runnable;
    private Context mContext;
    private String UserID;
    private int counter = 0;
    private MqttAndroidClient client;
    private PahoMqttClient pahoMqttClient;
    private MqttAndroidClient mqttAndroidClient;
    private String IEMINO;

    FaceCapture2(Resources resources, Context context, String id, String IEMI) {
        FirebaseVisionFaceDetectorOptions options =
                new FirebaseVisionFaceDetectorOptions.Builder()
                        .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
                        .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
                        .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
                        .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS)
                        //.enableTracking()
                        .setMinFaceSize(0.1f)
                        .build();

        detector = FirebaseVision.getInstance().getVisionFaceDetector(options);

//        overlayBitmap = BitmapFactory.decodeResource(resources, R.drawable.left_eyes_closed);

        mContext = context;
        int offset = 30;
        UserID = id;
        IEMINO = IEMI;
        //repeatOffset = offset;

        pahoMqttClient = new PahoMqttClient();
        client = pahoMqttClient.getMqttClient(mContext, Constants.MQTT_BROKER_URL, Constants.CLIENT_ID, IEMINO);
        mqttAndroidClient = pahoMqttClient.getMqttClient(mContext, Constants.MQTT_BROKER_URL, Constants.CLIENT_ID, IEMINO);

        Handler handler = new Handler(Looper.getMainLooper());
        handler.postDelayed(runnable, 1000);
    }
    @Override
    protected Task<List<FirebaseVisionFace>> detectInImage(FirebaseVisionImage image) {
        return detector.detectInImage(image);
    }

    @TargetApi(Build.VERSION_CODES.P)
    @Override
    protected void onSuccess(
            @Nullable Bitmap originalCameraImage,
            @NonNull List<FirebaseVisionFace> faces,
            @NonNull FrameMetadata frameMetadata,
            @NonNull GraphicOverlay graphicOverlay) {

        graphicOverlay.clear();
        if (originalCameraImage != null) {
            CameraImageGraphic imageGraphic = new CameraImageGraphic(graphicOverlay, originalCameraImage);
            graphicOverlay.add(imageGraphic);
        }

       /*for (int i = 0; i < faces.size(); ++i) {
            FirebaseVisionFace face = faces.get(i);
            int cameraFacing = frameMetadata != null ? frameMetadata.getCameraFacing() : CameraSource.CAMERA_FACING_BACK;
            FaceGraphic faceGraphic = new FaceGraphic(graphicOverlay, face, cameraFacing, overlayBitmap);
            graphicOverlay.add(faceGraphic);
        }*/
        try {
            detector.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (originalCameraImage != null) {
            Bitmap currentImage = originalCameraImage;

        }
        folder(originalCameraImage);
        graphicOverlay.postInvalidate();
    }

    @SuppressLint("NewApi")
    private void folder(Bitmap bm) {
        int count;
        for (count = 0; count <= 30; count++) {
            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root + "/folder_name");
            File myDir1 = new File(root + "/folder_name.zip");
            Uri file1 = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", myDir);
            if (!myDir.exists()) {
                //noinspection ResultOfMethodCallIgnored
                myDir.mkdirs();
            }
            if (myDir.exists()) {
                zipFolder(myDir.toString(), myDir1.toString());
            }

            try {
                File file = new File(root + "/folder_name.zip");
                //convert file to byte[]
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos = new ObjectOutputStream(bos);
                oos.writeObject(file);
                bos.close();
                oos.close();
                byte[] bytearray = bos.toByteArray();
                String is = Base64.encodeToString(bytearray, Base64.DEFAULT);
                // Log.d("bytearray", is);
                imageupload(bytearray);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Random generator = new Random();
            int n = 30;
            n = generator.nextInt(n);
            String fname = "Image-" + n + ".jpg";
            File file = new File(myDir, fname);
            try {
                FileOutputStream out = new FileOutputStream(file);
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                // getFile(file);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    @TargetApi(Build.VERSION_CODES.P)
    private void zipFolder(String srcFolderPath, String zipFolderPath) {
        try {
            FileOutputStream fos = new FileOutputStream(zipFolderPath);
            ZipOutputStream zos = new ZipOutputStream(fos);
            File srcFile = new File(srcFolderPath);
            File[] files = srcFile.listFiles();

            for (int i = 0; i < 30; i++) {
                //Log.d("", "Adding file: " + files[i].getName());
                byte[] buffer = new byte[1024];
                FileInputStream fis = new FileInputStream(files[i]);
                zos.putNextEntry(new ZipEntry(files[i].getName()));
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
                fis.close();
            }
            //uploadFile(zipFolderPath);
            zos.close();
        } catch (IOException ioe) {
            Log.e("", ioe.getMessage());
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    private void imageupload(final byte[] zipfile) throws IOException, JSONException, MqttException {
        String root = Environment.getExternalStorageDirectory().toString();
        InputStream inputStream = null;//You can get an inputStream using any IO API
        inputStream = new FileInputStream(root + "/folder_name.zip");
        byte[] buffer = new byte[8192];
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

        try {
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                output64.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        output64.close();

        String attachedFile = output.toString();
        int repeatOffset = 1;
        if (repeatOffset > counter) {
            String url = "http://xxx.xxx.xx.xxx:xxxx";
            int i = 0;
            i++;
            String userID = UUID.randomUUID().toString();

            final RequestQueue requestQueue = Volley.newRequestQueue(mContext);
            final JSONObject params = new JSONObject();
            params.put("file", attachedFile);
            params.put("file_name", UserID + ".zip");

            final JSONObject first_image = new JSONObject();
            first_image.put("device_id", IEMINO);
            first_image.put("bulk_link", UserID + ".zip");
            first_image.put("user_id", UserID);
            first_image.put("user_uuid", "NULL");

            pahoMqttClient.publishMessage(client, first_image.toString(), 1, Constants.BULK_IMAGE + IEMINO);
            SimpleDateFormat sformat = new SimpleDateFormat("HH:mm:ss");
            Date bdate = new Date();
            Log.e("date", sformat.format(bdate));
            final JsonObjectRequest stringRequestpost = new JsonObjectRequest(url, new JSONObject(String.valueOf(params)),
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            //Server Response Handler
                            Log.e("VolleyErr", response.toString());
                            requestQueue.stop();
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //On Error Response Handler
                    //Toast.makeText(mContext, "Success Reverse!", Toast.LENGTH_LONG).show();
                    Log.e("bulk_success", "Success Reverse");
                    Date edate = new Date();
                    Log.e("after-time", sformat.format(edate));
                    error.printStackTrace();

                    requestQueue.stop();
                }
            }) {

                @Override
                public String getBodyContentType() {
                    return "application/json; multipart/form-data";
                    //"multipart/form-data;boundary="
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = new HashMap<>();

                    headers.put("x-api-key", "Your-API-Key-Here");
                    headers.put("Accept", "application/json; charset=utf-8");
                    return headers;
                }

            };

            //Starts Request
            requestQueue.add(stringRequestpost);
            counter++;
        }
        // uploadZip(zipfile);
    }

    @Override
    protected void onFailure(@NonNull Exception e) {
        Log.e(TAG, "Face detection failed " + e);
    }
}
0 голосов
/ 15 октября 2019
    Well I've edited my Code and now the whole functionality runs smoothly.
    So here is the code:

    **BarcodeActivtiy.java:**

        package com.example.yourApp;


    import me.dm7.barcodescanner.zxing.ZXingScannerView;

    @SuppressWarnings("All")
    public class BarcodeDump extends AppCompatActivity implements ZXingScannerView.ResultHandler {
        private static final String TAG = "BarcodeDump";
        private static final String FLASH_STATE = "FLASH_STATE";
        private static final String AUTO_FOCUS_STATE = "AUTO_FOCUS_STATE";
        private static final String SELECTED_FORMATS = "SELECTED_FORMATS";
        private static final String CAMERA_ID = "CAMERA_ID";
        private static String EMPTY = "";
        private ZXingScannerView mScannerView;
        private boolean mFlash;
        private boolean mAutoFocus;
        private ArrayList<Integer> mSelectedIndices;
        private int mCameraId = -1;
        private ToggleButton btnFocus;
        private ToggleButton btnFlash;
        JSONObject barcodeMqtt, RawResult;
        private PahoMqttClient pahoMqttClient;
        private MqttAndroidClient client;
        private MqttAndroidClient mqttAndroidClient;
        private String userID;
        private String message = "xyz";
        private String demomsg = "NEW";
        private String product_url = "null";
        private Result rawResult;
        private String UserID;
        private String IEMINo;
        private String uuserUUID;
        private MqttHelper mqttHelper;
        private JSONObject jsonObject;
        private String productURL;
        private String urlprod = "xy";
        private String muserID = "xy";
        StringBuilder servermessage = new StringBuilder(" ");

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            try {
                getSupportActionBar().hide();
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            } catch (NullPointerException e) {
                System.out.print(e.getMessage());
            }
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_barcode);
            //servermessage = new StringBuilder("hello");
            userID = getIntent().getStringExtra("userid");
            String brokermsg = getIntent().getStringExtra("brokermsg");
            String prodScan = getIntent().getStringExtra("productscan");
            String userUUID = getIntent().getStringExtra("userUUID");
            String gifmsg = getIntent().getStringExtra("gifmsg");
            muserID = getIntent().getStringExtra("muserID");

            IEMINo = MqttConstant.getIMEI(BarcodeDump.this);
            try {
                Log.e("brokeeer", brokermsg);
                Log.e("prodscan", prodScan);
                Log.e("userUUID", userUUID);
                Log.e("gifmsg", gifmsg);
                Log.e("muserID", muserID);
                //Log.e("url---product", mqttmsg);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.e("iemino", IEMINo);
            message = brokermsg;
            uuserUUID = userUUID;
            pahoMqttClient = new PahoMqttClient();
            if (savedInstanceState != null) {
                mFlash = savedInstanceState.getBoolean(FLASH_STATE, false);
                mAutoFocus = savedInstanceState.getBoolean(AUTO_FOCUS_STATE, true);
                mSelectedIndices = savedInstanceState.getIntegerArrayList(SELECTED_FORMATS);
                mCameraId = savedInstanceState.getInt(CAMERA_ID, -1);
            } else {
                mFlash = false;
                mAutoFocus = true;
                mSelectedIndices = null;
                mCameraId = -1;
            }
            setContentView(R.layout.activity_barcode);

            btnFocus = findViewById(R.id.focusButton);
            btnFlash = findViewById(R.id.flashButton);

            ViewGroup contentFrame = findViewById(R.id.content_frame);
            mScannerView = new ZXingScannerView(this);
            mScannerView.setSquareViewFinder(true);
            mScannerView.setIsBorderCornerRounded(true);
            mScannerView.setBorderCornerRadius(100);
            mScannerView.setBorderColor(R.color.colorPrimary);
            mScannerView.setLaserEnabled(false);

            UserID = UUID.randomUUID().toString();
            setupFormats();
            contentFrame.addView(mScannerView);

            btnFocus.setOnClickListener(v -> {
                mAutoFocus = !mAutoFocus;
                mScannerView.setAutoFocus(mAutoFocus);
            });

            btnFlash.setOnClickListener(v -> {
                mFlash = !mFlash;
                mScannerView.setFlash(mFlash);
            });
            client = pahoMqttClient.getMqttClient(BarcodeDump.this, Constants.MQTT_BROKER_URL, Constants.CLIENT_ID, MqttConstant.getIMEI(BarcodeDump.this));
            mqttAndroidClient = pahoMqttClient.getMqttClient(BarcodeDump.this, Constants.MQTT_BROKER_URL, Constants.CLIENT_ID, MqttConstant.getIMEI(BarcodeDump.this));

            mqttHelper = new MqttHelper(getApplicationContext());
            mqttHelper.deviceIEMI(IEMINo);
            try {
                mqttmessage(message);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

        //----------------------------------------MQTT Server Message Method with Thread ---------------------------//
        public void mqttmessage(String str) throws MqttException {
            new Handler().postDelayed(() -> {
                try {
                    mqttAndroidClient.setCallback(new MqttCallbackExtended() {
                        @Override
                        public void connectComplete(boolean b, String s) {

                        }

                        @Override
                        public void connectionLost(Throwable throwable) {

                        }

                        @Override
                        public void messageArrived(String s, MqttMessage mqttMessage) throws JSONException {
                            //setMessageNotification(s, new String(mqttMessage.getPayload()));
                            Log.e("barcode_dump", new String(mqttMessage.getPayload()));
                            Log.e("barcode_dump_topic", s);
                            if (s.contains("product_url") && mqttMessage.toString().contains("product_url")) {
                                product_url = mqttMessage.toString();
                                Log.e("product_url", product_url);
                                urlprod = product_url;
                            } else {
                                product_url = "This Product may not exist in the DATABASE";
                            }
                            servermessage.append(mqttMessage.toString());
                            try {
                                jsonObject = new JSONObject(mqttMessage.toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                if (s.contains("old_user")) {
                                    Log.e("BarcodeDump----Jsonobject", jsonObject.getString("userUUID"));
                                } else {
                                    Log.e("else", "else---block");
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }

                        @Override
                        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    mqttAndroidClient.subscribe("product_url/#", 1);
                    mqttAndroidClient.subscribe("new_user/#", 1);
                } catch (MqttException ex) {
                    ex.printStackTrace();
                }
            }, 1500);
        }

        private void setDefaultFragment(Fragment defaultFragment) {
            this.replaceFragment(defaultFragment);
        }

        public void replaceFragment(Fragment destFragment) {

            //First get FragmentManager object
            FragmentManager fragmentManager = this.getSupportFragmentManager();

            // Begin Fragment transaction.
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            // Replace the layout holder with the required Fragment object.
            fragmentTransaction.replace(R.id.content_frame, destFragment);

            // Commit the Fragment replace action.
            fragmentTransaction.commit();
        }

        @Override
        protected void onResume() {
            super.onResume();
            mScannerView.setResultHandler(this);
            mScannerView.startCamera(CameraSource.CAMERA_FACING_BACK);
            mScannerView.setFlash(mFlash);
            mScannerView.setAutoFocus(mAutoFocus);
        }

        @Override
        protected void onPause() {
            super.onPause();
            mScannerView.stopCamera();
        }

        //-----Barcode / QR Code Result Manipulation------------//
        @Override
        public void handleResult(Result rawResult) {
            Log.d("rawresult", rawResult.toString());
            String product_scanned = "www.google.com";
            try {
                Log.e("urlprod", urlprod);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (rawResult.getBarcodeFormat() == BarcodeFormat.QR_CODE) {
                try {
                    RawResult = new JSONObject();
                    try {
                        RawResult.put("code", rawResult.toString());
                        RawResult.put("code_type", "qr");
                        RawResult.put("store_id", "BPR_50622052018");
                        RawResult.put("device_id", IEMINo);
                        Log.d("jsonresult", RawResult.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    product_scanned = getBarcodeMqttObject(false, rawResult.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    RawResult = new JSONObject();
                    try {
                        RawResult.put("code", rawResult.toString());
                        RawResult.put("code_type", "bar");
                        RawResult.put("store_id", "BPR_50622052018");
                        RawResult.put("device_id", IEMINo);
                        Log.d("jsonresult", RawResult.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    product_scanned = getBarcodeMqttObject(true, rawResult.toString());
                    try {
                        pahoMqttClient.publishMessage(client, RawResult.toString(), 0, MqttConstant.PRODUCT_CODE + IEMINo);
                    } catch (MqttException | UnsupportedEncodingException x) {
                        x.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //-----------------------------------Based on Mqtt Message which Activity must Open------------------------//
            try {
                if (message.equals("NEW USER")) {
                    Log.e("new-user-id", UserID);
                    //   Toast.makeText(this, "NEW USER!!!", Toast.LENGTH_LONG).show();
                    Intent a = new Intent(BarcodeDump.this, FormAct.class);
                    a.putExtra("productURL", rawResult.toString());
                    a.putExtra("RawResult", RawResult.toString());
                    a.putExtra("product-url", urlprod);
                    a.putExtra("productscan", product_scanned);
                    a.putExtra("userid", UserID);
                    a.putExtra("message", message);
                    startActivity(a);
                    finish();
                } else if (message.equals("error_no_face")) {
                    Log.e("new-user-id", UserID);
                    //   Toast.makeText(this, "ErrorFace", Toast.LENGTH_LONG).show();
                    Intent c = new Intent(BarcodeDump.this, FormAct.class);
                    c.putExtra("productURL", rawResult.toString());
                    c.putExtra("product-url", urlprod);
                    c.putExtra("RawResult", RawResult.toString());
                    c.putExtra("productscan", product_scanned);
                    c.putExtra("userid", UserID);
                    c.putExtra("message", message);
                    startActivity(c);
                    finish();
                } else {
                    try {
                        pahoMqttClient.publishMessage(client, product_scanned, 0, MqttConstant.PUBLISH_TOPIC + IEMINo);
                    } catch (MqttException | UnsupportedEncodingException x) {
                        x.printStackTrace();
                    }
                    //   Toast.makeText(this, "Else Block", Toast.LENGTH_LONG).show();
                    Intent b = new Intent(BarcodeDump.this, ResultActivity.class);
                    b.putExtra("productURL", rawResult.toString());
                    b.putExtra("product-url", urlprod);
                    b.putExtra("RawResult", RawResult.toString());
                    b.putExtra("productscan", product_scanned);
                    b.putExtra("userid", userID);
                    startActivity(b);
                    finish();

                }
            } catch (Exception e) {
                //   Toast.makeText(this, "Welcome To BPRISE STORE!!!!", Toast.LENGTH_LONG).show();
                try {
                    pahoMqttClient.publishMessage(client, product_scanned, 0, MqttConstant.PUBLISH_TOPIC + IEMINo);
                } catch (MqttException | UnsupportedEncodingException x) {
                    x.printStackTrace();
                }
                Intent b1 = new Intent(BarcodeDump.this, ResultActivity.class);
                b1.putExtra("productURL", rawResult.toString());
                b1.putExtra("product-url", urlprod);
                b1.putExtra("RawResult", RawResult.toString());
                b1.putExtra("productscan", product_scanned);
                b1.putExtra("userid", userID);
                startActivity(b1);
                finish();
            }
        }

        //------------------------------------Getting the Bar/QR Code Object as an JSON----------------------------//
        @NotNull
        @SuppressLint("SimpleDateFormat")
        private String getBarcodeMqttObject(Boolean isBarcode, String result) {
            try {
                Date currentDate = new Date();
                barcodeMqtt = new JSONObject();
                Log.e("userid", userID);
                Log.e("new-user : id", UserID);
                Log.e("b-obj-museriD", muserID);
                barcodeMqtt.put("device_id", MqttConstant.getIMEI(BarcodeDump.this));
                if (!muserID.equals(EMPTY)) {
                    UserID = muserID;
                } else {
                    Log.e("user--id--issue", "OOPS ID ISSUE");
                }
                try {
                    if (message.equals("NEW USER")) {
                        barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.USER_UUID, "None");
                        barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.USER_ID, UserID);
                    } else if (message.equals("error_no_face")) {
                        barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.USER_UUID, "None");
                        barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.USER_ID, UserID);
                    } else if (message.contains("userUUID")) {
                        barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.USER_UUID, uuserUUID);
                        barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.USER_ID, UserID);
                    } else {
                        barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.USER_UUID, "None");
                        barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.USER_ID, userID);
                    }
                } catch (Exception e) {
                    barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.USER_ID, userID);
                    e.printStackTrace();
                }
                if (isBarcode) {
                    barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.BARCODE, result);
                    barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.QRCODE, "None");
                } else {
                    barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.BARCODE, "None");
                    barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.QRCODE, result);
                }
                barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.STORE, "Chakala");
                barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.SCANNED_DATE, new SimpleDateFormat("dd/MM/YYYY").format(currentDate));
                barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.SCANNED_TIME, new SimpleDateFormat("hh:mm:ss").format(currentDate));
                barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.DEVICE_IEMI, "None");//AppConstants.getIMEI(BarcodeActivity.this)
                barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.DEVICEID_UUID, AppConstants.getDeviceUniqueID(BarcodeDump.this));
                barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.APP_VERSION, AppConstants.appVersion);
                barcodeMqtt.put(MqttConstants.PRODUCT_SCANNED.OS, "Android " + AppConstants.version);
                //  barcodeMqtt.put("UserID",userID);
                Log.d("barcode-dump", barcodeMqtt.toString());
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
            return barcodeMqtt.toString();
        }
        //------------------------------------Setting all Formats of Bar-code for the Method---------------------------//
        public void setupFormats() {
            List<BarcodeFormat> formats = new ArrayList<>();
            if (mSelectedIndices == null || mSelectedIndices.isEmpty()) {
                mSelectedIndices = new ArrayList<>();
                for (int i = 0; i < ZXingScannerView.ALL_FORMATS.size(); i++) {
                    mSelectedIndices.add(i);
                }
            }

            for (int index : mSelectedIndices) {
                formats.add(ZXingScannerView.ALL_FORMATS.get(index));
            }
            if (mScannerView != null) {
                mScannerView.setFormats(formats);
            }
        }
    }
...