动态

详情 返回 返回

【HarmonyOS 5】鴻蒙星閃NearLink詳解 - 动态 详情

【HarmonyOS 5】鴻蒙星閃NearLink詳解

一、前言

鴻蒙星閃NearLink Kit 是 HarmonyOS 提供的短距離通信服務,支持星閃設備間的連接、數據交互。例如,手機可作為中心設備與外圍設備(如鼠標、手寫筆、智能家電、車鑰匙等)通過星閃進行連接。

二、NearLink Kit 的接入與使用:

點擊跳轉官方文檔地址
在這裏插入圖片描述

鴻蒙星閃(NearLink)的基本接入代碼示例,包含設備發現、連接和數據傳輸的核心流程:

// NearLink設備管理服務示例

import nearlink from '@ohos.nearlink';
import nearlinkSle from '@ohos.nearlink.sle';
import common from '@ohos.app.ability.common';

// 星閃服務管理類
export class NearLinkManager {
  private context: common.UIAbilityContext | undefined;
  private deviceManager: nearlinkSle.SleDeviceManager | undefined;
  private connectedDeviceId: string | null = null;
  private dataChannel: nearlinkSle.SleDataChannel | undefined;
  
  constructor(context: common.UIAbilityContext) {
    this.context = context;
  }
  
  // 初始化星閃服務
  async initNearLinkService() {
    try {
      // 檢查並請求星閃權限
      await this.checkAndRequestNearLinkPermission();
      
      // 創建設備管理器實例
      this.deviceManager = await nearlinkSle.getSleDeviceManager(this.context!);
      
      // 註冊設備狀態變化監聽
      this.registerDeviceStateListener();
      
      console.info('NearLink service initialized successfully');
    } catch (error) {
      console.error(`Failed to initialize NearLink service: ${error}`);
      throw error;
    }
  }
  
  // 檢查並請求星閃權限
  private async checkAndRequestNearLinkPermission() {
    // 權限檢查邏輯
    // ...
  }
  
  // 開始掃描附近的星閃設備
  async startDiscovery() {
    if (!this.deviceManager) {
      throw new Error('Device manager not initialized');
    }
    
    try {
      // 配置掃描參數
      const discoveryConfig = {
        mode: nearlinkSle.SleDiscoveryMode.ACTIVE,
        duration: 30, // 掃描持續時間(秒)
        filter: {
          deviceTypes: [nearlinkSle.SleDeviceType.ALL]
        }
      };
      
      // 註冊設備發現回調
      const callback = {
        onDeviceFound: (device: nearlinkSle.SleDevice) => {
          console.info(`Found device: ${device.deviceName}, type: ${device.deviceType}`);
          // 處理髮現的設備,例如更新UI
          this.onDeviceDiscovered(device);
        },
        onDiscoveryStateChanged: (state: number) => {
          console.info(`Discovery state changed: ${state}`);
        }
      };
      
      // 開始掃描
      await this.deviceManager.startDiscovery(discoveryConfig, callback);
      console.info('NearLink device discovery started');
    } catch (error) {
      console.error(`Failed to start discovery: ${error}`);
      throw error;
    }
  }
  
  // 處理髮現的設備
  private onDeviceDiscovered(device: nearlinkSle.SleDevice) {
    // 這裏可以添加設備過濾邏輯
    // ...
    
    // 通知UI更新設備列表
    // ...
  }
  
  // 連接到指定星閃設備
  async connectToDevice(deviceId: string) {
    if (!this.deviceManager) {
      throw new Error('Device manager not initialized');
    }
    
    try {
      // 創建連接參數
      const connectParams = {
        timeout: 10000, // 連接超時時間(毫秒)
        connectionType: nearlinkSle.SleConnectionType.DATA_CHANNEL
      };
      
      // 連接設備
      const connectionResult = await this.deviceManager.connect(deviceId, connectParams);
      if (connectionResult.resultCode === 0) {
        this.connectedDeviceId = deviceId;
        this.dataChannel = connectionResult.dataChannel;
        console.info(`Connected to device: ${deviceId}`);
        
        // 註冊數據接收回調
        this.registerDataReceiveListener();
      } else {
        console.error(`Failed to connect device, error code: ${connectionResult.resultCode}`);
        throw new Error(`Connection failed: ${connectionResult.resultCode}`);
      }
    } catch (error) {
      console.error(`Failed to connect device: ${error}`);
      throw error;
    }
  }
  
  // 註冊數據接收監聽器
  private registerDataReceiveListener() {
    if (!this.dataChannel) return;
    
    this.dataChannel.on('dataReceived', (data: ArrayBuffer) => {
      // 處理接收到的數據
      const decoder = new TextDecoder();
      const message = decoder.decode(data);
      console.info(`Received data: ${message}`);
      
      // 通知UI有新數據到達
      // ...
    });
  }
  
