android – Facing issue in Connecting With Mqtt

Getting an exception in MQTT Connect, I am using QOS-2, once I kill my app during the data received that I won’t able to reconnect Exception are given below:-

onFailure Attempt to invoke virtual method ‘java.lang.Object byte().clone()’ on a null
object reference
onFailure org.eclipse.paho.android.service.MqttAndroidClient@3286954

class MqttMallConnectionService : Service(), MqttCallback, MqttTraceHandler,
IMqttActionListener {

private val TAG: String = MqttMallConnectionService::class.java.simpleName
private var brokerAddress: String? = null
private var clientId: String? = null
private var mqttAndroidClient: MqttAndroidClient? = null
private var mqttConnectOptions: MqttConnectOptions? = null
private var projectId: String = ""
private var deviceId: String = ""

companion object {
    private var handler: Handler? = null
    private var mIsConnecting = false
    private var isRunning = false
}

private fun getClient(): MqttAndroidClient? {
    return mqttAndroidClient
}

override fun onCreate() {
    super.onCreate()
    try {
        handler = Handler()
        brokerAddress = "**** some addresss"
        // serverUri = "tcp://" + AppModule.preferencesManager.getStringForKey(PwConstants.SubscriberRegistration.brokerUrl.toString())
        infoLog(TAG, "serverUri: $brokerAddress ")
        projectId = AppModule.preferencesManager.getStringForKey(PwConstants.PROJECT_ID).toString()
        deviceId = AppModule.preferencesManager.getStringForKey(PwConstants.POSID).toString()
        if (projectId.isEmpty() || deviceId.isEmpty() || brokerAddress.isNullOrEmpty()) {
            Toast.makeText(this, "Config data is missing", Toast.LENGTH_SHORT).show()
        }
        clientId = "$projectId-$deviceId"
        debugLog(TAG, "Client Id : $clientId and mqtt adress = $brokerAddress")
        mqttAndroidClient = MqttAndroidClient(this, brokerAddress, clientId)
        debugLog(TAG, "MqttAndroidClient isConnected : ${mqttAndroidClient?.isConnected}")
        buildMqttClient()
        Handler().postDelayed({
            connect()
        }, 60000)

        EventBus.getDefault().register(this)
    } catch (e: MqttException) {
        e.printStackTrace()
    }
}

private fun buildMqttClient() {
    mqttConnectOptions = MqttConnectOptions()
    mqttConnectOptions?.isCleanSession = false
    mqttConnectOptions?.connectionTimeout = 30  // 10 sec
    mqttConnectOptions?.keepAliveInterval = 30  //10sec
    mqttConnectOptions?.isAutomaticReconnect = false
    mqttAndroidClient?.setCallback(this)
    mqttAndroidClient?.setTraceCallback(this)
    mIsConnecting = true
}

override fun onBind(intent: Intent?): IBinder? {
    return null
}

@Throws(MqttException::class)
fun connect() {
    debugLog(TAG, "initiating connection to mqtt")
    mqttAndroidClient?.connect(mqttConnectOptions, null, this)
   // mqttAndroidClient?.acti = this
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    if (!isRunning) {
        debugLog(TAG, "onStartCommand")
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                MoaNotificationManager.createNotificationChannelForMQttService()
            }
            val notification = MoaNotificationManager.buildNotification(
                MoaNotificationManager.MQtt_CHANNEL_ID,
                "MOA",
                "Data Syncing"
            )
            debugLog("---->>>> mqtt started")
            startForeground(24, notification.build())
            isRunning = true
            retryConnection()
        } catch (e: Exception) {
        }
    }
    return START_STICKY
}

@org.greenrobot.eventbus.Subscribe()
fun publishEvent(mqttPublishData : MqttPublishData?) {
    GlobalScope.launch {
        AppLogger.infoLog(TAG, "Subscribe publishEvent")
        publishEventToMqtt(mqttPublishData)
    }
}
/**
 * Callback from Trace Handler
 */
