I'm trying to subscribe to a topic via my Android application. Even though it connects successfully subscription fails. As soon as I perform subscription call, IOT connectivity fails and gives an error log as stated below. Want to Know where have I done any wrong coding ? All the resources of IOT policy is given due to testing purposes to find a clue.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:*",
"Resource": "*"
}
]
}
I referred AWS-amplify for my development. https://aws-amplify.github.io/docs/android/pubsub
1 .Connecting to IOT
private var mAWSMobileClient : AWSMobileClient = AWSMobileClient.getInstance()
private lateinit var mIotDataManager: AWSIotMqttManager
private lateinit var mAttachedPolicyReq: AttachPolicyRequest
private lateinit var mAwsIOTClient: AWSIotClient
private lateinit var mAwsCredentials: AWSCredentials
private fun connectToIOT() {
Thread(Runnable {
var mDeviceIdentity = Settings.Secure.getString(this.contentResolver, Settings.Secure.ANDROID_ID)
mIotDataManager = AWSIotMqttManager(mDeviceIdentity, <iot endpoint>)
mIotDataManager.keepAlive = 50
mIotDataManager.isAutoReconnect = false
mIotDataManager.connectionStabilityTime = 100
mAwsCredentials = mAWSMobileClient.awsCredentials
mAwsIOTClient = AWSIotClient(mAWSMobileClient)
mAwsIOTClient.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_2))
mAttachedPolicyReq = AttachPolicyRequest()
mAttachedPolicyReq.policyName = "test_policy"
mAttachedPolicyReq.target = mAWSMobileClient.identityId
mAwsIOTClient.attachPolicy(mAttachedPolicyReq)
try {
mIotDataManager.connect(mAWSMobileClient, object : AWSIotMqttClientStatusCallback {
override fun onStatusChanged(
status: AWSIotMqttClientStatusCallback.AWSIotMqttClientStatus?,
throwable: Throwable?
) {
when (status) {
AWSIotMqttClientStatusCallback.AWSIotMqttClientStatus.ConnectionLost -> {}
AWSIotMqttClientStatusCallback.AWSIotMqttClientStatus.Connected -> {}
AWSIotMqttClientStatusCallback.AWSIotMqttClientStatus.Connecting -> {}
AWSIotMqttClientStatusCallback.AWSIotMqttClientStatus.Reconnecting -> {}
else -> {
}
}
}
})
} catch (e: Exception) {
Log.d("IOT Data Manager Connection Errror : $e")
}
}).start()
}
Subscription Method
fun subscribeToThing() { if(mConnected) { Thread(Runnable { mThingsName = "$mThingsName/shadow/get/accepted" var message: String? = null try { mIotDataManager.subscribeToTopic( mThingsName, AWSIotMqttQos.QOS1, object : AWSIotMqttNewMessageCallback { override fun onMessageArrived(topic: String?, data: ByteArray?) { try { message = String(data!!, Charsets.UTF_8) } catch (e: UnsupportedEncodingException) { Log.d("Unsupported Encoding error :$e") } } }) } catch (e: Exception) { Log.d("Subscription error :$e") } }).start() } else { Log.d("IOT Not Connected") } }
Result Log :
W/AWSIotMqttManager: connection is Lost
Subscription error :com.amazonaws.AmazonClientException: Client error when subscribing.