Error sending data to IoT central via MQTT

yjay 256 Reputation points
2021-03-01T21:15:45.903+00:00

Hello,

We have successfully sent data from our app to IoT central via http requests.

We are now looking into encrypting the data and have tried using MQTT following:

The azure iot sdk for java android example

Azure iot samples java

But we are encountering some errors:

 W/System.err: java.io.IOException: Could not open the connection  
    W/System.err: at com.microsoft.azure.sdk.iot.device.DeviceIO.open(DeviceIO.java:164)  
    at com.microsoft.azure.sdk.iot.device.InternalClient.open(InternalClient.java:130)  
    at com.microsoft.azure.sdk.iot.device.DeviceClient.open(DeviceClient.java:317)  
    at java.lang.Thread.run(Thread.java:764)  
    Caused by: com.microsoft.azure.sdk.iot.device.transport.mqtt.exceptions.MqttServerUnavailableException: Unable to establish MQTT connection  
    at com.microsoft.azure.sdk.iot.device.transport.mqtt.exceptions.PahoExceptionTranslator.convertToMqttException(PahoExceptionTranslator.java:57)  
    at com.microsoft.azure.sdk.iot.device.transport.mqtt.Mqtt.connect(Mqtt.java:125)  
    at com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttMessaging.start(MqttMessaging.java:56)  
    at com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttIotHubConnection.open(MqttIotHubConnection.java:180)  
    at com.microsoft.azure.sdk.iot.device.transport.IotHubTransport.openConnection(IotHubTransport.java:653)  
    at com.microsoft.azure.sdk.iot.device.transport.IotHubTransport.open(IotHubTransport.java:280)  
    at com.microsoft.azure.sdk.iot.device.DeviceIO.open(DeviceIO.java:160)  
    ... 6 more  
    Caused by: Broker unavailable (3)  
    W/System.err: at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:31)  
    at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988)  
    at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:145)  
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)  
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)  
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)  
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)  
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)  
    ... 1 more  

Here is the code:

package com.example.XXXXX;  
  
import android.util.Log;  
  
import com.google.gson.Gson;  
import com.microsoft.azure.sdk.iot.device.DeviceClient;  
import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol;  
import com.microsoft.azure.sdk.iot.device.IotHubEventCallback;  
import com.microsoft.azure.sdk.iot.device.IotHubStatusCode;  
import com.microsoft.azure.sdk.iot.device.Message;  
  
import java.io.IOException;  
import java.net.URISyntaxException;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
  
public class MyAsync {  
  
    private static String myData;  
  
    // The device connection string to authenticate the device with your IoT hub.  
    // Using the Azure CLI:  
    // az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyJavaDevice --output table  
    private static String connString = "XXXXXXXXX";  
  
    // Using the MQTT protocol to connect to IoT Hub  
    private static IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;  
    private static DeviceClient client;  
  
  
    public MyAsync(String myData) throws IOException, URISyntaxException {//(String myData) {  
        //Relevant Context should be provided to newly created components (whether application context or activity context)  
        //getApplicationContext() - Returns the context for all activities running in application  
        this.myData = myData;  
        main();  
    }  
  
    private static class EventCallback implements IotHubEventCallback {  
        public void execute(IotHubStatusCode status, Object context) {  
            System.out.println("IoT Hub responded to message with status: " + status.name());  
            if (context != null) {  
                synchronized (context) {  
                    context.notify();  
                }  
            }  
        }  
    }  
  
    private static class MessageSender implements Runnable {  
        @Override  
        public void run() {  
            Gson gson = new Gson();  
            String newData = gson.toJson(Integer.valueOf(myData));  
            Message msg = new Message(newData);  
            msg.setProperty("Content-type", "application/json");  
            Object lockobj = new Object();  
            EventCallback callback = new EventCallback();  
            client.sendEventAsync(msg, callback, lockobj);  
//            synchronized (lockobj) {  
//                try {  
//                    lockobj.wait();  
//                } catch (InterruptedException e) {  
//                    e.printStackTrace();  
//                }  
//            }  
        }  
    }  
  
    public static void main() throws IOException, URISyntaxException {  
  
        // Connect to the IoT hub.  
        client = new DeviceClient(connString, protocol);  
        client.open();  
  
        // Create new thread and start sending messages  
        MessageSender sender = new MessageSender();  
        ExecutorService executor = Executors.newFixedThreadPool(1);  
        executor.execute(sender);  
  
        // Stop the application.  
        System.in.read();  
        executor.shutdownNow();  
//        clienton mine.closeNow();  
    }  
}  

We have looked into similar errors others have posted:
“Connection is not open” FTP Android
Open Threads after 'Could not open the connection' azure response
Connection To The Azure Portal Timed Out With Java Custom Module
DeviceClient.open() in Android devices without internet make leak one thread

But have not yet been able to resolve our error.

Thanks so much!

Azure IoT
Azure IoT
A category of Azure services for internet of things devices.
382 questions
Azure IoT Central
Azure IoT Central
An Azure hosted internet of things (IoT) application platform.
348 questions
Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,124 questions
Azure IoT SDK
Azure IoT SDK
An Azure software development kit that facilitates building applications that connect to Azure IoT services.
208 questions
0 comments No comments
{count} votes

Accepted answer
  1. Tim Taylor 96 Reputation points
    2021-03-01T23:36:10.187+00:00

    Hi yjay-4307,

    There are a few reasons why you could see that error, so let's try to narrow down on it a bit. Do you know what API level your android application is set to? The Java Iot Hub SDK is only supported on Android API versions 24 and up. There are some known compatibility issues with older Android API versions and our MQTT library in particular.

    Do you see any errors when you use AMQP rather than MQTT?

    Thanks,
    -Tim

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful