MQTT broker not connecting after internet disconnect and reconnect in Android 10 - android

In my application i connect to IOT Device at that internet got disconnect and connection with MQTT Broker also disconnect then i send wifi to my IOT Device through TCP client and closing the socket i reconnect my internet connection after internet is connected again when i hit to re-establish connection with MQTT broker i got this ERROR:
MqttException (0) - java.net.SocketException: socket failed: ENONET (Machine is not on the network)
private fun initMQTTConnector() {
clientID = Installation.id(context)
client = MqttAndroidClient(
context, String.format(
"%s:%s",
BuildConfig.mqtt_server_url,
BuildConfig.mqtt_server_port
),
clientID, MemoryPersistence()
)
client!!.setCallback(listener)
Timber.e(
"qq - " + String.format(
"%s:%s",
BuildConfig.mqtt_server_url, //"tcp://192.168.1.164"
BuildConfig.mqtt_server_port
) + " -- " + clientID
)
connectToMQTTServer()
}
fun connectToMQTTServer() {
try {
if(client == null){
Timber.e("qq - client")
initMQTTConnector()
}else{
Timber.e("qq - Retrying the MQTT connection...!")
val options = MqttConnectOptions()
options.setCleanSession(false) // change for mqtt connection issue
options.setAutomaticReconnect(true)
options.userName = BuildConfig.mqtt_server_user_name
options.password = BuildConfig.mqtt_server_password.toCharArray()
options.setKeepAliveInterval(90) //seconds
token = client!!.connect(options)
eventBusManager?.post(
EventBusManager.MessageEvent(
EventBusConstants.MQTT_CONNECTING
)
)
token?.actionCallback = object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
// We are connected
Timber.e("qq - onSuccess for connection :: token.actionCallback")
// Timber.d("onSuccess for connection")
eventBusManager?.post(
EventBusManager.MessageEvent(
EventBusConstants.MQTT_CONNECTED
)
)
subscribeToReportedTopic()
subscribeToLoadedDevicesReportedChannel()
}
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable?) {
// Something went wrong e.g. connection timeout or firewall problems
Timber.e("qq - onFailure for connection :: token.actionCallback - " + exception.toString())
eventBusManager?.post(
EventBusManager.MessageEvent(
EventBusConstants.MQTT_NOT_CONNECTED
)
)
exception?.printStackTrace()
// connectToMQTTServer()
}
}
}
} catch (e: Exception) {
eventBusManager?.post(
EventBusManager.MessageEvent(
EventBusConstants.MQTT_NOT_CONNECTED
)
)
Timber.e("qq - Error occurred while connecting MQTT Client, Error = " + e.toString())
e.printStackTrace()
}
}

Related

FTPClient.connect's parameter

I'm trying to connect ftp server with FTPClient.
but connect is not working.
I passed ip address and port number as parameters.
When i don't write port number, "Socket:failed to connect to /106.10.40.222 (port 21) from /:: (port 37510): connect failed: ECONNREFUSED (Connection refused)" is occuring.
Ip address is "106.10.40.222" and port is 1028.
I will do download file in stp server after connecting.
fun ftpFileDownload(
uri: String?,
id: String?,
pw: String?,
localFile: String?,
ftpFile: String?,
directoryLocation: String?
) {
var ftp: FTPClient? = null
try {
ftp = FTPClient()
ftp.setControlEncoding("UTF-8")
ftp.connect(uri, 1028) //uri = "106.10.40.222"
} catch (e: SocketException) {
Log.d("kkang", "Socket:" + e.message)
} catch (e: IOException) {
Log.d("kkang", "IO:" + e.message)
} finally {
if (ftp != null && ftp.isConnected()) {
try {
ftp.disconnect()
} catch (e: IOException) {
}
}
}
}
I want to know how to connect in FTPClient

Cannot connect to socket.io in android , saying invalid namespace

When i try to connect my android app with socket.io, it saying invalid namespace. There is no issue with socket url , but having problem in connection, please help if you faced this issue ever. Thanks!
val options = io.socket.client.IO.Options().apply {
forceNew = false
reconnection = true
}
private val socket: Socket = io.socket.client.IO.socket(socket_url,options)
val socket = applicationAccessorImpl.socket
socket.connect()
socket.once(Socket.EVENT_CONNECT) {
try {
Log.d(TAG, "connect")
} catch (e: Exception) {
Log.d(TAG, e.message!!)
}
}.on(Socket.EVENT_CONNECT_ERROR) {
val e = it[0]
Log.e(TAG, "error $e")
}.on(Socket.EVENT_DISCONNECT) {
val e = it[0]
Log.e(TAG, "Transport error $e")
}
Sorry , it was my mistake , i was passing the wrong url 😋