override fun traceDebug(tag: String, message: String) {
    debugLog(TAG, "$tag $message")
}

override fun traceError(tag: String, message: String) {
    debugLog(TAG, "$tag $message")
}

override fun traceException(
    tag: String?,
    message: String?,
    e: Exception
) {
    e.printStackTrace()
}

/**
 * Callback from MQTT Connect
 */
override fun onSuccess(asyncActionToken: IMqttToken?) {
    debugLog(TAG, "Mqtt onSuccess connection made")
   // currentTimeInMillies = System.currentTimeMillis()
    if (mIsConnecting) {
        mIsConnecting = false
        setMqttConnectionStatus(true)
        subscribe()
       // GlobalScope.launch { publishEventToMqtt(null) }
    }
}

private fun setMqttConnectionStatus(status: Boolean) {
    AppModule.preferencesManager.setValueForKey(PwConstants.MQTT_CONNECTED_TO_SERVER, status)
}

override fun onDestroy() {
    try {
        if (getClient() != null)
            getClient()?.unsubscribe(getTopicsToSubscribe())
        isRunning = false
        mqttAndroidClient?.unregisterResources()
        handler?.removeCallbacksAndMessages(reconnectRunnable)
        EventBus.getDefault().unregister(this)
    } catch (e: Exception) {
        e.stackTrace
    }
    super.onDestroy()
    debugLog(TAG, "onDestroy")
}

private fun subscribe() {
    val qos = 2
    try {
        getClient()?.subscribe(getTopicsToSubscribe(), qos)
        debugLog(TAG, "Subscribed to topic")
    } catch (e: MqttSecurityException) {
        e.printStackTrace()
    } catch (e: MqttException) {
        e.printStackTrace()
    }
}

private fun getTopicsToSubscribe(): String {
    infoLog(TAG, "Topic to Subscribe - ${PwConstants.SubscriberRegistration.subscribeTopic.toString()}")
    return "t1"
    //return PwConstants.SubscriberRegistration.subscribeTopic.toString()
}

override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable) {
    errorLog(TAG, "onFailure ${exception.message}")
    setMqttConnectionStatus(false)
    exception.printStackTrace()
    try {
        errorLog(TAG, "onFailure ${mqttAndroidClient}")
        retryConnection()
    }catch (e:Exception){ }


}

override fun connectionLost(cause: Throwable?) {
    debugLog(TAG, "connectionLost")
    infoLog(TAG, "Cause: $cause")
    retryConnection()
}

private fun retryConnection() {
    handler?.postDelayed(reconnectRunnable, 10000)
}

/**
 * Callback from action listener
 */
@Throws(Exception::class)
override fun messageArrived(topic: String, message: MqttMessage) {
    GlobalScope.launch {
        AppLogger.debugLog(TAG, " on message arrived - $message, mid - ${message.id},   dup - ${message.isDuplicate}")
      /*  try {
            val mqttMessage: MqttMallResponse =
                GsonBuilder()
                    .excludeFieldsWithoutExposeAnnotation()
                    .create()
                    .fromJson<MqttMallResponse>(
                        message.toString(),
                        MqttMallResponse::class.java
                    )
            MqttFactory.updateDataInDB(mqttMessage)
        } catch (e: Exception) {
            debugLog(TAG, "Exception ${e.message} MqttResponseMessage: $message")
        }*/
    }
}


override fun deliveryComplete(token: IMqttDeliveryToken?) {
    debugLog(TAG, "deliveryComplete")
}

private val reconnectRunnable = Runnable {
    try {
        connect()
    } catch (e: MqttException) {
        e.printStackTrace()
    }
}

