溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何解析LoRaWAN設備數(shù)據(jù)及開源MQTT SDK設備端模擬

發(fā)布時間:2021-10-22 16:36:18 來源:億速云 閱讀:194 作者:柒染 欄目:大數(shù)據(jù)

這期內容當中小編將會給大家?guī)碛嘘P如何解析LoRaWAN設備數(shù)據(jù)及開源MQTT SDK設備端模擬,文章內容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

概述

LoRaWAN設備與物聯(lián)網(wǎng)平臺的通信數(shù)據(jù)格式為透傳/自定義,因此需要使用數(shù)據(jù)解析腳本,解析上下行數(shù)據(jù)。本文主要以阿里云官方文檔LoRaWAN設備數(shù)據(jù)解析為基礎,基于開源MQTT SDK,實現(xiàn)完整的: 設備<->云端消息鏈路測試。

操作步驟

前期準備


1、創(chuàng)建產品,因為這邊沒有入網(wǎng)憑證,使用WiFi聯(lián)網(wǎng)方式,數(shù)據(jù)格式:透傳/自定義:
如何解析LoRaWAN設備數(shù)據(jù)及開源MQTT SDK設備端模擬cdn.com/597e368e382cffc50012a9ecfd3e0a0db2deb00c.png">

2、添加物模型,可以直接參考官方文檔說明逐個添加,這里提供對應物模型的完整文本,可以copy內容到本地自己創(chuàng)建的:model.json文件,然后物聯(lián)網(wǎng)平臺管理控制臺直接導入:

{
    "schema":"https://iotx-tsl.oss-ap-southeast-1.aliyuncs.com/schema.json",
    "profile":{
        "productKey":"********">

如何解析LoRaWAN設備數(shù)據(jù)及開源MQTT SDK設備端模擬

3、添加腳本并測試,腳本使用官方附錄:示例腳本即可,測試正常后注意點擊提交。
如何解析LoRaWAN設備數(shù)據(jù)及開源MQTT SDK設備端模擬

虛擬設備調試


5、在線發(fā)送
如何解析LoRaWAN設備數(shù)據(jù)及開源MQTT SDK設備端模擬

7、二進制數(shù)據(jù)Base64編碼(對應截圖中使用的AAEC的計算方法)

import sun.misc.BASE64Encoder;
import java.io.IOException;

public class ByteToBase64 {

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

        String data = "000102"; // 待轉換的十六進制數(shù)據(jù)對應的字符串
        byte[] bytes = hexToByteArray(data);
        String base64Str = getBase64String(bytes);
        System.out.println("base64Str: ">

設備端開源MQTT SDK接入

8、設備端代碼

import com.alibaba.taro.AliyunIoTSignUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

// 透傳類設備測試
public class IoTDemoPubSubDemo {

    public static String productKey = "********";
    public static String deviceName = "device2";
    public static String deviceSecret = "*********";
    public static String regionId = "cn-shanghai";

    // 物模型-屬性上報topic
    private static String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/model/up_raw";
    // 物模型-訂閱屬性Topic
    private static String subTopic = "/sys/" + productKey + "/" + deviceName + "/thing/model/down_raw";

    private static MqttClient mqttClient;

    public static void main(String [] args){

        initAliyunIoTClient(); // 初始化Client
//        ScheduledExecutorService scheduledThreadPool = new ScheduledThreadPoolExecutor(1,
//                new ThreadFactoryBuilder().setNameFormat("thread-runner-%d").build());
//
//        scheduledThreadPool.scheduleAtFixedRate(()->postDeviceProperties(), 10,10, TimeUnit.SECONDS);
        // 匯報屬性
        postDeviceProperties();
        try {
            mqttClient.subscribe(subTopic); // 訂閱Topic
        } catch (MqttException e) {
            System.out.println("error:" + e.getMessage());
            e.printStackTrace();
        }

        // 設置訂閱監(jiān)聽
        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("16進制形式輸出:");
                System.out.println(bytes2hex(mqttMessage.getPayload()));

                System.out.println("10進制形式輸出:");
                byte[] bytes = mqttMessage.getPayload();
                for (byte t:bytes)
                {
                    System.out.print(t + " ");
                }
             }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });

    }

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

        try {
            // 構造連接需要的參數(shù)
            String clientId = "java" + System.currentTimeMillis();
            Map<String, String> params = new HashMap<>(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."+regionId+".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) {
            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.setCleanSession(true);

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

        mqttClient.connect(connOpts);
    }

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

        try {
            //上報數(shù)據(jù)
            //高級版 物模型-屬性上報payload
            System.out.println("上報屬性值");
            String hexString = "000111";
            byte[] payLoad = hexToByteArray(hexString);
            MqttMessage message = new MqttMessage(payLoad);
            message.setQos(0);
            mqttClient.publish(pubTopic, message);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    // 十進制byte[] 轉16進制 String
    public static String bytes2hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (byte b : bytes) {
            // 將每個字節(jié)與0xFF進行與運算,然后轉化為10進制,然后借助于Integer再轉化為16進制
            tmp = Integer.toHexString(0xFF & b);
            if (tmp.length() == 1) {
                tmp = "0" + tmp;
            }
            sb.append(tmp);
        }
        return sb.toString();

    }

    /**
     * hex字符串轉byte數(shù)組
     * @param inHex 待轉換的Hex字符串
     * @return  轉換后的byte數(shù)組結果
     */
    public static byte[] hexToByteArray(String inHex){
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1){
            //奇數(shù)
            hexlen++;
            result = new byte[(hexlen/2)];
            inHex="0"+inHex;
        }else {
            //偶數(shù)
            result = new byte[(hexlen/2)];
        }
        int j=0;
        for (int i = 0; i < hexlen; i+=2){
            result[j]=hexToByte(inHex.substring(i,i+2));
            j++;
        }
        return result;
    }

    /**
     * Hex字符串轉byte
     * @param inHex 待轉換的Hex字符串
     * @return  轉換后的byte
     */
    public static byte hexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }
}

9、設備運行狀態(tài)
如何解析LoRaWAN設備數(shù)據(jù)及開源MQTT SDK設備端模擬

10、在線調試服務調用

{
        "MaxTemp": 50,
        "MinTemp": 8,
        "MaxHumi": 90,
        "MinHumi": 10
}

_

11、設備端下行消息監(jiān)聽

上報屬性值
Sub message
Topic : /sys/********/device2/thing/model/down_raw
16進制形式輸出:
5d0a000332085a0a
10進制形式輸出:
93 10 0 3 50 8 90 10

12、數(shù)據(jù)腳本解析

如何解析LoRaWAN設備數(shù)據(jù)及開源MQTT SDK設備端模擬

上述就是小編為大家分享的如何解析LoRaWAN設備數(shù)據(jù)及開源MQTT SDK設備端模擬了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI