Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to parse LoRaWAN device data and open source MQTT SDK device-side simulation

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to parse LoRaWAN device data and open source MQTT SDK device-side simulation. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

Overview

The communication data format between LoRaWAN devices and the Internet of things platform is transparent / custom, so it is necessary to use data parsing scripts to parse up and down data. This paper is mainly based on Aliyun official document LoRaWAN device data analysis, based on open source MQTT SDK, to achieve a complete: device cloud message link testing.

Operation steps

Preparation in advance

1. Create a product because there is no network access certificate here. Use WiFi networking method. Data format: transparent / custom:

Cdn.com/597e368e382cffc50012a9ecfd3e0a0db2deb00c.png ">

2. Add the model one by one by referring to the official documentation. The complete text of the corresponding model is provided here. You can copy the content into the local self-created model.json file, and then import it directly into the Internet of things platform management console:

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

3. Add a script and test it. The script uses the official appendix: sample script. Click submit after the test is normal.

Virtual device debugging

5. Send online

7. Base64 encoding of binary data (corresponding to the calculation method of AAEC used in the screenshot)

Import sun.misc.BASE64Encoder;import java.io.IOException;public class ByteToBase64 {public static void main (String [] args) throws IOException {String data = "000102"; / / string byte [] bytes = hexToByteArray (data) for hexadecimal data to be converted; String base64Str = getBase64String (bytes); System.out.println ("base64Str:" > device-side open source MQTT SDK access

8. Device-side code

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;// transparent device test public class IoTDemoPubSubDemo {public static String productKey = "*"; public static String deviceName = "device2"; public static String deviceSecret = "*" Public static String regionId = "cn-shanghai"; / / property reporting topic private static String pubTopic = "/ sys/" + productKey + "/" + deviceName + "/ thing/model/up_raw"; / / property model-subscription attribute Topic private static String subTopic = "/ sys/" + productKey + "/" + deviceName + "/ thing/model/down_raw"; private static MqttClient mqttClient; public static void main (String [] args) {initAliyunIoTClient () / / initialize Client// ScheduledExecutorService scheduledThreadPool = new ScheduledThreadPoolExecutor (1mqttClient.subscribe / new ThreadFactoryBuilder (). SetNameFormat ("thread-runner-%d"). Build (); / scheduledThreadPool.scheduleAtFixedRate (()-> postDeviceProperties (), 10 mqttClient.subscribe 10, TimeUnit.SECONDS); / / report attribute postDeviceProperties (); try {mqttClient.subscribe (subTopic) / / subscribe to Topic} catch (MqttException e) {System.out.println ("error:" + e.getMessage ()); e.printStackTrace ();} / / set subscription listening mqttClient.setCallback (new MqttCallback () {@ Override public void connectionLost (Throwable throwable) {System.out.println ("connectionLost")) } @ Override public void messageArrived (String s, MqttMessage mqttMessage) throws Exception {System.out.println ("Sub message"); System.out.println ("Topic:" + s); System.out.println ("hexadecimal output:"); System.out.println (bytes2hex (mqttMessage.getPayload () System.out.println ("decimal output:"); byte [] bytes = mqttMessage.getPayload (); for (byte t:bytes) {System.out.print (t + "") } @ Override public void deliveryComplete (IMqttDeliveryToken iMqttDeliveryToken) {}});} / * * initialize Client object * / private static void initAliyunIoTClient () {try {/ / parameters needed to construct a connection String clientId = "java" + System.currentTimeMillis () Map 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) } / * * reporting attribute * / private static void postDeviceProperties () {try {/ / report data / / Premium Edition object Model-attribute reporting payload System.out.println ("report attribute value"); 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 ());}} / / Decimal byte [] to hexadecimal String public static String bytes2hex (byte [] bytes) {StringBuilder sb = new StringBuilder () String tmp = null; for (byte b: bytes) {/ / calculate each byte with 0xFF, then convert it to decimal, and then convert it to hexadecimal tmp = Integer.toHexString (0xFF & b) with the help of Integer; if (tmp.length () = = 1) {tmp = "0" + tmp } sb.append (tmp);} return sb.toString ();} / * hex string to byte array * @ param inHex Hex string to be converted * @ return converted byte array result * / public static byte [] hexToByteArray (String inHex) {int hexlen = inHex.length (); byte [] result If (hexlen% 2 = = 1) {/ / Odd hexlen++; result = new byte [(hexlen/2)]; inHex= "0" + inHex;} else {/ / even result = new byte [(hexlen/2)];} int jung0; 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. Device end downlink message monitoring

Report attribute value Sub messageTopic: / sys/*/device2/thing/model/down_raw16 binary output: 5d0a000332085a0a10 binary output: 93 10 03 50 8 90 10

12. Data script parsing

The above is how to parse LoRaWAN device data and open source MQTT SDK device-side simulation. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report