private suspend fun publishEventToMqtt(data: MqttPublishData?){
    try {
        data?.let { AppModule.dbHelperImpl.getPublishDataDao().addPublishData(it) }
        if (mqttAndroidClient!!.isConnected) {
            val list = AppModule.dbHelperImpl.getPublishDataDao().getAllUnPublishMessages()
            list?.let { list ->
                if(list.isNotEmpty()){
                    for(item in list){
                        val message = MqttMessage()
                        message.payload = item.message.toByteArray(Charset.defaultCharset())
                        message.id= item.id
                        message.qos = 2
                        AppModule.dbHelperImpl.getPublishDataDao().updateIsSent(item.id)
                        infoLog(TAG, "publish message Id - ${item.id}")
                        mqttAndroidClient!!.publish(item.topic, message, null, object : IMqttActionListener {
                            override fun onSuccess(asyncActionToken: IMqttToken) {
                                val messageId = (asyncActionToken as IMqttDeliveryToken).message.id
                                GlobalScope.launch { AppModule.dbHelperImpl.getPublishDataDao().deleteData(messageId)}
                                infoLog(TAG, "publish succeed! id - $messageId")
                            }

                            override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
                                val messageId = (asyncActionToken as IMqttDeliveryToken).message.id
                                infoLog(TAG, "publish failed! - id $messageId")
                                GlobalScope.launch { AppModule.dbHelperImpl.getPublishDataDao().resetIsSent(messageId)}
                            }
                        })
                    }
                }
            }
        } else{
            mqttAndroidClient!!.connect()
        }

    } catch (e: MqttException) {
        errorLog(TAG, e.toString())
        e.printStackTrace()
    }
}

}

amazon web services – mqtt error code RC = -1 connecting while esp32 to aws

I am going to establish a mqtt connection to aws. DHT senstor reading must be sent from esp32 to aws. How can I fix the error RC = -1 when connecting esp32 to aws. I receive this error in serial monitor :
Attempting MQTT connection…failed, rc=-1 try again in 5 seconds

What can be the reaon?

My code is as follows:

#include "SPIFFS.h"
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <DHT.h>  // library for getting data from DHT


// Enter your WiFi ssid and password
const char* ssid = "TP-Link_DBCA"; //Provide your SSID
const char* password = "44388027"; // Provide Password
const char* mqtt_server = "a3k7086cinb3bt-ats.iot.us-west-2.amazonaws.com"; // Relace with your MQTT END point
const int   mqtt_port = 8883;

String Read_rootca;
String Read_cert;
String Read_privatekey;
#define BUFFER_LEN 256
long lastMsg = 0;
char msg(BUFFER_LEN);
int Value = 0;
byte mac(6);
char mac_Id(18);
int count = 1;

WiFiClientSecure espClient;
PubSubClient client(espClient);



