package com.waytronic.libwtronline; import org.junit.Test; import static org.junit.Assert.*; import java.util.Arrays; /** * Example local unit test, which will execute on the development machine (host). * * @see Testing documentation */ public class ExampleUnitTest { @Test public void addition_isCorrect() { // assertEquals(4, 2 + 2); //模拟广播包数据 String hexString = "02010A030357540CFF0050E57757140003640001040D00051003021218100957545F303035306535373735373134"; byte[] scanRecordBytes = hexStringToBytes(hexString); processScanResult(scanRecordBytes); } private void processScanResult(byte[] scanRecordBytes) { if (scanRecordBytes == null) return; // 解析广播数据包格式(BLE 广播数据格式规范) int offset = 0; while (offset < scanRecordBytes.length) { int length = scanRecordBytes[offset] & 0xFF; // 数据段长度 if (length == 0) break; int type = scanRecordBytes[offset + 1] & 0xFF; // 数据类型 // 检查是否为厂商自定义数据(0xFF 类型) if (type == 0xFF) { byte[] data = Arrays.copyOfRange(scanRecordBytes, offset + 2, offset + length + 1); // 厂商自定义数据格式:2字节厂商ID + 自定义内容 if (data.length >= 6) { byte[] macData = Arrays.copyOfRange(data, 0, 6); String macString = bytesToHex(macData); // 转为十六进制字符串 System.out.println("mac地址:" + macString); } } offset += (length + 1); // 移动到下一段 } } public static byte[] hexStringToBytes(String hexString) { if (hexString == null || hexString.isEmpty()) { return new byte[0]; } // 移除所有空格和分隔符(如 "FF A1 B2" -> "FFA1B2") String cleanedHex = hexString.replaceAll("\\s+", ""); // 检查是否为有效十六进制字符串 if (!cleanedHex.matches("[0-9a-fA-F]+")) { throw new IllegalArgumentException("Invalid hex string: " + hexString); } // 补齐偶数长度(例如 "A" -> "0A") if (cleanedHex.length() % 2 != 0) { cleanedHex = "0" + cleanedHex; } byte[] byteArray = new byte[cleanedHex.length() / 2]; for (int i = 0; i < byteArray.length; i++) { int index = i * 2; int hexValue = Integer.parseInt(cleanedHex.substring(index, index + 2), 16); byteArray[i] = (byte) hexValue; } return byteArray; } public String bytesToHex(byte[] bytes) { if (bytes == null){ return ""; } StringBuilder hexString = new StringBuilder(); for (byte b : bytes) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } }