概述
LoRaWAN裝置與物聯網平台的通信資料格式為透傳/自定義,是以需要使用資料解析腳本,解析上下行資料。本文主要以阿裡雲官方文檔 LoRaWAN裝置資料解析 為基礎,基于開源MQTT SDK,實作完整的: 裝置<->雲端消息鍊路測試。
操作步驟
前期準備
1、建立産品,因為這邊沒有入網憑證,使用WiFi聯網方式,資料格式:透傳/自定義:

2、添加物模型,可以直接參考
官方文檔說明逐個添加,這裡提供對應物模型的完整文本,可以copy内容到本地自己建立的:model.json檔案,然後物聯網平台管理控制台直接導入:
{
"schema":"https://iotx-tsl.oss-ap-southeast-1.aliyuncs.com/schema.json",
"profile":{
"productKey":"********" // 注意為您自己産品的productkey
},
"services":[
{
"outputData":[
],
"identifier":"set",
"inputData":[
{
"identifier":"Temperature",
"dataType":{
"specs":{
"min":"-40",
"max":"55",
"step":"1"
},
"type":"int"
},
"name":"Temperature"
},
{
"identifier":"Humidity",
"dataType":{
"specs":{
"min":"1",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"Humidity"
}
],
"method":"thing.service.property.set",
"name":"set",
"required":true,
"callType":"async",
"desc":"屬性設定"
},
{
"outputData":[
{
"identifier":"Temperature",
"dataType":{
"specs":{
"min":"-40",
"max":"55",
"step":"1"
},
"type":"int"
},
"name":"Temperature"
},
{
"identifier":"Humidity",
"dataType":{
"specs":{
"min":"1",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"Humidity"
}
],
"identifier":"get",
"inputData":[
"Temperature",
"Humidity"
],
"method":"thing.service.property.get",
"name":"get",
"required":true,
"callType":"async",
"desc":"屬性擷取"
},
{
"outputData":[
],
"identifier":"SetTempHumiThreshold",
"inputData":[
{
"identifier":"MaxTemp",
"dataType":{
"specs":{
"min":"-100",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"MaxTemp"
},
{
"identifier":"MinTemp",
"dataType":{
"specs":{
"min":"-100",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"MinTemp"
},
{
"identifier":"MaxHumi",
"dataType":{
"specs":{
"min":"-100",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"MaxHumi"
},
{
"identifier":"MinHumi",
"dataType":{
"specs":{
"min":"-100",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"MinHumi"
}
],
"method":"thing.service.SetTempHumiThreshold",
"name":"SetTempHumiThreshold",
"required":false,
"callType":"async"
}
],
"properties":[
{
"identifier":"Temperature",
"dataType":{
"specs":{
"min":"-40",
"max":"55",
"step":"1"
},
"type":"int"
},
"name":"Temperature",
"accessMode":"rw",
"required":false
},
{
"identifier":"Humidity",
"dataType":{
"specs":{
"min":"1",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"Humidity",
"accessMode":"rw",
"required":false
}
],
"events":[
{
"outputData":[
{
"identifier":"Temperature",
"dataType":{
"specs":{
"min":"-40",
"max":"55",
"step":"1"
},
"type":"int"
},
"name":"Temperature"
},
{
"identifier":"Humidity",
"dataType":{
"specs":{
"min":"1",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"Humidity"
}
],
"identifier":"post",
"method":"thing.event.property.post",
"name":"post",
"type":"info",
"required":true,
"desc":"屬性上報"
},
{
"outputData":[
{
"identifier":"Temperature",
"dataType":{
"specs":{
"min":"-100",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"溫度"
}
],
"identifier":"TempError",
"method":"thing.event.TempError.post",
"name":"TempError",
"type":"alert",
"required":false
},
{
"outputData":[
{
"identifier":"Humidity",
"dataType":{
"specs":{
"min":"-100",
"max":"100",
"step":"1"
},
"type":"int"
},
"name":"濕度"
}
],
"identifier":"HumiError",
"method":"thing.event.HumiError.post",
"name":"HumiError",
"type":"alert",
"required":false
}
]
}
3、添加腳本并測試,腳本使用
官方附錄:示例腳本即可,測試正常後注意點選送出。
4、産品下面添加裝置
虛拟裝置調試
5、線上發送
6、裝置運作狀态
7、二進制資料Base64編碼(對應截圖中使用的AAEC的計算方法)
import sun.misc.BASE64Encoder;
import java.io.IOException;
public class ByteToBase64 {
public static void main(String[] args) throws IOException {
String data = "000102"; // 待轉換的十六進制資料對應的字元串
byte[] bytes = hexToByteArray(data);
String base64Str = getBase64String(bytes);
System.out.println("base64Str: " + base64Str);
}
/**
* 二進制轉base64 String
* @param data 傳入byte[]
* @return String
* @throws IOException
*/
public static String getBase64String(byte[] data) throws IOException {
BASE64Encoder encoder = new BASE64Encoder();
return data != null ? encoder.encode(data) : "";
}
/*** hex字元串轉byte數組
* @param inHex 待轉換的Hex字元串
* @return 轉換後的byte數組結果
*/
public static byte[] hexToByteArray(String inHex){
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1){
//奇數
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {
//偶數
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);
}
}
裝置端開源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();
}
// 設定訂閱監聽
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 {
// 構造連接配接需要的參數
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 {
//上報資料
//進階版 物模型-屬性上報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) {
// 将每個位元組與0xFF進行與運算,然後轉化為10進制,然後借助于Integer再轉化為16進制
tmp = Integer.toHexString(0xFF & b);
if (tmp.length() == 1) {
tmp = "0" + tmp;
}
sb.append(tmp);
}
return sb.toString();
}
/**
* hex字元串轉byte數組
* @param inHex 待轉換的Hex字元串
* @return 轉換後的byte數組結果
*/
public static byte[] hexToByteArray(String inHex){
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1){
//奇數
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {
//偶數
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、裝置運作狀态
10、線上調試服務調用
{
"MaxTemp": 50,
"MinTemp": 8,
"MaxHumi": 90,
"MinHumi": 10
}
11、裝置端下行消息監聽
上報屬性值
Sub message
Topic : /sys/********/device2/thing/model/down_raw
16進制形式輸出:
5d0a000332085a0a
10進制形式輸出:
93 10 0 3 50 8 90 10
12、資料腳本解析