Skip to content

Instantly share code, notes, and snippets.

@ali-cs
Last active September 10, 2019 13:22
Show Gist options
  • Save ali-cs/e923a03e22a9fec9584e05b483215027 to your computer and use it in GitHub Desktop.
Save ali-cs/e923a03e22a9fec9584e05b483215027 to your computer and use it in GitHub Desktop.
MqttAndroidConnection
String clientId;
CognitoCachingCredentialsProvider credentialsProvider;
AWSIotMqttManager mqttManager;
String clientSecret = "<Your JWT Token>";
public void init() {
clientId = UUID.randomUUID().toString();
Map<String, String> logins = new HashMap<String, String>();
logins.put("cognito-idp." + ApiClient.REGION + ".amazonaws.com/" + ApiClient.UserPool, clientSecret);
// Initialize the AWS Cognito credentials provider
credentialsProvider = new CognitoCachingCredentialsProvider(
context, // context
COGNITO_POOL_ID, // Identity Pool ID
MY_REGION // Region
);
credentialsProvider.setLogins(logins);
mqttManager = new AWSIotMqttManager(clientId, CUSTOMER_SPECIFIC_ENDPOINT);
}
public void connect() {
try {
mqttManager.connect(credentialsProvider, new AWSIotMqttClientStatusCallback() {
@Override
public void onStatusChanged(final AWSIotMqttClientStatus status,
final Throwable throwable) {
if (status == AWSIotMqttClientStatus.Connecting) {
Log.e(LOG_TAG, "Connecting...");
} else if (status == AWSIotMqttClientStatus.Connected) {
Log.e(LOG_TAG, "Connected");
subscribe("thing-update/<TOPIC>/#");
} else if (status == AWSIotMqttClientStatus.Reconnecting) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
}
} else if (status == AWSIotMqttClientStatus.ConnectionLost) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
}
Log.e(LOG_TAG, "Disconnected");
} else {
Log.e(LOG_TAG, "Disconnected");
}
}
});
} catch (final Exception e) {
Log.e(LOG_TAG, "Connection error.", e);
}
}
public String subscribe(String subTopic) {
Log.i(LOG_TAG, "Subscribing topic.." + subTopic);
try {
mqttManager.subscribeToTopic(subTopic, AWSIotMqttQos.QOS0,
new AWSIotMqttNewMessageCallback() {
@Override
public void onMessageArrived(final String topic, final byte[] data) {
String message = null;
try {
message = new String(data, "UTF-8");
//jsonMessage = new JSONObject(message);
Log.i("mqtt msg", message);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
Log.i(LOG_TAG, "Subscribed to topic " + subTopic);
return "Success";
} catch (Exception e) {
Log.e(LOG_TAG, "Subscription error.", e);
return "Failed";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment