Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Aws Iot issues with restricted policy permissions #640

Closed
phantom-j opened this issue Jan 9, 2019 · 18 comments
Closed

Aws Iot issues with restricted policy permissions #640

phantom-j opened this issue Jan 9, 2019 · 18 comments
Assignees
Labels
closing soon Issue will auto-close if there is no additional activity within 7 days. iot Issues with the AWS Android SDK for Internet of Things (IoT) pending-response Issue is pending response from the issue requestor question General question

Comments

@phantom-j
Copy link

phantom-j commented Jan 9, 2019

State your question
When i am trying to connect my end point its' not connecting,It's showing connection lost
Which AWS Services are you utilizing?
AWS cognito userpool,federated identity pool,Iot
Provide code snippets (if applicable)
This is my code

           protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_iot);
    Log.i("Iotstatus", "Iotactiviuty started");
    String clientId = UUID.randomUUID().toString();
   AWSIotMqttManager mqttManager = new AWSIotMqttManager(
            clientId,
            "************-ats.iot.eu-west-1.amazonaws.com/mqtt");
    try {
        mqttManager.connect(AWSMobileClient.getInstance(), new AWSIotMqttClientStatusCallback() {
            @Override
            public void onStatusChanged(final AWSIotMqttClientStatus status, final Throwable throwable) {
                Log.d("Iotstatus", "Connection Status: " + String.valueOf(status));
            }
        });
    } catch (final Exception e) {
        Log.e("Iotstatus", "Connection error: ", e);
    }
    try {
        String sub_id = AWSMobileClient.getInstance().getTokens().getIdToken().getClaim("sub");
        Log.i("usersub", "usersub is" + sub_id);
        try {
            mqttManager.subscribeToTopic(sub_id, AWSIotMqttQos.QOS0 /* Quality of Service */,
                    new AWSIotMqttNewMessageCallback() {
                        @Override
                        public void onMessageArrived(final String topic, final byte[] data) {
                            try {
                                String message = new String(data, "UTF-8");
                                Log.d("Iotstatus", "Message received: " + message);
                            } catch (UnsupportedEncodingException e) {
                                Log.e("Iotstatus", "Message encoding error: ", e);
                            }
                        }
                    });
        } catch (Exception e) {
            Log.e("Iotstatus", "Subscription error: ", e);
        }

    }
    catch (Exception e) {
        e.printStackTrace();
    }

}

This is the output i got

2019-01-09 17:54:25.141 29809-29809/com.example.aura.app15 I/Iotstatus: Iotactiviuty started
2019-01-09 17:54:25.142 2936-8444/? D/ConnectivityService: ConnectivityService NetworkRequestInfo binderDied(NetworkRequest [ LISTEN id=5293, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&FOREGROUND] ], android.os.BinderProxy@797f9a3)
2019-01-09 17:54:25.142 2936-4503/? D/ConnectivityService: ConnectivityService NetworkRequestInfo binderDied(NetworkRequest [ LISTEN id=5294, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&FOREGROUND] ], android.os.BinderProxy@e60c4d2)
2019-01-09 17:54:25.142 2936-8444/? D/ConnectivityService: ConnectivityService NetworkRequestInfo binderDied(NetworkRequest [ LISTEN id=5293, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&FOREGROUND] ], android.os.BinderProxy@797f9a3)
2019-01-09 17:54:25.143 2936-3370/? E/ConnectivityService: RemoteException caught trying to send a callback msg for NetworkRequest [ LISTEN id=5293, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&FOREGROUND] ]
2019-01-09 17:54:25.144 2936-3370/? E/ConnectivityService: RemoteException caught trying to send a callback msg for NetworkRequest [ LISTEN id=5294, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&FOREGROUND] ]
2019-01-09 17:54:25.154 29809-29809/com.example.aura.app15 D/AWSMobileClient: Inspecting user state details
2019-01-09 17:54:25.160 29809-29809/com.example.aura.app15 D/AWSMobileClient: hasFederatedToken: true provider: cognito-idp.eu-west-1.amazonaws.com/eu-west-1_*******
2019-01-09 17:54:25.160 29809-29809/com.example.aura.app15 D/AWSMobileClient: waitForSignIn: userState:SIGNED_IN
2019-01-09 17:54:25.160 29809-29922/com.example.aura.app15 D/AWSMobileClient: Inspecting user state details
2019-01-09 17:54:25.166 29809-29809/com.example.aura.app15 I/usersub: usersub ise30e7c1a-28cf-421e-b29c-3e77bf26ebc2
2019-01-09 17:54:25.167 29809-29922/com.example.aura.app15 D/AWSMobileClient: hasFederatedToken: true provider: cognito-idp.eu-west-1.amazonaws.com/eu-west-1_******
2019-01-09 17:54:25.167 29809-29922/com.example.aura.app15 D/AWSMobileClient: waitForSignIn: userState:SIGNED_IN
2019-01-09 17:54:25.167 29809-29922/com.example.aura.app15 D/AWSMobileClient: getCredentials: Validated user is signed-in
2019-01-09 17:54:25.254 2936-3053/? I/LaunchCheckinHandler: Displayed com.example.aura.app15/.Iot,wp,ca,185
2019-01-09 17:54:25.255 2936-3053/? I/ActivityManager: Displayed com.example.aura.app15/.Iot: +181ms
2019-01-09 17:54:25.282 29809-29860/com.example.aura.app15 D/OpenGLRenderer: endAllActiveAnimators on 0x8f49ea80 (RippleDrawable) with handle 0x9bcfd890
2019-01-09 17:54:25.477 29809-29922/com.example.aura.app15 I/AWSIotMqttManager: metrics collection is enabled, username: ?SDK=Android&Version=2.9.1
2019-01-09 17:54:25.477 29809-29922/com.example.aura.app15 I/AWSIotMqttManager: resetting reconnect attempt and retry time
2019-01-09 17:54:25.478 29809-29922/com.example.aura.app15 D/Iotstatus: Connection Status: Connecting
2019-01-09 17:54:25.491 29809-29922/com.example.aura.app15 D/Iotstatus: Connection Status: ConnectionLost
2019-01-09 17:54:25.549 2936-4503/? I/ActivityManager: Killing 26831:com.motorola.motodisplay/u0a67 (adj 906): empty #17