Android TCP client trying to connect to server

I am trying to make a TCP client that will try to connect to a server. If the server cannot be reached then it must retry after a fixed time. If the connection is lost then it should try to re-connect again. When connected it should be able to read data from the server (ASCII strings). This piece of code is not working as intended [App crashing without a server].
How can I fix it? (Note: Server is extremely unreliable and cannot expect gracefully disconnect)
package com.thinkalvb.sensorstorm
import android.util.Log
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.Socket
import java.net.SocketException
private const val TAG = "Storm_Commander"
class Commander : Runnable {
private lateinit var mTcpSocket: Socket
override fun run() {
val serverAddress = MainActivity.serverAddress
val serverPort = MainActivity.portNumber
while(!Thread.currentThread().isInterrupted) {
try {
Log.d(TAG,"Waiting for Server")
mTcpSocket = Socket(serverAddress, serverPort)
mTcpSocket.soTimeout = 5000
mTcpSocket.keepAlive = true
val receiveBuffer = BufferedReader(InputStreamReader(mTcpSocket.getInputStream(), "UTF-8"))
Log.d(TAG,"Connected to Server")
while (true) {
val command = receiveBuffer.readLine()
if (command != null) {
Log.d(TAG, command)
}
}
} catch (e: SocketException) {
Log.e(TAG, "Socket Error:", e)
} catch (e: IOException) {
Log.e(TAG, "IO Error:", e)
} finally {
mTcpSocket.close()
Log.d(TAG,"Client socket closed")
}
}
}
}
The entire project is in Github https://github.com/ThinkalVB/SensorStorm
Errors:
2021-03-25 21:05:44.201 1865-1865/com.thinkalvb.sensorstorm D/Storm_Location: Location Service created
2021-03-25 21:05:44.204 1865-1865/com.thinkalvb.sensorstorm D/Storm_Acceleration: Acceleration Sensor created
2021-03-25 21:05:44.204 1865-1865/com.thinkalvb.sensorstorm D/Storm_Orientation: Orientation Sensor created
2021-03-25 21:05:44.290 1865-1865/com.thinkalvb.sensorstorm D/Storm_Camera: Camera Service created
2021-03-25 21:05:44.290 1865-1865/com.thinkalvb.sensorstorm D/Storm_Temperature: Temperature Sensor created
2021-03-25 21:05:44.292 1865-1865/com.thinkalvb.sensorstorm D/Storm_MainActivity: Main Activity created
2021-03-25 21:05:48.986 1865-1865/com.thinkalvb.sensorstorm D/Storm_MainActivity: Service starting
2021-03-25 21:05:48.987 1865-1957/com.thinkalvb.sensorstorm D/Storm_Commander: Waiting for Server
2021-03-25 21:07:56.396 1865-1957/com.thinkalvb.sensorstorm E/Storm_Commander: Socket Error:
java.net.ConnectException: failed to connect to /10.0.2.2 (port 1357) from /:: (port 37528): connect failed: ETIMEDOUT (Connection timed out)
at libcore.io.IoBridge.connect(IoBridge.java:137)
at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at java.net.Socket.connect(Socket.java:570)
at java.net.Socket.<init>(Socket.java:450)
at java.net.Socket.<init>(Socket.java:250)
at com.thinkalvb.sensorstorm.Commander.run(Commander.kt:20)
at java.lang.Thread.run(Thread.java:764)
Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
at libcore.io.Linux.connect(Native Method)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:118)
at libcore.io.IoBridge.connectErrno(IoBridge.java:151)
at libcore.io.IoBridge.connect(IoBridge.java:129)
at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137) 
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390) 
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230) 
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212) 
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436) 
at java.net.Socket.connect(Socket.java:621) 
at java.net.Socket.connect(Socket.java:570) 
at java.net.Socket.<init>(Socket.java:450) 
at java.net.Socket.<init>(Socket.java:250) 
at com.thinkalvb.sensorstorm.Commander.run(Commander.kt:20) 
at java.lang.Thread.run(Thread.java:764) 
2021-03-25 21:07:56.405 1865-1865/com.thinkalvb.sensorstorm D/Storm_MainActivity: Service stopping
A temporary solution for those looking for some code to start with.
while(!Thread.currentThread().isInterrupted) {
try {
Log.d(TAG, "Waiting for Server")
mTcpSocket = Socket()
mTcpSocket.connect(serverSocketAddress, 10000)
mTcpSocket.keepAlive = true
mTcpSocket.soTimeout = 15000
if(mTcpSocket.isConnected){
mTCPBufferIncoming = BufferedReader(InputStreamReader(mTcpSocket.getInputStream(), "UTF-8"))
Log.d(TAG, "Connected to Server")
processCommands()
}
mTcpSocket.close()
} catch (e: SocketException) {
Log.e(TAG, "Socket Error:", e)
} catch (e: IOException) {
Log.e(TAG, "IO Error:", e)
} catch (e: Exception) {
Log.e(TAG, "Exception:", e)
}
}
private fun processCommands()
{
var command: String
while (mTCPBufferIncoming.readLine().also { command = it } != null) {
Log.d(TAG, command)
}
}

