当前位置:   article > 正文

Android设备接入阿里云IoT物联网平台——设备接入类_android 物联网

android 物联网

1. 准备工作

1.1 注册阿里云账号

使用个人淘宝账号或手机号,开通阿里云账号,并通过__实名认证(可以用支付宝认证)__

1.2 免费开通IoT物联网套件

产品官网 ​​https://www.aliyun.com/product/iot​

1.3 软件环境

JDK安装
编辑器 IDEA

2. 开发步骤

2.1 云端开发

1) 创建高级版产品

2) 功能定义,产品物模型添加属性

添加产品属性定义

属性名

标识符

数据类型

范围

温度

temperature

float

-50~100

湿度

humidity

float

0~100

物模型对应属性上报topic

/sys/替换为productKey/替换为deviceName/thing/event/property/post

物模型对应的属性上报payload

  1. {
  2. id: 123452452,
  3. params: {
  4. temperature: 26.2,
  5. humidity: 60.4
  6. },
  7. method: "thing.event.property.post"
  8. }

3) 设备管理>注册设备,获得身份三元组

2.2 设备端开发

我们以java程序来模拟设备,建立连接,上报数据。

1) build.gradle添加sdk依赖

  1. dependencies {
  2. implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'
  3. }

2) AliyunIoTSignUtil工具类

  1. import javax.crypto.Mac;
  2. import javax.crypto.SecretKey;
  3. import javax.crypto.spec.SecretKeySpec;
  4. import java.util.Arrays;
  5. import java.util.Map;
  6. /**
  7. * AliyunIoTSignUtil
  8. */
  9. public class AliyunIoTSignUtil {
  10. public static String sign(Map<String, String> params, String deviceSecret, String signMethod) {
  11. //将参数Key按字典顺序排序
  12. String[] sortedKeys = params.keySet().toArray(new String[] {});
  13. Arrays.sort(sortedKeys);
  14. //生成规范化请求字符串
  15. StringBuilder canonicalizedQueryString = new StringBuilder();
  16. for (String key : sortedKeys) {
  17. if ("sign".equalsIgnoreCase(key)) {
  18. continue;
  19. }
  20. canonicalizedQueryString.append(key).append(params.get(key));
  21. }
  22. try {
  23. String key = deviceSecret;
  24. return encryptHMAC(signMethod,canonicalizedQueryString.toString(), key);
  25. } catch (Exception e) {
  26. throw new RuntimeException(e);
  27. }
  28. }
  29. /**
  30. * HMACSHA1加密
  31. *
  32. */
  33. public static String encryptHMAC(String signMethod,String content, String key) throws Exception {
  34. SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"), signMethod);
  35. Mac mac = Mac.getInstance(secretKey.getAlgorithm());
  36. mac.init(secretKey);
  37. byte[] data = mac.doFinal(content.getBytes("utf-8"));
  38. return bytesToHexString(data);
  39. }
  40. public static final String bytesToHexString(byte[] bArray) {
  41. StringBuffer sb = new StringBuffer(bArray.length);
  42. String sTemp;
  43. for (int i = 0; i < bArray.length; i++) {
  44. sTemp = Integer.toHexString(0xFF & bArray[i]);
  45. if (sTemp.length() < 2) {
  46. sb.append(0);
  47. }
  48. sb.append(sTemp.toUpperCase());
  49. }
  50. return sb.toString();
  51. }
  52. }

