Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket error for client identifier on RSMB MQTT broker when using android

Tags:

android

mqtt

I am building a simple MQTT client for android, and I am getting the "Socket error for client identifier" error on the RMBS console. This only happens in the android implementation of the client ( I also created a Java desktop client and runs with no problems). For the Android client, I am suing the Paho Java client libraries. Here is my code:

This is the Android Client:

package com.example.mqttdroid;

import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.internal.MemoryPersistence;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MQTTClient extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mqttclient);
//  new BackTask().execute(); not used because (seems to be the problem)
  MqttConnectOptions conOpts = new MqttConnectOptions();
            conOpts.setKeepAliveInterval(30);
            conOpts.setWill(client.getTopic("Error"), "something bad happened".getBytes(), 1, true);
            client.connect(conOpts);

            client.subscribe("/House/Kitchen/Bulb");
            client.setCallback( new MqttCallback() {



                @Override
                public void connectionLost(Throwable arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void messageArrived(String arg0, MqttMessage arg1)
                        throws Exception {
                    // TODO Auto-generated method stub
                    Toast.makeText(Main.this, arg0.toString(), Toast.LENGTH_SHORT).show();
                }
            });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mqttclient, menu);
    return true;
}

/*public class BackTask extends AsyncTask<Void, Void, Void>{

    private MqttClient client;
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {

            client = new MqttClient("tcp://"Ip of machine running RSMB":1883", "ANDROID1", new MemoryPersistence());

            client.connect();
            client.subscribe("House/Kitchen/Bulb");


        } catch (MqttException e) {
            // TODO Auto-generated catch block
            Log.e("ERROR", "NOT CONNECTED");
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        try {
            client.setCallback( new MqttCallback() {

                @Override
                public void messageArrived(MqttTopic arg0, MqttMessage arg1)
                        throws Exception {
                    // TODO Auto-generated method stub
                    Toast.makeText(MQTTClient.this, arg0.toString(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void deliveryComplete(MqttDeliveryToken arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void connectionLost(Throwable arg0) {
                    // TODO Auto-generated method stub

                }
            });
        } catch (MqttException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 }*/