Environment(please complete the following information):

  • SDK Version: 2.9.1

Device Information (please complete the following information):

  • Device: Moto g6
  • Android Version: oreo

II have signed in using my user pool and gave full iot access to federated auth role
I just want to publish and subscribe to topic.
Any example code snippets are helpful.

@desokroshan
Copy link
Contributor

@warlock-jay Sorry to hear that you are having issues. Can you please update to the latest version and try again. We have made some changes to log detailed exceptions upon connection failures. With current logs that you have shared its difficult to root cause the issue.
Also since you are connecting to iot using AWS Cognito Identity, you would need to attach principal policy to the Cognito Identity before attempting a connect:

import com.amazonaws.services.iot.AWSIotClient;
import com.amazonaws.mobile.client.AWSMobileClient;
import com.amazonaws.services.iot.model.AttachPolicyRequest;

// Attach principal policy
AttachPolicyRequest attachPolicyReq = new AttachPolicyRequest();
attachPolicyReq.setPolicyName("myIOTPolicy"); // name of your IOT AWS policy
attachPolicyReq.setTarget(AWSMobileClient.getInstance().getIdentityId());
AWSIotClient mIotAndroidClient = new AWSIotClient(AWSMobileClient.getInstance());
mIotAndroidClient.setRegion(Region.getRegion("<YOUR-AWS-REGION>")); // name of your IoT Region such as "us-east-1"
mIotAndroidClient.attachPolicy(attachPolicyReq);

// Connect code
...

@desokroshan desokroshan self-assigned this Jan 9, 2019
@desokroshan desokroshan added iot Issues with the AWS Android SDK for Internet of Things (IoT) question General question pending-response Issue is pending response from the issue requestor closing soon Issue will auto-close if there is no additional activity within 7 days. labels Jan 9, 2019
@phantom-j
Copy link
Author

phantom-j commented Jan 14, 2019

Hi @desokroshan
I tried to attach policy,it's failing(app is crashing) at

  mIotAndroidClient.attachPolicy(attachPolicyReq);

This is my code
public class Iot extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_iot);
    Log.i("Iotstatus", "Iotactiviuty started");
    AttachPolicyRequest attachPolicyReq = new AttachPolicyRequest();
    attachPolicyReq.setPolicyName("myIOTPolicy"); // name of your IOT AWS policy
    attachPolicyReq.setTarget(AWSMobileClient.getInstance().getIdentityId());
    AWSIotClient mIotAndroidClient = new AWSIotClient(AWSMobileClient.getInstance());
    mIotAndroidClient.setRegion(Region.getRegion("eu-west-1")); // name of your IoT Region such as "us-east-1"
    mIotAndroidClient.attachPolicy(attachPolicyReq);
    String clientId = UUID.randomUUID().toString();
   AWSIotMqttManager mqttManager = new AWSIotMqttManager(
            clientId,
            "***********-ats.iot.eu-west-1.amazonaws.com/mqtt");
    try {
        mqttManager.connect(AWSMobileClient.getInstance(), new AWSIotMqttClientStatusCallback() {
            @Override
            public void onStatusChanged(final AWSIotMqttClientStatus status, final Throwable throwable) {
                Log.d("Iotstatus", "Connection Status: " + String.valueOf(status));
            }
        });
    } catch (final Exception e) {
        Log.e("Iotstatus", "Connection error: ", e);
    }
    try {
        String sub_id = AWSMobileClient.getInstance().getTokens().getIdToken().getClaim("sub");
        Log.i("usersub", "usersub is" + sub_id);
        try {
            mqttManager.subscribeToTopic(sub_id, AWSIotMqttQos.QOS0 /* Quality of Service */,
                    new AWSIotMqttNewMessageCallback() {
                        @Override
                        public void onMessageArrived(final String topic, final byte[] data) {
                            try {
                                String message = new String(data, "UTF-8");
                                Log.d("Iotstatus", "Message received: " + message);
                            } catch (UnsupportedEncodingException e) {
                                Log.e("Iotstatus", "Message encoding error: ", e);
                            }
                        }
                    });
        } catch (Exception e) {
            Log.e("Iotstatus", "Subscription error: ", e);
        }

    }
    catch (Exception e) {
        e.printStackTrace();
    }

   }
 }

This is the error i got

2019-01-14 10:55:34.854 22852-22852/com.example.aura.app15 I/Iotstatus: Iotactiviuty started
2019-01-14 10:55:34.969 22852-22852/com.example.aura.app15 D/AWSMobileClient: Inspecting
user state details
2019-01-14 10:55:34.974 22852-22852/com.example.aura.app15 D/AWSMobileClient: hasFederatedToken: true provider: cognito-idp.eu-west-1.amazonaws.com/eu-west-1_**********
2019-01-14 10:55:34.975 22852-22852/com.example.aura.app15 D/AWSMobileClient: waitForSignIn: userState:SIGNED_IN
2019-01-14 10:55:34.975 22852-22852/com.example.aura.app15 D/AWSMobileClient: getCredentials: Validated user is signed-in
2019-01-14 10:55:35.005 22852-22852/com.example.aura.app15 D/AndroidRuntime: Shutting down VM
2019-01-14 10:55:35.010 22852-22852/com.example.aura.app15 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aura.app15, PID: 22852
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aura.app15/com.example.aura.app15.Iot}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2979)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1634)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6673)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1457)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(Unknown Source:0)
at com.amazonaws.http.UrlHttpClient.writeContentToConnection(UrlHttpClient.java:162)
at com.amazonaws.http.UrlHttpClient.execute(UrlHttpClient.java:75)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:371)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212)
at com.amazonaws.services.iot.AWSIotClient.invoke(AWSIotClient.java:9160)
at com.amazonaws.services.iot.AWSIotClient.attachPolicy(AWSIotClient.java:588)
at com.example.aura.app15.Iot.onCreate(Iot.java:31)
at android.app.Activity.performCreate(Activity.java:6984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1235)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2853)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2979) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1634) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6673) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) 
2019-01-14 10:55:35.016 2906-3531/? W/ActivityManager: Force finishing activity com.example.aura.app15/.Iot
2019-01-14 10:55:35.019 2906-3531/? W/ActivityManager: Force finishing activity com.example.aura.app15/.DeviceActivity

Why it is failing?

@stale stale bot removed the closing soon Issue will auto-close if there is no additional activity within 7 days. label Jan 14, 2019
@desokroshan
Copy link
Contributor

@warlock-jay The call to attachPolicy make a network call which cannot be performed on main thread to avoid unresponsive apps. Please move the code to a separate worker thread :

new Thread(new Runnable() {
    @Override
    public void run() {
        // Attach principal policy
        AttachPolicyRequest attachPolicyReq = new AttachPolicyRequest();
        attachPolicyReq.setPolicyName("myIOTPolicy"); // name of your IOT AWS policy
        attachPolicyReq.setTarget(AWSMobileClient.getInstance().getIdentityId());
        AWSIotClient mIotAndroidClient = new AWSIotClient(AWSMobileClient.getInstance());
        mIotAndroidClient.setRegion(Region.getRegion("<YOUR-AWS-REGION>")); // name of your IoT Region such as "us-east-1"
        mIotAndroidClient.attachPolicy(attachPolicyReq);
    }
}, "Attach Policy").start();

@phantom-j
Copy link
Author

Hi @desokroshan
thanks,I did that using seperate thread but it's giving error

2019-01-14 12:52:00.049 2906-3360/? E/ConnectivityService: RemoteException caught trying to send a callback msg for NetworkRequest [ LISTEN id=1056, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&FOREGROUND] ]
2019-01-14 12:52:00.623 22138-22227/com.example.aura.app15 E/AndroidRuntime: FATAL EXCEPTION: Attach Policy
Process: com.example.aura.app15, PID: 22138
com.amazonaws.services.iot.model.ResourceNotFoundException: Policy not found (Service: AWSIot; Status Code: 404; Error Code: ResourceNotFoundException; Request ID: 15d18d44-17cd-11e9-9491-3f297b718855)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:730)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:405)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212)
at com.amazonaws.services.iot.AWSIotClient.invoke(AWSIotClient.java:9160)
at com.amazonaws.services.iot.AWSIotClient.attachPolicy(AWSIotClient.java:588)
at com.example.aura.app15.Iot$1.run(Iot.java:36)
at java.lang.Thread.run(Thread.java:764)

I created policy with that name and gave full IOT access also,still it's giving same error.

@phantom-j
Copy link
Author

Hi @desokroshan
I have changed my code like this

public class Iot extends AppCompatActivity {

public String clientId = UUID.randomUUID().toString();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_iot);
    Log.i("Iotstatus", "Iotactiviuty started");
    new Thread(new Runnable() {
        @Override
        public void run() {
            // Attach principal policy
            AttachPolicyRequest attachPolicyReq = new AttachPolicyRequest();
            attachPolicyReq.setPolicyName("myIOTPolicy"); // name of your IOT AWS policy
            attachPolicyReq.setTarget(AWSMobileClient.getInstance().getIdentityId());
            AWSIotClient mIotAndroidClient = new AWSIotClient(AWSMobileClient.getInstance());
            mIotAndroidClient.setRegion(Region.getRegion("eu-west-1")); // name of your IoT Region such as "us-east-1"
            mIotAndroidClient.attachPolicy(attachPolicyReq);
        }
    }, "Attach Policy").start();

}
public void connectiot( View view) {
    //String clientId = UUID.randomUUID().toString();
    AWSIotMqttManager mqttManager = new AWSIotMqttManager(
            clientId,
            "a*********-ats.iot.eu-west-1.amazonaws.com");
    try {
        mqttManager.connect(AWSMobileClient.getInstance(), new AWSIotMqttClientStatusCallback() {
            @Override
            public void onStatusChanged(final AWSIotMqttClientStatus status, final Throwable throwable) {
                Log.d("Iotstatus", "Connection Status: " + String.valueOf(status));
            }
        });
    } catch (final Exception e) {
        Log.e("Iotstatus", "Connection error: ", e);
    }

}
public void disconnectiot( View view) {
    //String clientId = UUID.randomUUID().toString();
    AWSIotMqttManager mqttManager = new AWSIotMqttManager(
            clientId,
            "a*******-ats.iot.eu-west-1.amazonaws.com");
    try {
        mqttManager.disconnect();
    } catch (Exception e) {
        Log.e("Iotstatus", "Disconnect error: ", e);
    }
}
public void subscribeiot( View view) {
    //String clientId = UUID.randomUUID().toString();
    AWSIotMqttManager mqttManager = new AWSIotMqttManager(
            clientId,
            "a********-ats.iot.eu-west-1.amazonaws.com");
    try {
        String sub_id = AWSMobileClient.getInstance().getTokens().getIdToken().getClaim("sub");
        Log.i("usersub", "usersub is" + sub_id);
        try {
            mqttManager.subscribeToTopic(sub_id, AWSIotMqttQos.QOS0 /* Quality of Service */,
                    new AWSIotMqttNewMessageCallback() {
                        @Override
                        public void onMessageArrived(final String topic, final byte[] data) {
                            try {
                                String message = new String(data, "UTF-8");
                                Log.d("Iotstatussubscribe", "Message received: " + message);
                            } catch (UnsupportedEncodingException e) {
                                Log.e("Iotstatusscribe", "Message encoding error: ", e);
                            }
                        }
                    });
        } catch (Exception e) {
            Log.e("Iotstatus", "Subscription error: ", e);
        }

    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
public void unsubscribeiot( View view) {
    AWSIotMqttManager mqttManager = new AWSIotMqttManager(
            clientId,
            "a********-ats.iot.eu-west-1.amazonaws.com");
    try {
        String sub_id = AWSMobileClient.getInstance().getTokens().getIdToken().getClaim("sub");
        Log.i("usersub", "usersub is" + sub_id);
        try {
            mqttManager.unsubscribeTopic(sub_id);
        } catch (Exception e) {
            Log.e("Iotstatus", "Unsubscription error: ", e);
        }}
        catch (Exception e) {
            Log.e("Iotstatus", "Publish error: ", e);
        }
}
public void publishiot( View view) {
    AWSIotMqttManager mqttManager = new AWSIotMqttManager(
            clientId,
            "a*******-ats.iot.eu-west-1.amazonaws.com");
    try {
        String sub_id = AWSMobileClient.getInstance().getTokens().getIdToken().getClaim("sub");
        Log.i("usersub", "usersub is" + sub_id);
        try {
            mqttManager.publishString("Hello to all subscribers!", sub_id, AWSIotMqttQos.QOS0);
        } catch (Exception e) {
            Log.e("Iotstatus", "Publish error: ", e);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

}

}

This is the output i got when i run connectiot()

2019-01-14 15:37:44.321 893-981/com.example.aura.app15 D/AWSMobileClient: Inspecting user state details
2019-01-14 15:37:44.327 893-981/com.example.aura.app15 D/AWSMobileClient: hasFederatedToken: true provider: cognito-idp.eu-west-1.amazonaws.com/eu-west-1_*******
2019-01-14 15:37:44.327 893-981/com.example.aura.app15 D/AWSMobileClient: waitForSignIn: userState:SIGNED_IN
2019-01-14 15:37:44.327 893-981/com.example.aura.app15 D/AWSMobileClient: getCredentials: Validated user is signed-in
2019-01-14 15:37:44.448 2906-2915/? I/zygote: Background concurrent copying GC freed 82537(4MB) AllocSpace objects, 81(5MB) LOS objects, 41% free, 33MB/57MB, paused 2.272ms total 333.528ms
2019-01-14 15:37:44.473 893-898/com.example.aura.app15 I/zygote: Do partial code cache collection, code=121KB, data=74KB
2019-01-14 15:37:44.474 893-898/com.example.aura.app15 I/zygote: After code cache collection, code=121KB, data=74KB
2019-01-14 15:37:44.474 893-898/com.example.aura.app15 I/zygote: Increasing code cache capacity to 512KB
2019-01-14 15:37:44.645 893-981/com.example.aura.app15 I/AWSIotMqttManager: metrics collection is enabled, username: ?SDK=Android&Version=2.9.2
2019-01-14 15:37:44.646 893-981/com.example.aura.app15 I/AWSIotMqttManager: resetting reconnect attempt and retry time
2019-01-14 15:37:44.646 893-981/com.example.aura.app15 D/Iotstatus: Connection Status: Connecting
2019-01-14 15:37:46.076 577-910/? I/SFPerfTracer: triggers: (rate: 2:95) (222094 sw vsyncs) (0 skipped) (49:3618982 vsyncs) (51:3989732)
2019-01-14 15:37:47.027 893-990/com.example.aura.app15 W/AWSIotMqttManager: onFailure: connection failed.
MqttException (0) - java.io.IOException: Already connected
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.io.IOException: Already connected
at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
at java.io.PipedInputStream.connect(PipedInputStream.java:191)
at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketReceiver.(WebSocketReceiver.java:42)
at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule.start(WebSocketSecureNetworkModule.java:78)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
at java.lang.Thread.run(Thread.java:764) 
2019-01-14 15:37:47.027 893-990/com.example.aura.app15 D/Iotstatus: Connection Status: Reconnecting
2019-01-14 15:37:47.028 893-990/com.example.aura.app15 I/AWSIotMqttManager: schedule Reconnect attempt 0 of 10 in 4 seconds.
2019-01-14 15:37:51.035 893-994/com.example.aura.app15 I/AWSIotMqttManager: attempting to reconnect to mqtt broker
2019-01-14 15:37:51.038 893-994/com.example.aura.app15 D/AWSMobileClient: Inspecting user state details
2019-01-14 15:37:51.055 893-994/com.example.aura.app15 D/AWSMobileClient: hasFederatedToken: true provider: cognito-idp.eu-west-1.amazonaws.com/eu-west-1_********
2019-01-14 15:37:51.056 893-994/com.example.aura.app15 D/AWSMobileClient: waitForSignIn: userState:SIGNED_IN
2019-01-14 15:37:51.057 893-994/com.example.aura.app15 D/AWSMobileClient: getCredentials: Validated user is signed-in
2019-01-14 15:37:53.039 25595-25748/? D/ClClient: Not sending keepalive. Current connection state=STOPPED
2019-01-14 15:37:53.239 893-1009/com.example.aura.app15 W/AWSIotMqttManager: Reconnect failed
MqttException (0) - java.io.IOException: Already connected
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.io.IOException: Already connected
at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
at java.io.PipedInputStream.connect(PipedInputStream.java:191)
at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketReceiver.(WebSocketReceiver.java:42)
at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule.start(WebSocketSecureNetworkModule.java:78)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
at java.lang.Thread.run(Thread.java:764) 
2019-01-14 15:37:53.241 893-1009/com.example.aura.app15 I/AWSIotMqttManager: schedule Reconnect attempt 1 of 10 in 8 seconds.
2019-01-14 15:37:53.244 893-1009/com.example.aura.app15 D/Iotstatus: Connection Status: Reconnecting
2019-01-14 15:38:00.049 25595-1016/? D/EventNotificationJob: Running EventNotificationJob, isDetail=true
2019-01-14 15:38:00.057 25595-1016/? D/EventNotificationJob: finished processing events.

It's giving message trying to reconnect and failing showing exception that it is already connected.When i try to subscribe,it's giving the same
When i run publishiot() ,i got this error

2019-01-14 15:53:56.345 893-893/com.example.aura.app15 D/AWSMobileClient: Inspecting user state details
2019-01-14 15:53:56.350 893-893/com.example.aura.app15 D/AWSMobileClient: hasFederatedToken: true provider: cognito-idp.eu-west-1.amazonaws.com/eu-west-1_********
2019-01-14 15:53:56.351 893-893/com.example.aura.app15 D/AWSMobileClient: waitForSignIn: userState:SIGNED_IN
2019-01-14 15:53:56.354 893-893/com.example.aura.app15 I/usersub: usersub ise30e7c1a-28cf-421e-b29c-3e77bf26ebc2
2019-01-14 15:53:56.357 893-893/com.example.aura.app15 E/Iotstatus: Publish error:
com.amazonaws.AmazonClientException: Client is disconnected or not yet connected.
at com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.publishData(AWSIotMqttManager.java:1242)
at com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.publishData(AWSIotMqttManager.java:1191)
at com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.publishString(AWSIotMqttManager.java:1151)
at com.example.aura.app15.Iot.publishiot(Iot.java:124)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6259)
at android.view.View$PerformClick.run(View.java:24732)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6673)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)

