目录

Transferring Data Using NearLink

You can establish port channels and execute data transfer. A device can be both the sending port and receiving port.

Use Cases

NearLink data transfer is supported since 5.1.0(18), including port registration, connection establishment, and data read/write.

Your app can transfer data between devices through NearLink, based on the logical link established between the devices.

  1. Data transfer links are not encrypted by default. You need to call the startPairing API to start the pairing process before performing encrypted data transfer.

  2. You can call the getAcbState API to check whether a link is encrypted. The ENCRYPTED state indicates that the link is encrypted.

API Description

API Description
createPort(uuid: string): void Registers a port.
connect(params: ConnectionParams): Promise<void> Connect to a remote device and establishes a port channel. This API uses a promise to return the result.
writeData(params: DataParams): Promise<void> Send data to a remote device using the device address and UUID. This API uses a promise to return the result.
on(type: 'connectionStateChanged', callback: Callback<ConnectionResult>): void Subscribes to the port channel connection status change event. This API uses a callback to return the result asynchronously.
on(type: 'readData', callback: Callback<DataParams>): void Subscribes to the port channel data receiving event. This API uses a callback to return the result asynchronously.

Development Procedure

  1. Import required modules.

    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    import { scan, ssap, dataTransfer, constant, remoteDevice } from '@kit.NearLinkKit';
  2. (Optional) Encrypt the pairing between the local device and the remote device. (This step is required for encrypted data transfer.) After the operation, different types of dialog boxes will be displayed based on the input and output capability flags of both the local and remote devices. The user will need to confirm the pairing. Currently, the following dialog boxes are supported: dialog box for pairing without input, dialog box for comparing numbers, and dialog box for passcode authentication.

    @State chosenDeviceAddr: string = '00:11:22:33:AA:FF';
    // ...
    let device: remoteDevice.RemoteDevice;
    try {
      device = remoteDevice.createRemoteDevice(this.chosenDeviceAddr);
      device.startPairing().then(()=>{
        hilog.info(this.domainId, this.logTag, `start pairing success`);
        // ...
      }).catch ((err: BusinessError) => {
        hilog.error(this.domainId, this.logTag, `errCode: ${err.code}, errMessage: ${err.message}`);
      });
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
    }
  3. Register ports, including data sending and receiving ports. The UUID of the sending port must be the same as that of the receiving port.

    const SERVICE_UUID: string = 'FFFFFFFF-1234-5678-ABCD-000000001234';
    try {
      dataTransfer.createPort(SERVICE_UUID);
      hilog.info(this.domainId, this.logTag, `Create port finished`);
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
    }
  4. Subscribes to the port channel connection status change event.

    let onReceiveConnectionStateEvent:(data: dataTransfer.ConnectionResult) => void =
      (data: dataTransfer.ConnectionResult) => {
      hilog.info(this.domainId, this.logTag, `Port connection state: ${JSON.stringify(data)}`);
      // ...
    };
    try {
      dataTransfer.on('connectionStateChanged', onReceiveConnectionStateEvent);
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
    }
  5. Subscribes to the port channel data receiving event.

    let onReceiveReadDataEvent:(data: dataTransfer.DataParams) => void = (data: dataTransfer.DataParams) => {
      hilog.info(this.domainId, this.logTag, `Port read data: ${JSON.stringify(data)}`);
    };
    try {
      dataTransfer.on('readData', onReceiveReadDataEvent);
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
    }
  6. Connect to a remote device and establishes a port channel. The UUID must be the same as that of the ports registered in Step 3.

    let connectionParams: dataTransfer.ConnectionParams = {
      address: this.chosenDeviceAddr,
      uuid: SERVICE_UUID,
      mtu: 1024
    };
    try {
      dataTransfer.connect(connectionParams).then(() => {
        hilog.info(this.domainId, this.logTag, `Connect port finished`);
      }).catch((err: BusinessError) => {
        hilog.error(this.domainId, this.logTag, `errCode: ${err.code}, errMessage: ${err.message}`);
      });
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
    }
  7. Send data to a remote device using the device address and UUID. The UUID must be the same as that of the ports registered in Step 3.

    let transferValueBuffer: Uint8Array = new Uint8Array(4);
    transferValueBuffer[0] = 1;
    transferValueBuffer[1] = 2;
    transferValueBuffer[2] = 3;
    transferValueBuffer[3] = 4;
    let dataParams: dataTransfer.DataParams = {
      address: this.chosenDeviceAddr,
      uuid: SERVICE_UUID,
      data: transferValueBuffer.buffer
    };
    try {
      dataTransfer.writeData(dataParams).then(() => {
        hilog.info(this.domainId, this.logTag, `Port data write: ${JSON.stringify(dataParams)}`);
        // ...
      }).catch((err: BusinessError) => {
        hilog.error(this.domainId, this.logTag, `errCode: ${err.code}, errMessage: ${err.message}`);
      });
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
    }

Sample Code

For details about the data transmission function, see the implementation method in entry/src/main/ets/pages/SsapClientPage.ets in NearLink sample code.