• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# SPP Development
2
3## Introduction
4Serial Port Profile (SPP) is a Bluetooth protocol used to establish serial communication connections between Bluetooth devices. With SPP, Bluetooth devices can transmit data, such as files and text, just like using a serial port.
5
6## When to Use
7
8You can use the APIs provided by the **spp** module to:
9- Write data to the client.
10- Connect to the peer device over a socket.
11
12## Available APIs
13
14For details about the APIs and sample code, see [@ohos.bluetooth.socket](../../reference/apis/js-apis-bluetooth-socket.md).
15
16The following table describes the related APIs.
17
18| API                            | Description                                                                      |
19| ---------------------------------- | ------------------------------------------------------------------------------ |
20| sppListen()                        | Creates an SPP listening socket for the server.                                                      |
21| sppAccept()                        | Accepts a connection request from the client over a socket of the server.                                                 |
22| sppConnect()                       | Initiates an SPP connection to a remote device from the client.                                                    |
23| sppCloseServerSocket()             | Closes the listening socket of the server.                                                          |
24| sppCloseClientSocket()             | Closes the client socket.                                                              |
25| sppWrite()                         | Sends data to the remote end over the socket.                                                      |
26| on(type: 'sppRead')                | Subscribes to the SPP read request events.                                                             |
27| off(type: 'sppRead')               | Unsubscribes from the SPP read request events.                                                          |
28
29## How to Develop
30
31### Writing Data to the Client
321. Import the **socket** module.
332. Check that the SystemCapability.Communication.Bluetooth.Core capability is available.
343. Enable Bluetooth on the device.
354. Creates a server socket. If the operation is successful, **serverId** is returned.
365. Create a communication channel between the server socket and the client socket. If the operation is successful, **clientId** is returned.
376. Write data to the client.
387. (Optional) Subscribe to the data written by the client.
398. Close the server socket.
409. Close the client socket.
41
42Example:
43
44```ts
45import socket from '@ohos.bluetooth.socket';
46import { BusinessError } from '@ohos.base';
47
48// Create a server listening socket. serverId is returned if the socket is created.
49let serverNumber = -1;
50let sppOption: socket.SppOptions = {
51  uuid: '00001101-0000-1000-8000-00805f9b34fb',
52  secure: true,
53  type: 0
54};
55socket.sppListen('server1', sppOption, (code, serverSocketID) => {
56  if (code != null) {
57    console.error('sppListen error, code is ' + (code as BusinessError).code);
58    return;
59  } else {
60    serverNumber = serverSocketID;
61    console.info('sppListen success, serverNumber = ' + serverNumber);
62  }
63});
64
65// Establish a connection between the server socket and client socket. If the connection is successful, clientId is returned.
66let clientNumber = -1;
67socket.sppAccept(serverNumber, (code, clientSocketID) => {
68  if (code != null) {
69    console.error('sppAccept error, code is ' + (code as BusinessError).code);
70    return;
71  } else {
72    clientNumber = clientSocketID;
73    console.info('accept the client success');
74  }
75})
76console.info('waiting for client connection');
77
78// Write data to the client.
79let array = new Uint8Array(990);
80array[0] = 'A'.charCodeAt(0);
81array[1] = 'B'.charCodeAt(0);
82array[2] = 'C'.charCodeAt(0);
83array[3] = 'D'.charCodeAt(0);
84socket.sppWrite(clientNumber, array.buffer);
85console.info('sppWrite success');
86
87// Subscribe to the read request event.
88socket.on('sppRead', clientNumber, (dataBuffer: ArrayBuffer) => {
89  const data = new Uint8Array(dataBuffer);
90  if (data != null) {
91    console.info('sppRead success, data = ' + JSON.stringify(data));
92  } else {
93    console.error('sppRead error, data is null');
94  }
95});
96
97// Unsubscribe from the read request event.
98socket.off('sppRead', clientNumber, (dataBuffer: ArrayBuffer) => {
99  const data = new Uint8Array(dataBuffer);
100  if (data != null) {
101    console.info('offSppRead success, data = ' + JSON.stringify(data));
102  } else {
103    console.error('offSppRead error, data is null');
104  }
105});
106
107// Close the server socket.
108socket.sppCloseServerSocket(serverNumber);
109console.info('sppCloseServerSocket success');
110
111// Close the client socket.
112socket.sppCloseClientSocket(clientNumber);
113console.info('sppCloseClientSocket success');
114```
115For details about the error codes, see [Bluetooth Error Codes](../../reference/errorcodes/errorcode-bluetoothManager.md).
116
117### Connecting to the Peer Device over a Socket
1181. Import the **socket** module.
1192. Check that the SystemCapability.Communication.Bluetooth.Core capability is available.
1203. Enable Bluetooth on the device.
1214. Start Bluetooth scanning to obtain the MAC address of the peer device.
1225. Connect to the peer device.
123
124Example:
125
126```ts
127import socket from '@ohos.bluetooth.socket';
128import { BusinessError } from '@ohos.base';
129
130// Start Bluetooth scanning to obtain the MAC address of the peer device.
131let deviceId = 'xx:xx:xx:xx:xx:xx';
132
133// Connect to the peer device.
134socket.sppConnect(deviceId, {
135  uuid: '00001101-0000-1000-8000-00805f9b34fb',
136  secure: true,
137  type: 0
138}, (code, socketID) => {
139  if (code != null) {
140    console.error('sppConnect error, code = ' + (code as BusinessError).code);
141    return;
142  }
143  console.info('sppConnect success, socketId = ' + socketID);
144})
145```
146For details about the error codes, see [Bluetooth Error Codes](../../reference/errorcodes/errorcode-bluetoothManager.md).