So i understood it didn't connected properly or not connected,
is endpoint format correct ?
do i have to put any certificates?

@desokroshan
Copy link
Contributor

An Amazon Cognito authenticated user needs two policies to access AWS IoT. The first policy is attached to the role of the authenticated pool to authenticate and authorize the Cognito user to communicate with AWS IoT. The second policy is attached to the authenticated Cognito user ID principal for fine-grained permissions. The above snippet attaches policy to the user id. Can you confirm if you have attached required policy to the "authenticated" role of your user pool?

@phantom-j
Copy link
Author

Yes,I gave full Iot access to authenticated and unauthenticated roles.

@desokroshan
Copy link
Contributor

Some comments based your code above :

  1. Where did you create the IoT policy with the name "myIOTPolicy" that you attach to the cognito identity above. Can you please share a snapshot of this policy?
  2. You should not to instantiating AWSIotMqttManager for each of connect, publish, subscribe operations. This should be instantiated once and same instance should be used for all the operations.
  3. You don't need to attach iot access to the unauthenticated roles since users are signed in before attempting connect.
  4. Can you please confirm from the iot console that Cognito identity for the user you are trying with has policy attached to it?

@phantom-j
Copy link
Author

phantom-j commented Jan 16, 2019

Hi @desokroshan
1)
iotpolicy
This is policy document

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iot:*", "Resource": "arn:aws:iot:eu-west-1:4************3:topic/*" } ] }

I have changed and tested my code as you suggested.This is current code

  public class Iot extends AppCompatActivity {

public String clientId = UUID.randomUUID().toString();
AWSIotMqttManager mqttManager;
String endpoint = "a***********p-ats.iot.eu-west-1.amazonaws.com";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_iot);
    Log.i("Iotstatus", "Iotactiviuty started");
    mqttManager = new AWSIotMqttManager(clientId, endpoint);
    new Thread(new Runnable() {
        @Override
        public void run() {
            // Attach principal policy
            AttachPolicyRequest attachPolicyReq = new AttachPolicyRequest();
            attachPolicyReq.setPolicyName("myIOTPolicy"); // name of your IOT AWS policy
            attachPolicyReq.setTarget(AWSMobileClient.getInstance().getIdentityId());
            AWSIotClient mIotAndroidClient = new AWSIotClient(AWSMobileClient.getInstance());
            mIotAndroidClient.setRegion(Region.getRegion("eu-west-1")); // name of your IoT Region such as "us-east-1"
            mIotAndroidClient.attachPolicy(attachPolicyReq);
        }
    }, "Attach Policy").start();
    try {
        mqttManager.connect(AWSMobileClient.getInstance(), new AWSIotMqttClientStatusCallback() {
            @Override
            public void onStatusChanged(final AWSIotMqttClientStatus status, final Throwable throwable) {
                Log.d("Iotstatus", "Connection Status: " + String.valueOf(status));
            }
        });
    } catch (final Exception e) {
        Log.e("Iotstatus", "Connection error: ", e);
    }

}
public void connectiot( View view) {
    try {
        mqttManager.connect(AWSMobileClient.getInstance(), new AWSIotMqttClientStatusCallback() {
            @Override
            public void onStatusChanged(final AWSIotMqttClientStatus status, final Throwable throwable) {
                Log.d("Iotstatus", "Connection Status: " + String.valueOf(status));
            }
        });
    } catch (final Exception e) {
        Log.e("Iotstatus", "Connection error: ", e);
    }

}
public void disconnectiot( View view) {
    try {
        mqttManager.disconnect();
    } catch (Exception e) {
        Log.e("Iotstatus", "Disconnect error: ", e);
    }
}
public void subscribeiot( View view) {
    try {
        String sub_id = AWSMobileClient.getInstance().getTokens().getIdToken().getClaim("sub");
        Log.i("usersub", "usersub is" + sub_id);
        try {
            mqttManager.subscribeToTopic(sub_id, AWSIotMqttQos.QOS0 /* Quality of Service */,
                    new AWSIotMqttNewMessageCallback() {
                        @Override
                        public void onMessageArrived(final String topic, final byte[] data) {
                            try {
                                String message = new String(data, "UTF-8");
                                Log.d("Iotstatussubscribe", "Message received: " + message);
                            } catch (UnsupportedEncodingException e) {
                                Log.e("Iotstatusscribe", "Message encoding error: ", e);
                            }
                        }
                    });
        } catch (Exception e) {
            Log.e("Iotstatus", "Subscription error: ", e);
        }

    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
