设备发现与组网测试工具设计与实现 原创

进修的泡芙
发布于 2025-6-17 20:41
浏览
0收藏

设备发现与组网测试工具设计与实现

一、项目概述

基于HarmonyOS分布式能力构建的设备发现与组网测试工具,可自动发现周边设备并测试组网性能。借鉴《鸿蒙跨端U同步》中的设备发现与状态同步机制,实现多设备自动组网、网络质量测试与可视化分析。

二、架构设计

±--------------------+
设备发现引擎
(Discovery Engine)

±---------±---------+
±---------v----------+ ±--------------------+

组网测试控制器 <—> 分布式通信服务
(Test Controller) (Distributed Comm)

±---------±---------+ ±--------------------+
±---------v----------+

测试结果可视化
(Visualization)

±--------------------+

三、核心代码实现
设备发现服务

// 设备发现服务
public class DeviceDiscoveryService {
private static final String TAG = “DeviceDiscovery”;
private DeviceManager deviceManager;
private List<DeviceInfo> discoveredDevices = new ArrayList<>();
private DiscoveryListener listener;

public DeviceDiscoveryService(Context context) {
    this.deviceManager = DeviceManager.getInstance(context);

// 开始发现设备

public void startDiscovery(DiscoveryListener listener) {
    this.listener = listener;
    
    deviceManager.startDiscovery(new DeviceDiscoveryCallback() {
        @Override
        public void onDeviceFound(DeviceInfo device) {
            if (!containsDevice(device)) {
                discoveredDevices.add(device);
                notifyDeviceFound(device);

}

        @Override
        public void onDiscoveryFailed(int errorCode) {
            notifyDiscoveryFailed(errorCode);

});

// 停止发现设备

public void stopDiscovery() {
    deviceManager.stopDiscovery();

// 获取已发现设备列表

public List<DeviceInfo> getDiscoveredDevices() {
    return new ArrayList<>(discoveredDevices);

private boolean containsDevice(DeviceInfo newDevice) {

    for (DeviceInfo device : discoveredDevices) {
        if (device.getDeviceId().equals(newDevice.getDeviceId())) {
            return true;

}

    return false;

private void notifyDeviceFound(DeviceInfo device) {

    if (listener != null) {
        listener.onDeviceFound(device);

}

private void notifyDiscoveryFailed(int errorCode) {
    if (listener != null) {
        listener.onDiscoveryFailed(errorCode);

}

public interface DiscoveryListener {
    void onDeviceFound(DeviceInfo device);
    void onDiscoveryFailed(int errorCode);

// 设备信息类

public static class DeviceInfo {
    private String deviceId;
    private String deviceName;
    private DeviceType deviceType;
    private int signalStrength; // dBm
    
    // Getters & Setters
    public String getDeviceId() { return deviceId; }
    public String getDeviceName() { return deviceName; }
    public DeviceType getDeviceType() { return deviceType; }
    public int getSignalStrength() { return signalStrength; }

public enum DeviceType {

    PHONE, TABLET, TV, IOT

}

组网测试控制器

// 组网测试控制器
public class NetworkTestController {
private static final String TAG = “NetworkTest”;
private DistributedDataManager dataManager;
private String sessionId;
private TestListener listener;
private Map<String, TestResult> testResults = new ConcurrentHashMap<>();

public NetworkTestController(Context context) {
    this.dataManager = DistributedDataManagerFactory.getInstance()
        .createDistributedDataManager(context);

// 创建测试会话

public void createTestSession(String sessionId, List<DeviceInfo> devices) {
    this.sessionId = sessionId;
    
    // 注册测试结果监听
    dataManager.registerDataChangeListener(
        "network_test_" + sessionId,
        new DataChangeListener() {
            @Override
            public void onDataChanged(String deviceId, String key, String value) {
                TestResult result = TestResult.fromJson(value);
                testResults.put(deviceId, result);
                
                if (listener != null) {
                    listener.onTestProgress(deviceId, result);

if (testResults.size() == devices.size()) {

                    if (listener != null) {
                        listener.onTestCompleted(testResults);

}

}

    );
    
    // 向所有设备发送测试指令
    for (DeviceInfo device : devices) {
        startPingTest(device.getDeviceId());

}

// 启动Ping测试
private void startPingTest(String deviceId) {
    JSONObject testCommand = new JSONObject();
    try {
        testCommand.put("command", "start_ping_test");
        testCommand.put("target_device", DeviceInfo.getLocalDeviceId());
        testCommand.put("test_id", sessionId);

catch (JSONException e) {

        return;

dataManager.putString(

        "network_test_cmd_" + deviceId,
        testCommand.toString()
    );

// 测试结果类

public static class TestResult {
    private String deviceId;
    private int latency; // ms
    private float packetLoss; // %
    private int bandwidth; // Mbps
    
    public String toJson() {
        JSONObject json = new JSONObject();
        try {
            json.put("deviceId", deviceId);
            json.put("latency", latency);
            json.put("packetLoss", packetLoss);
            json.put("bandwidth", bandwidth);

catch (JSONException e) {

            return "{}";

return json.toString();

public static TestResult fromJson(String jsonStr) {

        try {
            JSONObject json = new JSONObject(jsonStr);
            TestResult result = new TestResult();
            result.deviceId = json.getString("deviceId");
            result.latency = json.getInt("latency");
            result.packetLoss = (float)json.getDouble("packetLoss");
            result.bandwidth = json.getInt("bandwidth");
            return result;

catch (JSONException e) {

            return null;

}

public interface TestListener {

    void onTestProgress(String deviceId, TestResult result);
    void onTestCompleted(Map<String, TestResult> results);

}

测试执行端实现

// 测试执行Ability
public class TestExecutorAbility extends Ability {
private static final String TAG = “TestExecutor”;
private DistributedDataManager dataManager;

@Override
public void onStart(Intent intent) {
    super.onStart(intent);
    
    dataManager = DistributedDataManagerFactory.getInstance()
        .createDistributedDataManager(this);
    
    // 监听测试命令
    dataManager.registerDataChangeListener(
        "network_test_cmd_" + DeviceInfo.getLocalDeviceId(),
        new DataChangeListener() {
            @Override
            public void onDataChanged(String deviceId, String key, String value) {
                try {
                    JSONObject command = new JSONObject(value);
                    if ("start_ping_test".equals(command.getString("command"))) {
                        String testId = command.getString("test_id");
                        String targetDevice = command.getString("target_device");
                        executeNetworkTest(testId, targetDevice);

} catch (JSONException e) {

                    HiLog.error(TAG, "Invalid test command: " + e.getMessage());

}

);

// 执行网络测试

private void executeNetworkTest(String testId, String targetDevice) {
    new Thread(() -> {
        // 模拟网络测试结果
        NetworkTestController.TestResult result = new NetworkTestController.TestResult();
        result.deviceId = DeviceInfo.getLocalDeviceId();
        
        // 测试延迟
        result.latency = measureLatency(targetDevice);
        
        // 测试丢包率
        result.packetLoss = measurePacketLoss(targetDevice);
        
        // 测试带宽
        result.bandwidth = measureBandwidth(targetDevice);
        
        // 上报测试结果
        dataManager.putString(
            "network_test_" + testId,
            result.toJson()
        );
    }).start();

// 测量延迟

private int measureLatency(String targetDevice) {
    // 实际实现应使用真实的网络测量方法
    return 50 + (int)(Math.random() * 50);

// 测量丢包率

private float measurePacketLoss(String targetDevice) {
    // 实际实现应使用真实的网络测量方法
    return (float)(Math.random() * 5);

// 测量带宽

private int measureBandwidth(String targetDevice) {
    // 实际实现应使用真实的网络测量方法
    return 50 + (int)(Math.random() * 50);

}

测试结果可视化

// 测试结果展示AbilitySlice
public class TestResultSlice extends AbilitySlice {
private Map<String, NetworkTestController.TestResult> results;
private RadarChartView radarChart;

@Override
public void onStart(Intent intent) {
    super.onStart(intent);
    setUIContent(ResourceTable.Layout_test_result_layout);
    
    // 获取测试结果
    results = intent.getSerializableParam("results");
    
    // 初始化图表
    radarChart = (RadarChartView) findComponentById(ResourceTable.Id_radar_chart);
    displayResults();

private void displayResults() {

    List<RadarChartView.Indicator> indicators = new ArrayList<>();
    
    // 添加指标
    indicators.add(new RadarChartView.Indicator("延迟(ms)", 0, 100));
    indicators.add(new RadarChartView.Indicator("丢包率(%)", 0, 5));
    indicators.add(new RadarChartView.Indicator("带宽(Mbps)", 0, 100));
    
    radarChart.setIndicators(indicators);
    
    // 添加设备数据
    for (Map.Entry<String, NetworkTestController.TestResult> entry : results.entrySet()) {
        String deviceName = DeviceInfo.getDeviceName(entry.getKey());
        NetworkTestController.TestResult result = entry.getValue();
        
        RadarChartView.DataSet dataSet = new RadarChartView.DataSet();
        dataSet.setLabel(deviceName);
        dataSet.setColor(getDeviceColor(entry.getKey()));
        dataSet.addValue(result.latency);
        dataSet.addValue(result.packetLoss * 100); // 转换为百分比
        dataSet.addValue(result.bandwidth);
        
        radarChart.addDataSet(dataSet);

radarChart.startAnimation();

private int getDeviceColor(String deviceId) {

    // 为不同设备分配不同颜色
    int hash = deviceId.hashCode();
    return Color.rgb(
        (hash & 0xFF0000) >> 16,
        (hash & 0x00FF00) >> 8,
        hash & 0x0000FF
    );

}

四、XML布局示例

<!-- 设备发现布局 discovery_layout.xml -->
<DirectionalLayout
xmlns:ohos=“http://schemas.huawei.com/res/ohos
ohos:width=“match_parent”
ohos:height=“match_parent”
ohos:orientation=“vertical”
ohos:padding=“24vp”>

<Text
    ohos:width="match_parent"
    ohos:height="wrap_content"
    ohos:text="设备发现与组网测试"
    ohos:text_size="32fp"
    ohos:margin_bottom="24vp"/>
    
<Button
    ohos:id="$+id/start_discovery"
    ohos:width="match_parent"
    ohos:height="60vp"
    ohos:text="开始发现设备"
    ohos:margin_bottom="16vp"/>
    
<ScrollView
    ohos:width="match_parent"
    ohos:height="0vp"
    ohos:weight="1">
    
    <ListContainer
        ohos:id="$+id/device_list"
        ohos:width="match_parent"
        ohos:height="match_content"/>
</ScrollView>

<Button
    ohos:id="$+id/start_test"
    ohos:width="match_parent"
    ohos:height="60vp"
    ohos:text="开始组网测试"
    ohos:visibility="hide"
    ohos:margin_top="16vp"/>

</DirectionalLayout>

<!-- 测试结果布局 test_result_layout.xml -->
<DirectionalLayout
xmlns:ohos=“http://schemas.huawei.com/res/ohos
ohos:width=“match_parent”
ohos:height=“match_parent”
ohos:orientation=“vertical”
ohos:padding=“24vp”>

<Text
    ohos:width="match_parent"
    ohos:height="wrap_content"
    ohos:text="组网测试结果"
    ohos:text_size="28fp"
    ohos:margin_bottom="24vp"/>
    
<com.example.testtool.RadarChartView
    ohos:id="$+id/radar_chart"
    ohos:width="match_parent"
    ohos:height="400vp"
    ohos:margin_bottom="24vp"/>
    
<TableLayout
    ohos:id="$+id/result_table"
    ohos:width="match_parent"
    ohos:height="match_content"/>

</DirectionalLayout>

五、技术创新点
智能设备发现:自动发现周边HarmonyOS设备并识别设备类型

多维度测试:全面测量延迟、丢包率、带宽等网络指标

分布式测试:利用HarmonyOS分布式能力实现多设备协同测试

可视化分析:雷达图直观展示各设备网络性能差异

实时反馈:测试过程中实时更新进度和结果

六、总结

本设备发现与组网测试工具实现了以下核心价值:
网络质量评估:量化多设备间的通信性能

问题诊断:快速定位组网中的性能瓶颈

设备管理:可视化展示周边设备状态

自动化测试:一键完成多设备组网测试

标准规范:建立统一的设备组网测试方法

系统借鉴了《鸿蒙跨端U同步》中的设备发现与状态同步机制,将游戏场景的设备管理技术应用于组网测试领域。未来可增加更多测试指标(如抖动、吞吐量等),并与网络优化策略结合实现智能组网。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏
回复
举报
回复
    相关推荐