天天看點

阿裡雲物聯網平台一型一密免預注冊Java使用示例

Step By Step

物聯網平台校驗通過後,下發ClientID、DeviceToken。裝置後續通過ProductKey、ProductSecret和下發的ClientID、DeviceToken與雲端建立連接配接,進行資料通信。

1、物聯網平台建立産品,打開動态注冊

阿裡雲物聯網平台一型一密免預注冊Java使用示例

2、pom.xml

<dependencies>
        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.61</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>27.0.1-jre</version>
        </dependency>
    </dependencies>           

3、動态預注冊擷取:clientId、deviceToken測試Code Sample

import com.alibaba.fastjson.JSONObject;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 裝置動态注冊。 
 */
public class DynamicRegisterByMqtt_WithoutDeviceName {

    // 地域ID,填寫您的産品所在地域ID。
    private static String regionId = "cn-shanghai";

    // 定義加密方式。可選MAC算法:HmacMD5、HmacSHA1、HmacSHA256,需和signmethod取值一緻。
    private static final String HMAC_ALGORITHM = "hmacsha1";

    // 接收物聯網平台下發裝置證書的Topic。無需建立,無需訂閱,直接使用。
    private static final String REGISTER_TOPIC = "/ext/regnwl";

    /**
     * 動态注冊。
     *
     * @param productKey 産品key
     * @param productSecret 産品密鑰
     * @param deviceName 裝置名稱
     * @throws Exception
     */
    public void register(String productKey, String productSecret, String deviceName) throws Exception {

        // 接入域名,隻能使用TLS。
        String broker = "ssl://" + productKey + ".iot-as-mqtt." + regionId + ".aliyuncs.com:1883";

        // 表示用戶端ID,建議使用裝置的MAC位址或SN碼,64字元内。
        String clientId = productKey + "." + deviceName;

        // 擷取随機值。
        Random r = new Random();
        int random = r.nextInt(1000000);

        // securemode隻能為2表示隻能使用TLS;signmethod指定簽名算法。
        String clientOpts = "|securemode=2,authType=regnwl,signmethod=" + HMAC_ALGORITHM + ",random=" + random + "|";

        // MQTT接入用戶端ID。
        String mqttClientId = clientId + clientOpts;

        // MQTT接入使用者名。
        String mqttUsername = deviceName + "&" + productKey;

        // MQTT接入密碼,即簽名。
        JSONObject params = new JSONObject();
        params.put("productKey", productKey);
        params.put("deviceName", deviceName);
        params.put("random", random);
        String mqttPassword = sign(params, productSecret);

        // 通過MQTT connect封包進行動态注冊。
        connect(broker, mqttClientId, mqttUsername, mqttPassword);
    }

    /**
     * 通過MQTT connect封包發送動态注冊資訊。
     *
     * @param serverURL 動态注冊域名位址
     * @param clientId 用戶端ID
     * @param username MQTT使用者名
     * @param password MQTT密碼
     */
    @SuppressWarnings("resource")
    private void connect(String serverURL, String clientId, String username, String password) {
        try {
            MemoryPersistence persistence = new MemoryPersistence();
            MqttClient sampleClient = new MqttClient(serverURL, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setMqttVersion(4);// MQTT 3.1.1
            connOpts.setUserName(username);// 使用者名
            connOpts.setPassword(password.toCharArray());// 密碼
            connOpts.setAutomaticReconnect(false); // MQTT動态注冊協定規定必須關閉自動重連。
            System.out.println("----- register params -----");
            System.out.print("server=" + serverURL + ",clientId=" + clientId);
            System.out.println(",username=" + username + ",password=" + password);
            sampleClient.setCallback(new MqttCallback() {
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // 僅處理動态注冊傳回消息。
                    if (REGISTER_TOPIC.equals(topic)) {
                        String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
                        System.out.println("----- register result -----");
                        System.out.println(payload);
                        sampleClient.disconnect();
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                }

                @Override
                public void connectionLost(Throwable cause) {
                }
            });
            sampleClient.connect(connOpts);
        } catch (MqttException e) {
            System.out.print("register failed: clientId=" + clientId);
            System.out.println(",username=" + username + ",password=" + password);
            System.out.println("reason " + e.getReasonCode());
            System.out.println("msg " + e.getMessage());
            System.out.println("loc " + e.getLocalizedMessage());
            System.out.println("cause " + e.getCause());
            System.out.println("excep " + e);
            e.printStackTrace();
        }
    }

    /**
     * 動态注冊簽名。
     *
     * @param params 簽名參數
     * @param productSecret 産品密鑰
     * @return 簽名十六進制字元串
     */
    private String sign(JSONObject params, String productSecret) {

        // 請求參數按字典順序排序。
        Set<String> keys = getSortedKeys(params);

        // sign、signMethod除外。
        keys.remove("sign");
        keys.remove("signMethod");

        // 組裝簽名明文。
        StringBuffer content = new StringBuffer();
        for (String key : keys) {
            content.append(key);
            content.append(params.getString(key));
        }

        // 計算簽名。
        String sign = encrypt(content.toString(), productSecret);
        System.out.println("sign content=" + content);
        System.out.println("sign result=" + sign);

        return sign;
    }

    /**
     * 擷取JSON對象排序後的key集合。
     *
     * @param json 需要排序的JSON對象
     * @return 排序後的key集合
     */
    private Set<String> getSortedKeys(JSONObject json) {
        SortedMap<String, String> map = new TreeMap<String, String>();
        for (String key : json.keySet()) {
            String vlaue = json.getString(key);
            map.put(key, vlaue);
        }
        return map.keySet();
    }

    /**
     * 使用HMAC_ALGORITHM加密。
     *
     * @param content 明文
     * @param secret 密鑰
     * @return 密文
     */
    private String encrypt(String content, String secret) {
        try {
            byte[] text = content.getBytes(StandardCharsets.UTF_8);
            byte[] key = secret.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_ALGORITHM);
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return byte2hex(mac.doFinal(text));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 二進制轉十六進制字元串。
     *
     * @param b 二進制數組
     * @return 十六進制字元串
     */
    private String byte2hex(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int n = 0; b != null && n < b.length; n++) {
            String stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append('0');
            }
            sb.append(stmp);
        }
        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) throws Exception {

        String productKey = "a1J********";
        String productSecret = "IWfYPtnm********";
        String deviceName = "device8";// 自定義的裝置名稱,運作後會在控制台自動建立裝置

        // 進行動态注冊。
        DynamicRegisterByMqtt_WithoutDeviceName client = new DynamicRegisterByMqtt_WithoutDeviceName();
        client.register(productKey, productSecret, deviceName);

        // 動态注冊成功,需要在本地固化deviceSecre或者clientId、deviceToken。
    }
}           