  // 發送數據到已連接設備
  async sendData(message: string) {
    if (!this.dataChannel) {
      throw new Error('Data channel not initialized');
    }
    
    try {
      const encoder = new TextEncoder();
      const data = encoder.encode(message).buffer;
      
      // 發送數據
      await this.dataChannel.send(data);
      console.info(`Data sent successfully: ${message}`);
    } catch (error) {
      console.error(`Failed to send data: ${error}`);
      throw error;
    }
  }
  
  // 斷開與設備的連接
  async disconnect() {
    if (!this.deviceManager || !this.connectedDeviceId) return;
    
    try {
      await this.deviceManager.disconnect(this.connectedDeviceId);
      this.connectedDeviceId = null;
      this.dataChannel = undefined;
      console.info('Device disconnected');
    } catch (error) {
      console.error(`Failed to disconnect device: ${error}`);
      throw error;
    }
  }
  
  // 註冊設備狀態變化監聽
  private registerDeviceStateListener() {
    if (!this.deviceManager) return;
    
    this.deviceManager.on('deviceStateChanged', (params) => {
      console.info(`Device state changed: ${JSON.stringify(params)}`);
      // 處理設備狀態變化
      // ...
    });
  }
  
  // 釋放資源
  async release() {
    await this.disconnect();
    
    if (this.deviceManager) {
      try {
        await this.deviceManager.release();
        console.info('NearLink resources released');
      } catch (error) {
        console.error(`Failed to release resources: ${error}`);
      }
    }
  }
}

三、鴻蒙星閃指標對比

以下是鴻蒙星閃、藍牙和NFC在技術性能、應用場景、成本與生態系統等方面的區別表格:

比較項目 鴻蒙星閃 藍牙 NFC
傳輸速率 最高可達2.5Gbps,低功耗模式下峯值速率可達12Mbps 藍牙5.2的傳輸速率為400Mbps,異步連接允許一個方向的數據傳輸速率達到721kbps,反向速率57.6kbps 無(數據傳輸速率通常遠低於前兩者)
延遲表現 傳輸延遲可低至20微秒,響應時延為0.25ms 時延約為600微秒,響應時延約為10ms 無(主要用於近距離快速交互,不強調延遲指標)
連接設備數量 支持最多4096台設備同時連接 一般只能連接8台設備,1個藍牙設備可以同時加入8個不同的微網 無(一般用於一對一的快速連接,不強調多設備連接)
抗干擾能力 採用多種抗干擾技術,抗干擾能力比藍牙提升10dB以上 採用跳頻展頻技術,抗干擾性強,不易竊聽 無(工作距離短,干擾相對較小)
功耗表現 採用先進的功耗管理策略,功耗僅相當於藍牙的60% 功耗較低,適用於多種低功耗設備 功耗較低(工作時間短)
消費電子領域應用 實現高清無損音頻傳輸和低延遲的交互體驗,如華為MatePad Pro 13.2英寸平板電腦和FreeBuds Pro 3無線耳機等產品 廣泛用於無線耳機、音箱等設備的音頻傳輸 可用於設備之間的快速配對和數據傳輸,如手機與音箱、耳機等設備快速連接
智能家居領域應用 能實現多種智能設備的無縫連接,支持更多設備同時在線 用於連接智能家電,實現遠程控制等功能 可通過NFC標籤快速切換手機模式或控制智能家電開關、模式等
智能汽車領域應用 可實現車內外設備的高速、低延遲數據交換,提升自動駕駛的安全性和效率 用於連接車載設備,如車載藍牙電話、藍牙音樂播放等 可用於汽車鑰匙功能,通過手機NFC實現車輛解鎖、啓動等
工業製造領域應用 能滿足高精度控制和大數據傳輸的需求,推動工業4.0的實現 用於工業設備之間的無線連接,如傳感器數據傳輸等 無(一般不用於工業製造場景)
成本 相關解決方案、芯片模塊等成本還比較高 技術成熟,成本較低 成本相對較低
生態系統 生態系統還不夠完善,支持星閃技術的設備相對較少 擁有龐大而成熟的生態系統,幾乎所有電子設備都支持藍牙 在移動支付、交通出行等領域有廣泛的應用,生態系統較為成熟
連接方式與距離 覆蓋範圍約為藍牙的兩倍,常規覆蓋距離可達到20米,設備之間的連接需要在一定範圍內進行配對和連接 一般有效傳輸距離為10cm - 10m,增加發射功率可達到100米,需要進行配對和連接操作 工作距離非常短,一般在幾釐米以內,通常用於設備之間的近距離快速觸碰連接
user avatar vivotech 头像 josie_68d213f999ae8 头像 qiyuxuanangdelvdou 头像 harmonyossdk 头像 xingfendexiyang 头像 5gz5hi3e 头像 aixiaodekaomianbao_ddkwvd 头像 aitaokedemugua 头像 xiangyuecn 头像
点赞 9 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.