1

want to start development with AWS IOT using Android app

I am seeking for example for IOT in android. need to start basic configuration on AWS console and android app. i already tested temperature demo but didn't get any clue from that! need a basic steps on shadow, policy , role. how to configure them step by step and use of cognito.

below getshadow() method is called onCreate , need to update value on real time basis not ony onCreate.

  public void getShadows() {

        GetShadowTask getControlShadowTask = new GetShadowTask("TemperatureControl");
       getControlShadowTask.execute();
    }


    private class GetShadowTask extends AsyncTask<Void, Void, AsyncTaskResult<String>> {

        private final String thingName;

        public GetShadowTask(String name) {
            thingName = name;
        }

        @Override
        protected AsyncTaskResult<String> doInBackground(Void... voids) {
            try {
                GetThingShadowRequest getThingShadowRequest = new GetThingShadowRequest()
                        .withThingName(thingName);
                GetThingShadowResult result = iotDataClient.getThingShadow(getThingShadowRequest);
//                Toast.makeText(getApplication(),result.getPayload().remaining(),Toast.LENGTH_LONG).show();
                byte[] bytes = new byte[result.getPayload().remaining()];
                result.getPayload().get(bytes);
                String resultString = new String(bytes);
                return new AsyncTaskResult<String>(resultString);
            } catch (Exception e) {

                Log.e("E", "getShadowTask", e);
                return new AsyncTaskResult<String>(e);
            }
        }

        @Override
        protected void onPostExecute(AsyncTaskResult<String> result) {
            if (result.getError() == null) {
                JsonParser parser=new JsonParser();
                JsonObject jsonObject= (JsonObject) parser.parse(result.getResult());
response=result.getResult();
         setPoint=jsonObject.getAsJsonObject("state").getAsJsonObject("reported")
               .get("current_date").getAsString();
textView.setText(setPoint);
           //     Toast.makeText(getApplication(),setPoint,Toast.LENGTH_LONG).show();
                Log.i(GetShadowTask.class.getCanonicalName(), result.getResult());

            } else {
                Log.e(GetShadowTask.class.getCanonicalName(), "getShadowTask", result.getError());
                Toast.makeText(getApplication(),result.getError().toString(),Toast.LENGTH_LONG).show();
            }
        }
    }

UPDATE

Thing Shadow

{ "desired": { "welcome": "aws-iot" }, "reported": { "welcome": "aws-iot", "current_date": "06-Sep-2017 1:26:40 PM" } }

2 Answers2

1

AWS has provided a complete Github repo of Android samples. In the samples do the PubSubWebSocket to connect, subscribe and publish the data to the shadow.

If you have a closer look into the PubSubWebSocket example you will find a detailed information on how to to make a thing policy and role. It cannot be more concise and clear than that.

For understanding and using Cognito follow AmazonCognitoAuthDemo example to make the identity pool and use it in the PubSubWebSocket example.

To get a better understanding of roles and Cognito. Please read the AWS documentation.

Update: In the IoT thing policy did you give appropriate permissions to connect, subscribe and publish. The option can be found in AWS IoT->Security->Policy->Create Policy.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "iot:*",
      "Resource": "arn:aws:iot:us-east-2:293751794947:topic/replaceWithATopic"
    }
  ]
}

The above policy gives all access to the user. Also, make sure your pool which you created is for unauthenticated users.

To get the changes to the shadow type the following in the sample android(WebSocketAwsPubSub) edit box $aws/things/thing_name/shadow/update/accepted

And to publish the data to the shadow type $aws/things/thing_name/shadow/update

Update 2: Android Code where you will receive the reported messaged. Its suscribing to the device. Its the copy of the snippet from PubSubWebSocketSample.

public void AwsSubscribe(){
    final String topic = "$aws/things/D1/shadow/update/accepted";

Log.d(LOG_TAG, "topic = " + topic);

try {
    mqttManager.subscribeToTopic(topic, AWSIotMqttQos.QOS0,
            new AWSIotMqttNewMessageCallback() {
                @Override
                public void onMessageArrived(final String topic, final byte[] data) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String message = new String(data, "UTF-8");
                                Log.d(LOG_TAG, "Message arrived:");
                                Log.d(LOG_TAG, "   Topic: " + topic);
                                Log.d(LOG_TAG, " Message: " + message);

                                tvLastMessage.setText(message);

                            } catch (UnsupportedEncodingException e) {
                                Log.e(LOG_TAG, "Message encoding error.", e);
                            }
                        }
                    });
                }
            });
} catch (Exception e) {
    Log.e(LOG_TAG, "Subscription error.", e);
}

}

Aarth Tandel
  • 1,001
  • 12
  • 32
  • Ya i tried that example! but i'm stuck on how to create topic , subscribe to that topic and receive changes if shadow changes in real time. if you have developed something basic on iot please give me resources to understand it step by step. – Jenish Keriwala Sep 06 '17 at 05:34
  • If the shadow changes you will automatically receive the changes in the application. Head here for detailed understanding https://stackoverflow.com/questions/44113956/aws-iot-login-from-android-mqtt-client-using-iam-is-not-working/45993988#45993988 – Aarth Tandel Sep 06 '17 at 06:43
  • If possible provide me snippet. as per my research for getting realtime updates from shadow needs to define rules for triggering updates. – Jenish Keriwala Sep 06 '17 at 06:51
  • already completed policy, role and permission part.what i want is if any changes made to the shadow which will directly reflect on android device. and also want to know how to create topic and publish and subscribe to it. – Jenish Keriwala Sep 06 '17 at 07:06
  • Whenever the shadow is changed by the thing. It will automatically be reflected in the Android code (PubSubWebSocket) if you see the log. You will get the reported thing. Just make a JSON Parser and parse the data to get the updated thing. Do the following in the sample aws code. You will get to know what I am saying. – Aarth Tandel Sep 06 '17 at 07:39
  • so don't need to create topic for getting real time updates! – Jenish Keriwala Sep 06 '17 at 07:43
  • how to create topic in console? and link that topic to thing? – Jenish Keriwala Sep 06 '17 at 09:09
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153756/discussion-between-jenish-keriwala-and-aarth-tandel). – Jenish Keriwala Sep 06 '17 at 09:12
0

If you want to create a topic, just change the value of this variable final String topic = "YOUR TOPIC" then subscribe to it by using the sample code.

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46