Paho mqtt connection lost

I'm testing with paho mqtt client library with mosquitto.org broker service.
My connection code is at below.
buttonConnect.setOnClickListener{ view ->
val topic = textViewTopic.text.toString()
try {
val msg = "now connecting... " + textViewUrl.text as String?
Log.d(TAG, msg)
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
client.setCallback(this)
client.connect()
client.subscribe(topic, 1)
buttonConnect.visibility = View.GONE
buttonDisconnect.visibility = View.VISIBLE
} catch (ex: MqttException) {
ex.printStackTrace()
Toast.makeText(this, "$ex", Toast.LENGTH_LONG).show()
}
}
But whenever connection complete, connection is lost as below logs.
now connecting... tcp://test.mosquitto.org:1883 connectComplete
reconnect:false, URI:tcp://test.mosquitto.org:1883 connectionLost
connectComplete reconnect:true, URI:tcp://test.mosquitto.org:1883
connectionLost connectComplete reconnect:true,
URI:tcp://test.mosquitto.org:1883 connectionLost
Here is my full activity code.
What do I mistake?

Not able to connect with bluetooth device with socket in android studio

Hello everyone I am new to android development i am connecting with bluetooth device as a client in different class thread. If Nullpointerexcception occur then i use default UUID. After this when i use socket.connect() it show debug warning and don't send any pair request to device. Nothing happen. I am new to android development if any one can help. Thank you in advance.
Warning and Logs
here is my code in Thread;
class ConnectWithDevice(context : ConnectWithBluetooth, device : BluetoothDevice) : Thread(){
private val mContext : ConnectWithBluetooth = context
private val mmSocket : BluetoothSocket
private val mmDevice : BluetoothDevice
// Default UUID
private val mmDefaultUUID = UUID.fromString("78c374fd-f84d-4a9e-aa5b-9b0b6292952e")
init {
var temp : BluetoothSocket? = null
mmDevice = device
try {
temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)
}catch (en : NullPointerException){
en.printStackTrace()
temp = device.createRfcommSocketToServiceRecord(mmDefaultUUID)
}catch (e : IOException){
e.printStackTrace()
Log.e("TAG","Socket's create() method failed",e)
}
mmSocket = temp!!
Log.i("TAG","Got the Socket")
}
override fun run() {
// Cancel discovery because it otherwise slows down the connection.
if(mContext.bluetoothAdapter != null){
mContext.bluetoothAdapter!!.cancelDiscovery()
}
try{
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
Log.i("TAG","Connecting...")
mmSocket.connect()
Log.i("TAG","Bluetooth Successfully Connected")
}catch (connectException : IOException){
// Unable to connect; close the socket and return.
try{
mmSocket.close()
}catch (closeException : IOException){
Log.e("TAG","Could not close the client socket",closeException)
}
return
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
Log.i("TAG","Device is Connected")
//manageMyConnectedSocket(mmSocket)
}
// Closes the client socket and causes the thread to finish.
// Call this method from the main activity to shut down the connection.
fun cancel(){
try {
mmSocket.close()
} catch (e: IOException) {
Log.e(ContentValues.TAG, "Could not close the client socket", e)
}
}
}
Finally i find the solution here it is ->
I use this code ->
val m = device.javaClass.getMethod("createRfcommSocket", *arrayOf<Class<*>>(Int::class.java))
temp = m.invoke(device, 1) as BluetoothSocket
Instead of this ->
temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)

Categories

Resources