3) 模拟设备MainActivity.java代码

  1. public class MainActivity extends AppCompatActivity {
  2. private static final String TAG = MainActivity.class.getSimpleName();
  3. private TextView msgTextView;
  4. private String productKey = "";// 高级版产品key
  5. private String deviceName = "";//已经注册的设备id
  6. private String deviceSecret = "";//设备秘钥
  7. //property post topic
  8. private final String payloadJson = "{\"id\":%s,\"params\":{\"temperature\": %s,\"humidity\": %s},\"method\":\"thing.event.property.post\"}";
  9. private MqttClient mqttClient = null;
  10. final int POST_DEVICE_PROPERTIES_SUCCESS = 1002;
  11. final int POST_DEVICE_PROPERTIES_ERROR = 1003;
  12. private Handler mHandler = new Handler() {
  13. @Override
  14. public void handleMessage(Message msg) {
  15. switch (msg.what) {
  16. case POST_DEVICE_PROPERTIES_SUCCESS:
  17. showToast("发送数据成功");
  18. break;
  19. case POST_DEVICE_PROPERTIES_ERROR:
  20. showToast("post数据失败");
  21. break;
  22. }
  23. }
  24. };
  25. private String responseBody = "";
  26. @Override
  27. protected void onCreate(Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.activity_main);
  30. msgTextView = findViewById(R.id.msgTextView);
  31. findViewById(R.id.activate_button).setOnClickListener((l) -> {
  32. new Thread(() -> initAliyunIoTClient()).start();
  33. });
  34. findViewById(R.id.post_button).setOnClickListener((l) -> {
  35. mHandler.postDelayed(() -> postDeviceProperties(), 1000);
  36. });
  37. findViewById(R.id.quit_button).setOnClickListener((l) -> {
  38. try {
  39. mqttClient.disconnect();
  40. } catch (MqttException e) {
  41. e.printStackTrace();
  42. }
  43. });
  44. }
  45. /**
  46. * 使用 productKey,deviceName,deviceSecret 三元组建立IoT MQTT连接
  47. */
  48. private void initAliyunIoTClient() {
  49. try {
  50. String clientId = "androidthings" + System.currentTimeMillis();
  51. Map<String, String> params = new HashMap<String, String>(16);
  52. params.put("productKey", productKey);
  53. params.put("deviceName", deviceName);
  54. params.put("clientId", clientId);
  55. String timestamp = String.valueOf(System.currentTimeMillis());
  56. params.put("timestamp", timestamp);
  57. // cn-shanghai
  58. String targetServer = "tcp://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883";
  59. String mqttclientId = clientId + "|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|";
  60. String mqttUsername = deviceName + "&" + productKey;
  61. String mqttPassword = AliyunIoTSignUtil.sign(params, deviceSecret, "hmacsha1");
  62. connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. responseBody = e.getMessage();
  66. mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_ERROR);
  67. }
  68. }
  69. public void connectMqtt(String url, String clientId, String mqttUsername, String mqttPassword) throws Exception {
  70. MemoryPersistence persistence = new MemoryPersistence();
  71. mqttClient = new MqttClient(url, clientId, persistence);
  72. MqttConnectOptions connOpts = new MqttConnectOptions();
  73. // MQTT 3.1.1
  74. connOpts.setMqttVersion(4);
  75. connOpts.setAutomaticReconnect(true);
  76. connOpts.setCleanSession(true);
  77. connOpts.setUserName(mqttUsername);
  78. connOpts.setPassword(mqttPassword.toCharArray());
  79. connOpts.setKeepAliveInterval(60);
  80. mqttClient.connect(connOpts);
  81. Log.d(TAG, "connected " + url);
  82. }
  83. /**
  84. * post 数据
  85. */
  86. private void postDeviceProperties() {
  87. try {
  88. Random random = new Random();
  89. //上报数据
  90. String payload = String.format(payloadJson, String.valueOf(System.currentTimeMillis()), 10 + random.nextInt(20), 50 + random.nextInt(50));
  91. responseBody = payload;
  92. MqttMessage message = new MqttMessage(payload.getBytes("utf-8"));
  93. message.setQos(1);
  94. String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
  95. mqttClient.publish(pubTopic, message);
  96. Log.d(TAG, "publish topic=" + pubTopic + ",payload=" + payload);
  97. mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_SUCCESS);
  98. mHandler.postDelayed(() -> postDeviceProperties(), 5 * 1000);
  99. } catch (Exception e) {
  100. e.printStackTrace();
  101. responseBody = e.getMessage();
  102. mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_ERROR);
  103. Log.e(TAG, "postDeviceProperties error " + e.getMessage(), e);
  104. }
  105. }
  106. private void showToast(String msg) {
  107. msgTextView.setText(msg + "\n" + responseBody);
  108. }
  109. }

3. 启动运行

3.1 设备启动

3.2 云端查看设备运行状态

物联网平台产品介绍详情:​​https://www.aliyun.com/product/iot/iot_instc_public_cn​

阿里云物联网平台客户交流群

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/592870
推荐阅读
相关标签
  

闽ICP备14008679号