public void unsubscribeiot( View view) {
    try {
        String sub_id = AWSMobileClient.getInstance().getTokens().getIdToken().getClaim("sub");
        Log.i("usersub", "usersub is" + sub_id);
        try {
            mqttManager.unsubscribeTopic(sub_id);
        } catch (Exception e) {
            Log.e("Iotstatus", "Unsubscription error: ", e);
        }}
        catch (Exception e) {
            Log.e("Iotstatus", "Publish error: ", e);
        }
}
public void publishiot( View view) {
    try {
        String sub_id = AWSMobileClient.getInstance().getTokens().getIdToken().getClaim("sub");
        Log.i("usersub", "usersub is" + sub_id);
        try {
            mqttManager.publishString("Hello to all subscribers!", sub_id, AWSIotMqttQos.QOS0);
        } catch (Exception e) {
            Log.e("Iotstatus", "Publish error: ", e);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

}
}

This is the output i got for connectiot()

2019-01-16 17:04:39.069 31277-31371/com.example.aura.app15 W/AWSIotMqttManager: onFailure: connection failed.
MqttException (0) - java.io.IOException: Already connected
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.io.IOException: Already connected
at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
at java.io.PipedInputStream.connect(PipedInputStream.java:191)
at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketReceiver.(WebSocketReceiver.java:42)
at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule.start(WebSocketSecureNetworkModule.java:78)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
at java.lang.Thread.run(Thread.java:764) 
2019-01-16 17:04:39.069 31277-31371/com.example.aura.app15 D/Iotstatus: Connection Status: Reconnecting

This is the output i got for subscribeiot()

2019-01-16 17:05:23.626 31277-31277/com.example.aura.app15 E/Iotstatus: Subscription error:
com.amazonaws.AmazonClientException: Client error when subscribing.
at com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.subscribeToTopic(AWSIotMqttManager.java:1086)
at com.example.aura.app15.Iot.subscribeiot(Iot.java:86)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6259)
at android.view.View$PerformClick.run(View.java:24732)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6673)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
Caused by: Client is not connected (32104)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:31)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.sendNoWait(ClientComms.java:166)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.subscribe(MqttAsyncClient.java:835)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.subscribe(MqttAsyncClient.java:790)
at com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.subscribeToTopic(AWSIotMqttManager.java:1084)
at com.example.aura.app15.Iot.subscribeiot(Iot.java:86) 
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:6259) 
at android.view.View$PerformClick.run(View.java:24732) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6673) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) 

  1. I gave permissions for checking purpose ,once connection established and it's working properly then i remove full access and i will give limited and required access.

