Search code examples
javaandroidmqttpaho

MqttException (0) - java.net.SocketTimeoutException: failed to connect to /192.168.1.xx (port 1883) from /10.0.2.xx (port xxxxx) after 30000ms


I am very new to the mqtt on Android Development. So, I did something similar to this guide. https://www.hivemq.com/blog/mqtt-client-library-enyclopedia-paho-android-service/

I have tried to connect my android application from the Android Studio emulator to Mqtt broker. The broker is located in my Windows10 laptop (which is the same machine as the Android client). The problem I found is that my Android client cannot connect itself to the Mqtt broker ip. I've tried it in many ways but still couldn't get it work. So, I'm not sure if I'm doing it right?

Here is my build.gradle dependencies

dependencies {
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
}

In my setting.gladle file, I've added maven repository as below.

(This supposed to be in the build.gladle file, but I did it this way because I found out that build.gladle in the newer version of android studio has a different way to compile the app. When I first tried on that, it shows the message that 'syncing error'. So, I've included in the setting.gladle instead, to avoid that error.)

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()

        maven {
            url "https://repo.eclipse.org/content/repositories/paho-releases/"
        }
    }
}

The AndroidManifest.xml, I have included some permission and android service.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.smartmousetrap">

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SmartMouseTrap">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="org.eclipse.paho.android.service.MqttService"/>

    </application>

</manifest>

And this is all of the MainActivity.java where it has the connection problem

public class MainActivity extends AppCompatActivity {

    private Button buttonConnect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonConnect = findViewById(R.id.buttonConnect);
        buttonConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String clientId = MqttClient.generateClientId();
                Toast.makeText(MainActivity.this, clientId, Toast.LENGTH_SHORT).show();
                MqttAndroidClient client = new MqttAndroidClient(MainActivity.this, "tcp://192.168.1.43:1883", clientId);

                try {
                    IMqttToken token = client.connect();
                    token.setActionCallback(new IMqttActionListener() {
                        @Override
                        public void onSuccess(IMqttToken asyncActionToken) {
                            Log.d("Debug", "onSuccess");
                            Toast.makeText(MainActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                            Log.d("Debug", "onFailure");
                            Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
                            exception.printStackTrace();
                        }
                    });
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

First, I reference to the button using this variable. When the button get clicked, the application will connect itself to the Mqtt broker.

buttonConnect = findViewById(R.id.buttonConnect);

buttonConnect.setOnClickListener(new View.OnClickListener() {...})

===========================================

'192.168.1.43' is my laptop ip (broker)

MqttAndroidClient client = new MqttAndroidClient(MainActivity.this, "tcp://192.168.1.43:1883", clientId);

===========================================

After it tried 'client.connect', it ended up in this 'onFailure' section.

IMqttToken token = client.connect();

try {
    IMqttToken token = client.connect();
    token.setActionCallback(new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            Log.d("Debug", "onSuccess");
            Toast.makeText(MainActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            Log.d("Debug", "onFailure");
            Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
            exception.printStackTrace();
        }
    });
} catch (MqttException e) {
    e.printStackTrace();
}

This is the MqttException prompted error I've got.

Note that 10.0.2.16 is my android ip (from Android Studio emulator)

D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x75161b0e2c50, tid 7084
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
W/OpenGLRenderer: Failed to initialize 101010-2 format, error = EGL_SUCCESS
D/EGL_emulation: eglCreateContext: 0x75161b0e2650: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0x75161b0e2650: ver 2 0 (tinfo 0x751835ee2080) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x75161b0e2110, tid 7084
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3efffe000 size 0x2000
W/Gralloc4: allocator 4.x is not supported
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
W/System: A resource failed to call close. 
D/EGL_emulation: app_time_stats: avg=409.15ms min=4.48ms max=3278.83ms count=9
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10166; state: ENABLED
D/AlarmPingSender: Unregister alarmreceiver to MqttServicepaho3870573646500
D/AlarmPingSender: Unregister alarmreceiver to MqttServicepaho3870573646500
D/Debug: onFailure
W/System.err: MqttException (0) - java.net.SocketTimeoutException: failed to connect to /192.168.1.43 (port 1883) from /10.0.2.16 (port 56170) after 30000ms
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
W/System.err:     at java.lang.Thread.run(Thread.java:920)
W/System.err: Caused by: java.net.SocketTimeoutException: failed to connect to /192.168.1.43 (port 1883) from /10.0.2.16 (port 56170) after 30000ms
W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:236)
W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:180)
W/System.err:     at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:142)
W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err:     at java.net.Socket.connect(Socket.java:621)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
W/System.err:   ... 1 more

If I done anything wrong or any suggestion please help.


Solution

  • Following something like:

    How do you connect localhost in the Android emulator?

    you probably need to access the broker on:

    10.0.2.2:1883