#define DHTPIN 4        //pin where the DHT22 is connected 
DHT dht(DHTPIN, DHT11);

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived (");
  Serial.print(topic);
  Serial.print(") ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload(i));
  }
  Serial.println();
}
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("ei_out", "hello world");
      // ... and resubscribe
      client.subscribe("ei_in");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  dht.begin();
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(2, OUTPUT);
  setup_wifi();
  delay(1000);
  //=============================================================
  if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }
  //=======================================
  //Root CA File Reading.
  File file2 = SPIFFS.open("/AmazonRootCA1.pem", "r");
  if (!file2) {
    Serial.println("Failed to open file for reading");
    return;
  }
  Serial.println("Root CA File Content:");
  while (file2.available()) {
    Read_rootca = file2.readString();
    Serial.println(Read_rootca);
  }
  //=============================================
  // Cert file reading
  File file4 = SPIFFS.open("/certificate.pem.crt.txt", "r");
  if (!file4) {
    Serial.println("Failed to open file for reading");
    return;
  }
  Serial.println("Cert File Content:");
  while (file4.available()) {
    Read_cert = file4.readString();
    Serial.println(Read_cert);
  }
  //=================================================
  //Privatekey file reading
  File file6 = SPIFFS.open("/private.pem.key", "r");
  if (!file6) {
    Serial.println("Failed to open file for reading");
    return;
  }
  Serial.println("privateKey File Content:");
  while (file6.available()) {
    Read_privatekey = file6.readString();
    Serial.println(Read_privatekey);
  }
  //=====================================================

  char* pRead_rootca;
  pRead_rootca = (char *)malloc(sizeof(char) * (Read_rootca.length() + 1));
  strcpy(pRead_rootca, Read_rootca.c_str());

  char* pRead_cert;
  pRead_cert = (char *)malloc(sizeof(char) * (Read_cert.length() + 1));
  strcpy(pRead_cert, Read_cert.c_str());

  char* pRead_privatekey;
  pRead_privatekey = (char *)malloc(sizeof(char) * (Read_privatekey.length() + 1));
  strcpy(pRead_privatekey, Read_privatekey.c_str());

  Serial.println("================================================================================================");
  Serial.println("Certificates that passing to espClient Method");
  Serial.println();
  Serial.println("Root CA:");
  Serial.write(pRead_rootca);
  Serial.println("================================================================================================");
  Serial.println();
  Serial.println("Cert:");
  Serial.write(pRead_cert);
  Serial.println("================================================================================================");
  Serial.println();
  Serial.println("privateKey:");
  Serial.write(pRead_privatekey);
  Serial.println("================================================================================================");

  espClient.setCACert(pRead_rootca);
  espClient.setCertificate(pRead_cert);
  espClient.setPrivateKey(pRead_privatekey);

  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);

  //====================================================================================================================
  WiFi.macAddress(mac);
  snprintf(mac_Id, sizeof(mac_Id), "%02x:%02x:%02x:%02x:%02x:%02x",
           mac(0), mac(1), mac(2), mac(3), mac(4), mac(5));
  Serial.print(mac_Id);
  //=====================================================================================================================
  delay(2000);
}


void loop() {
  float h = 80;   // Reading Temperature form DHT sensor
  float t = 22.5;      // Reading Humidity form DHT sensor
  float tF = (t * 1.8) + 32;
  if (isnan(h) || isnan(t))
  {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    //=============================================================================================
    String macIdStr = mac_Id;
    String Temprature = String(t);
    String Humidity = String(h);
    snprintf (msg, BUFFER_LEN, "{"mac_Id" : "%s", "Temprature" : %s, "Humidity" : "%s"}", macIdStr.c_str(), Temprature.c_str(), Humidity.c_str());
    Serial.print("Publish message: ");
    Serial.print(count);
    Serial.println(msg);
    client.publish("temp/", msg);
    count = count + 1;
    //================================================================================================
  }
  digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(2, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}```

java – Is there any sample implementation of MQTT for connecting an android device to PC?

I am working on a project in which i need to connect an Android device to a PC through adapter adapter.
the plan is to use MQTT protocol for connecting them and implement the MQTT client and use an open source MQTT broker.
My questions are:

  1. Is there any suggestion for MQTT broker? I found mosquitto and moquette. Although the download link for binary listener for the second is dead.
  2. Is there any sample project that uses USBC -> ethernet for mqtt client and mqtt broker? (more preferably in Java as this should be used on Android device)

it would be great if the sample project shows how the following steps will be implemented for the use case i explained (borrowed the following example from this git-repository).

//publish
    MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
    client.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload(messageString.getBytes());
    client.publish("iot_data", message);

    System.out.println("tMessage '"+ messageString +"' to 'iot_data'");

    client.disconnect();

//subscribe
    MqttClient client=new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
    client.setCallback( new SimpleMqttCallBack() );
    client.connect();

    client.subscribe("iot_data");

javascript – Mqtt Sending and Reciving Image

I am currently working on a project in which I want to send an image from raspberry pi to a broker then i want to diplay it to a web app (nodeJs backend and angular front).

This image would be sent from the back to the front and be displayed in real time using Socket.io.

I managed to create the sending part from the raspberry but I am having difficulties with the receiving part (I am new to this)

Can anybody point me in the right direction? I’m a bit lost in the matter.

c++ – Is it possible to transfer a mp3 file via mqtt?

I’m trying to make a project in ESP32. The main goal is to play a mp3 file in a codec, but I have 2 possible ways to get this file:

  1. Recieve it from a MQTT Broker, which I don’t know if it’s possible. I have been reading a lot in different pages, but I can’t find a clear answer. For example, I have read that Mosquitto an publish a file, or pahoMqtt, but there is no info about how I got the file when I subscribe, because people usually use them to publish simple arrays, but not files.

  2. The other option is to recieve an URL from the broker and download a file from this site. The problem is that the information that I found is that it’s easy to download txt files, but I can’t find the way to download a mp3 file from a website with the HTTPClient libraries.

If someone has any information, or knows about any similar project, pleas contact me!

Thank you so much! :]

security – How Authorize/Authenticate a users (not a machine) in AWS-IoT-Core MQTT broker?

In the AWS-IoT-Core the Authentication & Authorization are made by polices and certificate in order to restrict a THING to get access to the MQTT broker, publish or subscribe to a specific topic. In this scenario I have a topic attached to a lambda that will apply a DELETE operation in a database. The machine (the thing) is already authorized/authenticated trough certificates/policies but let’s say a hacker got access to the machine and to its certificate. Reading the Firmware he will see the a topic to dele a file, for example p/serialNumber/deletelog/log_nb. Now the hacker, trough the machine, is authorized and authenticated to publish in this topic. I would like to know if it is possible to mitigate this action (in this scenario) by creating a kind of Authorization SESSION, like a HTTP SESSION in the MQTT architecture. In this scenario the hacker would need a login and password to be Authorized to this operation (not only the machine). It would be another layer of security.

multithreading – How to subscribe additional topics in threaded mqtt (based on libmosquitto)?

I am using mosquitto.hin pure C to connect to a MQTT broker. All fine so far for single threaded code.

But now I have threaded code and created a thread who listens with mosquitto_loop_forever() to a given topic for any updates from the subscriber. The subscription by mosquitto_subscribe() is done in the main thread.

Now I want to subscribe to additional topics.

Can I subscribe in the main program additional topics simply by using mosquitto_subscribe()? And my thread will realize this? Or do I have to reconnect in some way?

Thank you!
/KNEBB

penetration test – MQTT – Man in The Middle Attack

I’m trying to perform a MiTM attack using Ettercap.
where i’m trying to publish a message to topic “A” and using ettercap trying to replace topic “A” to topic “B”.

MQTT Subscribe to topic “A”

mosquitto_sub -t "A" -v

MQTT Subscribe to topic “B” : The place where i want to redirect the messages published to Topic “A”

mosquitto_sub -t "B" -v

MQTT Publish

mosquitto_pub -m "checking" -t "A" -d

Ettercap Filter
#owned.filter

if (ip.proto == TCP && tcp.dst == 1883 && ip.dst == '127.0.0.1' && search(DATA.data, "A")) {
replace("A", "B");
msg("payload replacedn");
}

Compiling the filter

etterfilter owned.filter -o owned.ef

Since i’m running performing all the operations on localhost. kept the interface to loopback ip
running the ettercap application

ettercap -T -q -i lo -F owned.ef -M ARP /// ///

Now the issue i’m facing is

**

JIT FILTER FAULT: Cannot modify packets in unoffensive mode payload
replaced

**
I’m not able to redirect the message for topic A to topic B. instead its is been send to Topic A itself. Where i might be going wrong? is this the right way to perform this MiTM attacK?
I’m not sure what is going wrong, I surfed the internet but couldn’t find any results.
What could be the reason I’m not able to modify the packet payload.
My test MQTT does not contain TLS or any authentication mechanism