4)I don't understand the question properly,I think this is what you asked
policycert
Let me know if this isn't

@desokroshan
Copy link
Contributor

desokroshan commented Jan 16, 2019

Thanks for sharing the details.
Could you please use the following policy document as myIOTPolicy for testing purpose and share the results:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:*"
            ],
            "Resource": "*"
        }
    ]
}

In general giving full access is discouraged for production apps but you can try above just for debugging purpose.
Also can you share snapshot of policies attached to the authenticated and unauthenticated roles from the IAM console?

@phantom-j
Copy link
Author

Hi @desokroshan
I have changed Resource to "*" in myIOTpolicy and it started working.
When i run connectiot() it is showing status connected.
subscription and publishing also working.

But
When i subscribed to topic and published a message in topic it is receiving in my phone but shadow document is not updating.
Why it is happening?
How to update shadow?

@phantom-j
Copy link
Author

Thanks @desokroshan

It's working when i change subscribe and publish topic names

for publish i used "$aws/things//shadow/update"
for subscribe i used "$aws/things/
*/shadow/update/accepted"

Still i have confusion on getting full data ,getting only delta,publishing.working on it.
And i have to restrict permissions in policy documents,Can you tell me best method?

@desokroshan
Copy link
Contributor

@warlock-jay Thanks for the update. I will try to reproduce and investigate the issue with restricted policy permissions soon as I can and update the thread.

@frankmuellr frankmuellr added investigating and removed pending-response Issue is pending response from the issue requestor labels Jan 18, 2019
@desokroshan desokroshan changed the title Aws Iot not connecting Aws Iot issues with restricted policy permissions Jan 28, 2019
@suandplzop
Copy link

suandplzop commented Mar 14, 2019

Similar issues here.
Unable to attach policy after user logged in and the implementation is followed by Amplify website.
But iOS works fine using same user pool, user identity pool

error message:

com.amazonaws.AmazonServiceException: User: arn:aws:sts::884418826570:assumed-role/cognito-auth-goodlinkeriot@sensor.live/CognitoIdentityCredentials is not authorized to perform: iot:AttachPolicy on resource: ap-southeast-1:81084a40-f161-4960-90f9-835f3d8de579 (Service: AWSIot; Status Code: 403; Error Code: AccessDeniedException; Request ID: 1d48eb35-4640-11e9-998b-050d8e5cb97a) at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:730) at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:405) at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212) at com.amazonaws.services.iot.AWSIotClient.invoke(AWSIotClient.java:9160) at com.amazonaws.services.iot.AWSIotClient.attachPolicy(AWSIotClient.java:588)

Attach policy code is run right after user logged in:

GlobalScope.launch(Dispatchers.IO) {
    val attachPolicyRequest = AttachPolicyRequest()
    attachPolicyRequest.policyName = "sensor.live-policy"
    attachPolicyRequest.target = AWSMobileClient.getInstance().identityId
    Timber.d(AWSMobileClient.getInstance().identityId)

    val mIotAndroidClient = AWSIotClient(AWSMobileClient.getInstance())
    mIotAndroidClient.setRegion(Region.getRegion("ap-southeast-1"))
    mIotAndroidClient.attachPolicy(attachPolicyRequest)
}

policy on AWS IoT:

{
  "Version": "2012-10-17", 
 "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Subscribe",
        "iot:Connect",
        "iot:Receive"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}

auth-rule(named cognito-auth-goodlinkeriot@sensor.live) has two policies as followed:

  1. AWSIoTDataAccess
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect",
                "iot:Publish",
                "iot:Subscribe",
                "iot:Receive",
                "iot:GetThingShadow",
                "iot:UpdateThingShadow",
                "iot:DeleteThingShadow"
            ],
            "Resource": "*"
        }
    ]
}
  1. Cognito_Auth_Role
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "iot:AttachPrincipalPolicy"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*",
                "cognito-identity:*"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}

Environment(please complete the following information):

SDK Version: 2.12.2
Device Information (please complete the following information):

Device: Samsung note 4 and OPPO A57
Android Version: both 6.0.1

@desokroshan any further progress ?

@desokroshan
Copy link
Contributor

@scdplzop Your issue is different from OP's. From the stacktrace, you need to add iot:AttachPolicy action to the policy statement attached to the auth-role. So the AWSIoTDataAccess policy above should be modified as follows:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect",
                "iot:Publish",
                "iot:Subscribe",
                "iot:Receive",
                "iot:GetThingShadow",
                "iot:UpdateThingShadow",
                "iot:DeleteThingShadow",
                "iot:AttachPolicy"
            ],
            "Resource": "*"
        }
    ]
}

Please feel free to open a new issue if you have follow-up questions.

@desokroshan
Copy link
Contributor

@warlock-jay The following documents lists restricted policy documents granting varying degree of authorization on the IoT resources. Can you check to see if you can find one matching your use case :
IAM IoT Policies - https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html
IoT Policies - https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html
Please let me your exact use case if you are still having issues.

@desokroshan desokroshan added pending-response Issue is pending response from the issue requestor and removed Investigating labels Apr 4, 2019
@frankmuellr frankmuellr added the closing soon Issue will auto-close if there is no additional activity within 7 days. label Apr 10, 2019
@stale
Copy link

stale bot commented Apr 17, 2019

This issue has been automatically closed because of inactivity. Please open a new issue if are still encountering problems.

@stale stale bot closed this as completed Apr 17, 2019
@sharad2970
Copy link

sharad2970 commented Nov 19, 2020

Hello,
trying to connect to IoT with Authenticated user but not connecting to Mqtt.
plz find the error message

com.amazonaws.services.cognitoidentity.model.ResourceNotFoundException: IdentityPool 'us-east-2:1d25e******' not found. (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: 0a52b7)*

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closing soon Issue will auto-close if there is no additional activity within 7 days. iot Issues with the AWS Android SDK for Internet of Things (IoT) pending-response Issue is pending response from the issue requestor question General question
Projects
None yet
Development

No branches or pull requests

5 participants