4、裝置端連接配接:Code Sample

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class DynamicDeivceConnectByToken_Demo1 {


    public static String productKey = "a1JQQ9St8cf";
    public static String deviceName = "device8";
    public static String clientId = "****************";
    public static String token = "^1^160145822536**************";
    public static String regionId = "cn-shanghai";

    // 物模型-屬性上報topic
    private static String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
    // 自定義topic,在産品Topic清單位置定義
    private static String subTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";

    private static MqttClient mqttClient;

    public static void main(String [] args){

        initAliyunIoTClient();
        ScheduledExecutorService scheduledThreadPool = new ScheduledThreadPoolExecutor(1,
                new ThreadFactoryBuilder().setNameFormat("thread-runner-%d").build());

        scheduledThreadPool.scheduleAtFixedRate(()->postDeviceProperties(), 2,2, TimeUnit.SECONDS);

        try {
            mqttClient.subscribe(subTopic); // 訂閱Topic
        } catch (MqttException e) {
            System.out.println("error:" + e.getMessage());
            e.printStackTrace();
        }

        // 設定訂閱監聽
        mqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {
                System.out.println("connection Lost");

            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                System.out.println("Sub message");
                System.out.println("Topic : " + s);
                System.out.println(new String(mqttMessage.getPayload())); //列印輸出消息payLoad
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });

    }

    /**
     * 初始化 Client 對象
     */
    private static void initAliyunIoTClient() {

        try {
            // cn-shanghai
            String targetServer = "tcp://" + productKey + ".iot-as-mqtt."+regionId+".aliyuncs.com:1883";
            String mqttUsername = deviceName + "&" + productKey;
            String mqttClientId = clientId + "|securemode=-2,authType=connwl|"; //clientId+"|securemode=-2,authType=connwl|"
            String mqttPassword = token;// deviceToken
            System.out.println("mqttClientId:" + mqttClientId);
            System.out.println("mqttPassword: " + mqttPassword);
            System.out.println("mqttUsername: " + mqttUsername);

            connectMqtt(targetServer, mqttClientId, mqttUsername, mqttPassword);
        } catch (Exception e) {
            System.out.println("initAliyunIoTClient error " + e.getMessage());
        }
    }

    public static 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(false);
        connOpts.setConnectionTimeout(10);
//        connOpts.setCleanSession(true);
        connOpts.setCleanSession(false);

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

        mqttClient.connect(connOpts);
    }

    /**
     * 彙報屬性
     */
    private static void postDeviceProperties() {

        try {
            //上報資料
            //進階版 物模型-屬性上報payload
            System.out.println("上報屬性值");
            String payloadJson = "{\"params\":{\"CH2\":22,\"CH1\":\"33\",\"CH3\":\"11\"}}";

            MqttMessage message = new MqttMessage(payloadJson.getBytes("utf-8"));
            message.setQos(1);
            mqttClient.publish(pubTopic, message);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}           

5、裝置資訊

阿裡雲物聯網平台一型一密免預注冊Java使用示例

參考連結

一型一密 IoT 裝置免燒錄三元組,無需預注冊,基于MQTT即時注冊三元組,快速上雲方案