This is the Desktop Java Client:

 import org.eclipse.paho.client.mqttv3.MqttCallback;
 import org.eclipse.paho.client.mqttv3.MqttClient;
 import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
 import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
 import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
 import org.eclipse.paho.client.mqttv3.MqttException;
 import org.eclipse.paho.client.mqttv3.MqttMessage;
 import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
 import org.eclipse.paho.client.mqttv3.MqttTopic;
 import org.eclipse.paho.client.mqttv3.internal.MemoryPersistence;



 public class MQTTBaseClass {

/**
 * @param args
 */

public static void main(String[] args) {
    // TODO Auto-generated method stub
    MqttClientPersistence persistence;
    try {

        MqttClient client = new MqttClient("tcp://localhost:1883", "PC",new      MemoryPersistence());
        MqttConnectOptions conOpts = new MqttConnectOptions();
        conOpts.setKeepAliveInterval(30);
        conOpts.setWill(client.getTopic("Error"), "something bad happened".getBytes(), 1, true);
        client.connect(conOpts);
        MqttMessage msg = new MqttMessage("hello".getBytes());
        msg.setQos(0);
        msg.setRetained(true);
        MqttTopic topic = client.getTopic("House/Kitchen/Bulb");
        client.subscribe("House/Kitchen/Bulb");

        try {
            client.setCallback( new MqttCallback() {

                @Override
                public void messageArrived(MqttTopic arg0, MqttMessage arg1)
                        throws Exception {
                    // TODO Auto-generated method stub
                    System.out.println(arg1.toString());
                }

                @Override
                public void deliveryComplete(MqttDeliveryToken arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void connectionLost(Throwable arg0) {
                    // TODO Auto-generated method stub

                }
            });
        } catch (MqttException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        topic.publish(msg);


    } catch (MqttPersistenceException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MqttException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}






 }

Just a few notes:

I am connected on my android device via WiFi, and so is my desktop when I run the Java Dekstop client.

The Java Destop Client is running on the same machine as the RSMB

The Java Desktop Client creates and subscirbes to the topic "House/Kitchen/Bulb" and sends a message with the String "Hello"

The Android Client also subscribes to "House/Kitchen/Bulb" and attempts to display a Toast with the received message.

I have addeded the Internet permission on the android manifest

The android device seems to connect to the broker just fine, but as soon as I initialize the Java Desktop Service client (or the Paho client plug-in in Eclipse and publish a message) I get the error mentioned.

I ran the app using the emulator on the same machine the RSMB runs, and I get the same error.

What might be the problem?

UPDATE:

Originally, I got a "Network on Main Thread" Exception, so I moved the connect operation to an AsyncTask. Now it seems that the Android Client is still connected when I publish a message with the Java Client(Asynctask might have been creating issues), but the messageArrived() of the MqttCallback() doesn't seem to be called.

UPDATE 2:

I managed to make it work. Here is the code I am using now:

package com.example.mqttphone;

*import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;*

public class Main extends Activity {
protected static String msg;
public MqttClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {

        client = new MqttClient("tcp://10.1.201.27:1883", "ANDROID1", new MemoryPersistence());

        MqttConnectOptions conOpts = new MqttConnectOptions();
        conOpts.setKeepAliveInterval(30);
        conOpts.setWill(client.getTopic("Error"), "something bad happened".getBytes(), 1, true);
        client.setCallback( new MqttCallback() {



            @Override
            public void connectionLost(Throwable arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void messageArrived(String arg0, MqttMessage arg1)
                    throws Exception {
                // TODO Auto-generated method stub
            Main.msg = arg1.toString();
            Main.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    Toast.makeText(Main.this, msg, Toast.LENGTH_LONG).show();
                }
            });
                Log.e("MESSAGE RECEIVED", arg1.toString());

            }
        });
        client.connect(conOpts);
        //MqttMessage msg = new MqttMessage("ANDROID MESSAGE".getBytes());
        //client.getTopic("world").publish(msg);

        if(client.isConnected()){

        client.subscribe("/House/Kitchen/Bulb");


            Toast.makeText(this, "CONNECTED", Toast.LENGTH_SHORT).show();

        }



    } catch (MqttException e) {
        // TODO Auto-generated catch block
        Log.e("ERROR", "NOT CONNECTED");
        e.printStackTrace();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


}
like image 665
Emmanuel Avatar asked Apr 17 '13 15:04

Emmanuel


2 Answers

Hello
I have use your code but I can not connect my paho client to my apollo server I have get below error.

 I/global(677): Default buffer size used in BufferedOutputStream constructor. It would be better to be explicit if an 8k buffer is required.
 E/ERROR(677): NOT CONNECTED
 W/System.err(677):  (32109) - java.io.EOFException
 W/System.err(677):     at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:127)
 W/System.err(677):     at java.lang.Thread.run(Thread.java:1096)
 W/System.err(677): Caused by: java.io.EOFException
 W/System.err(677):     at java.io.DataInputStream.readFully(DataInputStream.java:266)
 W/System.err(677):     at org.eclipse.paho.client.mqttv3.internal.wire.MqttInputStream.readMqttWireMessage(MqttInputStream.java:63)
 W/System.err(677):     at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:94)
 W/System.err(677):     ... 1 more

Thanks
Girish

like image 99
Girish Bhutiya Avatar answered Oct 13 '22 11:10

Girish Bhutiya


I got it working. Here is a link to the github repository where everyone can find a project that implements this code. It allows users to turn on a LED light remotely using their Android device via voice recognition.

like image 38
Emmanuel Avatar answered Oct 13 '22 09:10

Emmanuel