简体   繁体   English

如何在 android 应用程序上获取 aws-iot 事物阴影

[英]How to get aws-iot thing shadow on android app

want to start development with AWS IOT using Android app想使用 Android 应用程序开始使用 AWS IOT 进行开发

I am seeking for example for IOT in android.我正在寻找例如 android 中的物联网。 need to start basic configuration on AWS console and android app.需要在 AWS 控制台和 android 应用程序上启动基本配置。 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.如何逐步配置它们以及使用 cognito。

below getshadow() method is called onCreate , need to update value on real time basis not ony onCreate.下面的 getshadow() 方法称为 onCreate ,需要实时更新值而不是 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" } } { "desired": { "welcome": "aws-iot" }, "reported": { "welcome": "aws-iot", "current_date": "06-Sep-2017 1:26:40 PM" } }

AWS has provided a complete Github repo of Android samples. AWS 提供了完整的 Android 示例Github 存储库 In the samples do the PubSubWebSocket to connect, subscribe and publish the data to the shadow.在示例中执行PubSubWebSocket来连接、订阅和发布数据到影子。

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.如果您仔细查看 PubSubWebSocket 示例,您将找到有关如何制定事物策略和角色的详细信息。 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.为了理解和使用 Cognito,请按照AmazonCognitoAuthDemo示例制作身份池并在 PubSubWebSocket 示例中使用它。

To get a better understanding of roles and Cognito.更好地了解角色和 Cognito。 Please read the AWS documentation.请阅读 AWS 文档。

Update: In the IoT thing policy did you give appropriate permissions to connect, subscribe and publish.更新:在 IoT 事物政策中,您是否授予了适当的连接、订阅和发布权限。 The option can be found in AWS IoT->Security->Policy->Create Policy.该选项可以在 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要获取对阴影的更改,请在示例 android(WebSocketAwsPubSub) 编辑框$aws/things/thing_name/shadow/update/accepted键入以下内容

And to publish the data to the shadow type $aws/things/thing_name/shadow/update并将数据发布到影子类型$aws/things/thing_name/shadow/update

Update 2: Android Code where you will receive the reported messaged.更新 2: Android 代码,您将在其中收到报告的消息。 Its suscribing to the device.它依赖于设备。 Its the copy of the snippet from PubSubWebSocketSample.它是来自 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);
}

} }

如果要创建主题,只需更改此变量final String topic = "YOUR TOPIC"的值,然后使用示例代码订阅它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Android应用程序上获得aws-iot的东西阴影?我为此使用了rest api(由aws创建),但需要了解如何使用rest api添加标头? - How to get aws-iot thing shadow on android app??I Used rest api(created by aws) for this but need to understand how to add headers with rest api? Android AWS IoT示例不更新阴影 - Android AWS IoT example not updating shadow 无法使用适用于Android的AWS开发工具包在AWS IoT中创建事物 - Unable to create a Thing in AWS IoT using AWS sdk for Android Android 应用程序使用 X.509 证书连接到 AWS IoT - Android app to connect to AWS IoT using X.509 certificate Android:如何向App Widget添加阴影 - Android: how to add shadow to App Widget 如何在EditTexts上摆脱这种奇怪的灰色阴影效果? - How do I get rid of this weird gray drop shadow thing on my EditTexts? 如何在Android中的ListView末尾获得阴影效果? - How to get a shadow effect at end of the ListView in android? 如何在Android应用程序UI上获取带阴影的框? - How to get boxes with shadow on an Android application UI? 解锁手机后如何让Android应用程序首先启动 - How to make android app to first thing to be launched after Unlocking phone 如何在我的android应用中检测导致电池电量耗尽的原因? - How to detect which thing is causing battery drain in my android app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM