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?
Related
I need to send my sensor data collected in a JSON file to the AWS cloud server at a particular time in the day automatically.
Here is the code I am using to upload the file manually
private fun uploadFile() {
val exampleFile = File(applicationContext.filesDir, "light.json")
val randomNumber = (1..999999999999999).random()
try {
val writer = BufferedWriter(FileWriter(exampleFile))
writer.append(jsonArray.toString())
writer.close()
} catch (exception: Exception) {
Log.e("MyAmplifyApp", "Upload failed", exception)
}
Amplify.Storage.uploadFile(
"Light-Sensor/light$randomNumber.json",
exampleFile,
{ result: StorageUploadFileResult ->
Log.i(
"MyAmplifyApp",
"Successfully uploaded: " + result.key
)
Toast.makeText(this, "File has Successfully Uploaded:" , Toast.LENGTH_SHORT).show()
}
) { storageFailure: StorageException? ->
Log.e(
"MyAmplifyApp",
"Upload failed",
storageFailure
)
Toast.makeText(this, "Upload failed", Toast.LENGTH_SHORT).show()
}
}
}
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 😋
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()
}
}
I'm making an android app for a school project, using Android Studio (Kotlin).
I need to send strings to an Arduino Genuino Uno module, passing by a HC-05 bluetooth module.
The Arduino will already be connected (paired) to my android device when the app will be launched.
Can someone help me to find a right and easy way to only SEND these datas ?
Thanks a lot.
I finally got the answer, I did that :
private fun CheckBt() {
Toast.makeText(applicationContext, "It has started", Toast.LENGTH_SHORT).show()
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
if (!mBluetoothAdapter.enable()) {
Toast.makeText(applicationContext, "Bluetooth Disabled !", Toast.LENGTH_SHORT).show()
/* It tests if the bluetooth is enabled or not, if not the app will show a message. */
finish()
}
if (mBluetoothAdapter == null) {
Toast.makeText(applicationContext, "Bluetooth null !", Toast.LENGTH_SHORT).show()
}
}
fun Connect() {
val device = mBluetoothAdapter.getRemoteDevice("98:D3:32:71:17:DE")
Log.d("", "Connecting to ... $device")
Toast.makeText(applicationContext, "Connecting to ... ${device.name} mac: ${device.uuids[0]} address: ${device.address}", Toast.LENGTH_LONG).show()
mBluetoothAdapter.cancelDiscovery()
try {
btSocket = device.createRfcommSocketToServiceRecord(myUUID)
/* Here is the part the connection is made, by asking the device to create a RfcommSocket (Unsecure socket I guess), It map a port for us or something like that */
btSocket.connect()
Log.d("", "Connection made.")
Toast.makeText(applicationContext, "Connection made.", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
try {
btSocket.close()
} catch (e2: IOException) {
Log.d("", "Unable to end the connection")
Toast.makeText(applicationContext, "Unable to end the connection", Toast.LENGTH_SHORT).show()
}
Log.d("", "Socket creation failed")
Toast.makeText(applicationContext, "Socket creation failed", Toast.LENGTH_SHORT).show()
}
//beginListenForData()
/* this is a method used to read what the Arduino says for example when you write Serial.print("Hello world.") in your Arduino code */
}
private fun writeData(data: String) {
var outStream = btSocket.outputStream
try {
outStream = btSocket.outputStream
} catch (e: IOException) {
//Log.d(FragmentActivity.TAG, "Bug BEFORE Sending stuff", e)
}
val msgBuffer = data.toByteArray()
try {
outStream.write(msgBuffer)
} catch (e: IOException) {
//Log.d(FragmentActivity.TAG, "Bug while sending stuff", e)
}
}
I am writing an Android app mostly in Kotlin that is supposed to scan for Bluetooth devices and also pair with them. I also want it to have a Bluetooth server socket running in the background to await connection attempts. However, I keep running into the same exception when attempting to invoke the BluetoothSocket.connect() method. The exception is:
10-10 20:07:57.917 18643-27894/com.example.zemcd.toofxchange E/Pairing Thread: error connecting
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:754)
at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:766)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:388)
at com.example.zemcd.toofxchange.PairingThread.run(BluetoothUtils.kt:83)
I read that this could be fixed with code similar to
btSocket = device.javaClass.getMethod("createRFcommSocket", Int::class).invoke(device, 1) as BluetoothSocket
But this does not work. It causes the app to crash with a ReflectException caused by NoSuchMethod. Also I have read that this is not a published method for a reason and I would like to try to use the published createRFcommSocketToServiceRecord() method. I am unsure of where to go from here, or what exactly is causing the IOException. Also, I never even get to the pairing screen. I am trying to find what is the cause of this exception, and how to fix it. My code:
class BluetoothUtils {
companion object {
val _UUID = UUID.fromString("a0e7e4c7-0e4e-43b7-9d18-659192512164")
val TAG = "BluetoothUtils"
fun initPairingServer(adapter: BluetoothAdapter){
var mmServerSocket: BluetoothServerSocket? = null
try {
var tmp = adapter.listenUsingRfcommWithServiceRecord(TAG, _UUID)
mmServerSocket = tmp
ListenThread(mmServerSocket).start()
}catch (ioe: IOException){
Log.e(TAG, "Error initializing Bluetooth", ioe)
}
}
fun pair(adapter: BluetoothAdapter, device: BluetoothDevice){
var btSocket: BluetoothSocket? = null
try {
adapter.cancelDiscovery()
btSocket = device.createRfcommSocketToServiceRecord(_UUID)
PairingThread(btSocket).start()
}catch (ioe: IOException){
Log.e(TAG, "error connecting", ioe)
}
}
}
}
class ListenThread(val btServSock: BluetoothServerSocket) : Thread(){
companion object {
val TAG = "ListenThread"
}
var btSocket: BluetoothSocket? = null
override fun run() {
super.run()
while (true){
try {
Log.d(TAG, "listening . . . ")
btSocket = btServSock.accept()
}catch (ioe: IOException){
Log.e(TAG, "Error", ioe)
break
}
//manage connection here
//with either BluetoothUtils function
//or BluetoothSocket extension
}
}
}
class PairingThread(val btSocket: BluetoothSocket) : Thread(){
companion object {
val TAG = "Pairing Thread"
}
override fun run() {
super.run()
try {
Log.d(TAG, "attempting to connect")
btSocket.connect()
}catch (ioe: IOException){
Log.e(TAG, "error connecting", ioe)
btSocket.close()
}
}
}
Please somebody help me find my problem. Could it be that I'm attempting to connect to a device that isn't using the same UUID? I am just trying to connect to my laptop.