关于java:Android设备接入阿里云IoT物联网平台设备接入类

40次阅读

共计 5567 个字符,预计需要花费 14 分钟才能阅读完成。

1. 筹备工作

1.1 注册阿里云账号

应用集体淘宝账号或手机号,开明阿里云账号,并通过__实名认证(能够用支付宝认证)__

1.2 收费开明 IoT 物联网套件

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

1.3 软件环境

JDK 装置
编辑器 IDEA

2. 开发步骤

2.1 云端开发

1) 创立高级版产品

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

增加产品属性定义

物模型对应属性上报 topic

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

物模型对应的属性上报 payload

{
    id: 123452452,
    params: {
        temperature: 26.2,
        humidity: 60.4
    },
    method: "thing.event.property.post"
}

3) 设施治理 > 注册设施,取得身份三元组

2.2 设施端开发

咱们以 java 程序来模仿设施,建设连贯,上报数据。

1) build.gradle 增加 sdk 依赖

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

2) AliyunIoTSignUtil 工具类

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Map;

/**
 * AliyunIoTSignUtil
 */

public class AliyunIoTSignUtil {public static String sign(Map<String, String> params, String deviceSecret, String signMethod) {
        // 将参数 Key 按字典程序排序
        String[] sortedKeys = params.keySet().toArray(new String[] {});
        Arrays.sort(sortedKeys);

        // 生成规范化申请字符串
        StringBuilder canonicalizedQueryString = new StringBuilder();
        for (String key : sortedKeys) {if ("sign".equalsIgnoreCase(key)) {continue;}
            canonicalizedQueryString.append(key).append(params.get(key));
        }

        try {
            String key = deviceSecret;
            return encryptHMAC(signMethod,canonicalizedQueryString.toString(), key);
        } catch (Exception e) {throw new RuntimeException(e);
        }
    }

    /**
     * HMACSHA1 加密
     *
     */
    public static String encryptHMAC(String signMethod,String content, String key) throws Exception {SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"), signMethod);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        byte[] data = mac.doFinal(content.getBytes("utf-8"));
        return bytesToHexString(data);
    }

    public static final String bytesToHexString(byte[] bArray) {StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();}

}

3) 模仿设施 MainActivity.java 代码

public class MainActivity extends AppCompatActivity {private static final String TAG = MainActivity.class.getSimpleName();

    private TextView msgTextView;

    private String productKey = "";// 高级版产品 key
    private String deviceName = "";// 曾经注册的设施 id
    private String deviceSecret = "";// 设施秘钥

    //property post topic
    private final String payloadJson = "{\"id\":%s,\"params\":{\"temperature\": %s,\"humidity\": %s},\"method\":\"thing.event.property.post\"}";
    private MqttClient mqttClient = null;

    final int POST_DEVICE_PROPERTIES_SUCCESS = 1002;
    final int POST_DEVICE_PROPERTIES_ERROR = 1003;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {switch (msg.what) {
                case POST_DEVICE_PROPERTIES_SUCCESS:
                    showToast("发送数据胜利");
                    break;
                case POST_DEVICE_PROPERTIES_ERROR:
                    showToast("post 数据失败");
                    break;
            }
        }
    };

    private String responseBody = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        msgTextView = findViewById(R.id.msgTextView);

        findViewById(R.id.activate_button).setOnClickListener((l) -> {new Thread(() -> initAliyunIoTClient()).start();});


        findViewById(R.id.post_button).setOnClickListener((l) -> {mHandler.postDelayed(() -> postDeviceProperties(), 1000);
        });


        findViewById(R.id.quit_button).setOnClickListener((l) -> {
            try {mqttClient.disconnect();
            } catch (MqttException e) {e.printStackTrace();
            }
        });

    }


    /**
     * 应用 productKey,deviceName,deviceSecret 三元组建设 IoT MQTT 连贯
     */
    private void initAliyunIoTClient() {

        try {String clientId = "androidthings" + System.currentTimeMillis();

            Map<String, String> params = new HashMap<String, String>(16);
            params.put("productKey", productKey);
            params.put("deviceName", deviceName);
            params.put("clientId", clientId);
            String timestamp = String.valueOf(System.currentTimeMillis());
            params.put("timestamp", timestamp);

            // cn-shanghai
            String targetServer = "tcp://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883";

            String mqttclientId = clientId + "|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|";
            String mqttUsername = deviceName + "&" + productKey;
            String mqttPassword = AliyunIoTSignUtil.sign(params, deviceSecret, "hmacsha1");

            connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);


        } catch (Exception e) {e.printStackTrace();
            responseBody = e.getMessage();
            mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_ERROR);
        }
    }

    public void connectMqtt(String url, String clientId, String mqttUsername, String mqttPassword) throws Exception {MemoryPersistence persistence = new MemoryPersistence();
        mqttClient = new MqttClient(url, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        // MQTT 3.1.1
        connOpts.setMqttVersion(4);
        connOpts.setAutomaticReconnect(true);
        connOpts.setCleanSession(true);

        connOpts.setUserName(mqttUsername);
        connOpts.setPassword(mqttPassword.toCharArray());
        connOpts.setKeepAliveInterval(60);

        mqttClient.connect(connOpts);
        Log.d(TAG, "connected" + url);

    }

    /**
     * post 数据
     */
    private void postDeviceProperties() {

        try {Random random = new Random();

            // 上报数据
            String payload = String.format(payloadJson, String.valueOf(System.currentTimeMillis()), 10 + random.nextInt(20), 50 + random.nextInt(50));
            responseBody = payload;
            MqttMessage message = new MqttMessage(payload.getBytes("utf-8"));
            message.setQos(1);


            String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
            mqttClient.publish(pubTopic, message);
            Log.d(TAG, "publish topic=" + pubTopic + ",payload=" + payload);
            mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_SUCCESS);

            mHandler.postDelayed(() -> postDeviceProperties(), 5 * 1000);
        } catch (Exception e) {e.printStackTrace();
            responseBody = e.getMessage();
            mHandler.sendEmptyMessage(POST_DEVICE_PROPERTIES_ERROR);
            Log.e(TAG, "postDeviceProperties error" + e.getMessage(), e);
        }
    }

    private void showToast(String msg) {msgTextView.setText(msg + "\n" + responseBody);
    }


}

3. 启动运行

3.1 设施启动

3.2 云端查看设施运行状态

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

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

正文完
 0