【发布时间】:2019-05-09 11:01:20
【问题描述】:
我正在尝试通过我的 Android 应用程序订阅一个主题。即使它连接成功订阅失败。一旦我执行订阅呼叫,IOT 连接就会失败并给出如下所述的错误日志。想知道我在哪里做错了编码? IOT政策的所有资源都是出于测试目的,以寻找线索。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:*",
"Resource": "*"
}
]
}
我为我的开发推荐了 AWS-amplify。 https://aws-amplify.github.io/docs/android/pubsub
1.连接物联网
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()
}
-
订阅方式
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") } }
结果日志:
W/AWSIotMqttManager:连接丢失
订阅错误:com.amazonaws.AmazonClientException:客户端错误 订阅时。
【问题讨论】:
标签: android amazon-web-services iot