概述
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、数据脚本解析
参考链接
基于开源JAVA MQTT Client连接阿里云IoT
LoRaWAN设备数据解析
阅读原文
本文为云栖社区原创内容,未经允许不得转载。
网友评论