• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# DSoftBus
2
3
4## Introduction
5
6DSoftBus implements unified distributed communications between near-field devices and provides APIs for device discovery, connection, networking, and data transmission, regardless of the link type. It provides the following capabilities:
7
8-   Device discovery and connection in various communication modes, such as WLAN and Bluetooth.
9-   Unified device networking and topology management, and device information provisioning for data transmission.
10-   Channel setup for transmitting messages, bytes, streams, and files.
11
12You can use the APIs provided by DSoftBus to implement fast communication between devices without caring about the communication details, which facilitating deployment and running of services across platforms.
13
14## Architecture
15
16![](figures/dsoftbus-architecture.png)
17
18**Figure 1** DSoftBus architecture
19
20## Directory Structure
21
22The DSoftBus directory structure is as follows:
23
24```text
25//foundation/communication/dsoftbus
26├── adapter               # Adaptation code
27├── components            # Dependent component code
28├── core                  # Core code
29│   ├── adapter           # Adaptation code
30│   ├── authentication    # Authentication code
31│   ├── bus_center        # Networking code
32│   ├── common            # Common code
33│   ├── connection        # Connection code
34│   ├── discovery         # Discovery code
35│   ├── frame             # Framework code
36│   └── transmission      # Transmission code
37├── interfaces            # External APIs
38├── sdk                   # Service process code
39│   ├── bus_center        # Networking code
40│   ├── discovery         # Discovery code
41│   ├── frame             # Framework code
42│   └── transmission      # Transmission code
43├── tests                 # Test code
44└── tools                 # Tool code
45```
46
47## Constraints
48
49-   Connections can be set up only between the devices in the same LAN or between near-field devices.
50-   Before setting up a connection between two devices, you must bind the devices. For details about the binding process, see the Security subsystem readme file.
51-   After data transmission is complete, the service needs to close the session to release resources.
52
53## Usage
54
55### Usage Guidelines
56
57>**NOTE**
58>
59>- The permissions ohos.permission.DISTRIBUTED_DATASYNC and ohos.permission.DISTRIBUTED_SOFTBUS_CENTER are required for remote procedure calls (RPCs) across devices.
60>- To make a mobile phone visible to other devices, choose **Settings** > **Super Device** > **This device** > **Visible to**, and select **All nearby devices**.
61
62**1. Discovery**
63
64-   **Publishing process**
65
661.  Publish a service of your application.
67
68    ```C
69    // Callback for service publishing.
70    typedef struct {
71        /** Callback used to return the publish result. */
72        void (*OnPublishResult)(int publishId, PublishResult reason);
73    } IPublishCb;
74
75    // Publish a service.
76    int32_t PublishLNN(const char *pkgName, const PublishInfo *info, const IPublishCb *cb);
77    ```
78
792.  Unpublish a service of your application.
80
81    ```C
82    // Unpublish a service.
83    int32_t StopPublishLNN(const char *pkgName, int32_t publishId);
84    ```
85
86
87-   **Discovery process**
88
891.  Discover a device.
90
91    ```C
92    // Callbacks for device discovery.
93    typedef struct {
94        /** Callback invoked when a device is found. */
95        void (*OnDeviceFound)(const DeviceInfo *device);
96        /** Callback invoked to return the device discovery result. */
97        void (*OnDiscoverResult)(int32_t refreshId, RefreshResult reason);
98    } IRefreshCallback;
99
100    // Start device discovery.
101    int32_t RefreshLNN(const char *pkgName, const SubscribeInfo *info, const IRefreshCallback *cb);
102    ```
103
1042.  DSoftBus notifies the service of the device information via the callback once a device is found.
1053.  Stop device discovery.
106
107    ```C
108    // Stop the discovery.
109    int32_t StopRefreshLNN(const char *pkgName, int32_t refreshId);
110    ```
111
112**2. Networking**
113
1141.  Initiate a connection request with the address of the target device and the connection callback.
115
116    ```C
117    // Address to connect to.
118    typedef struct {
119        ConnectionAddrType type;
120        union {
121            struct BrAddr {
122                char brMac[BT_MAC_LEN];
123            } br;
124            struct BleAddr {
125                char bleMac[BT_MAC_LEN];
126                uint8_t udidHash[UDID_HASH_LEN];
127            } ble;
128            struct IpAddr {
129                char ip[IP_STR_MAX_LEN];
130                uint16_t port;
131            } ip;
132        } info;
133        char peerUid[MAX_ACCOUNT_HASH_LEN];
134    } ConnectionAddr;
135
136    // Address type.
137    typedef enum {
138        CONNECTION_ADDR_WLAN = 0,
139        CONNECTION_ADDR_BR,
140        CONNECTION_ADDR_BLE,
141        CONNECTION_ADDR_ETH,
142        CONNECTION_ADDR_MAX
143    } ConnectionAddrType;
144
145    // Callback invoked to return the connection result.
146    typedef void (*OnJoinLNNResult)(ConnectionAddr *addr, const char *networkId, int32_t retCode);
147
148    // Initiate a connection request.
149    int32_t JoinLNN(const char *pkgName, ConnectionAddr *target, OnJoinLNNResult cb);
150    ```
151
1522.  Wait for the connection result. If DSoftBus accepts the connection request, a callback is invoked to return the result. In the return value, if **retCode** is **0**, the connection is successful, and the **addr** parameter matches the **target** parameter in **JoinLNN()**. In this case, the value of **networkId** is valid and will be used in the data transmission and disconnection APIs. If the value of **retCode** is not **0**, the connection fails, and the value of **networkId** is invalid.
1533.  Transmit data using transmission APIs.
1544.  Initiate a disconnection request with the **networkId** and the callback.
155
156    ```C
157    // Callback invoked to return the disconnection result.
158    typedef void (*OnLeaveLNNResult)(const char *networkId, int32_t retCode);
159
160    // Initiate a disconnection request.
161    int32_t LeaveLNN(const char *pkgName, const char *networkId, OnLeaveLNNResult cb);
162    ```
163
1645.  Wait until the disconnection is complete. The **networkId** parameter in **OnLeaveLNNResult()** matches **networkId** in **LeaveLNN()**. If **retCode** is **0**, the disconnection is successful; otherwise, the disconnection fails. If the disconnection is successful, **networkId** becomes invalid and can no longer be used.
1656.  Register and unregister callbacks for device state changes.
166
167    ```C
168    // Device state events.
169    #define EVENT_NODE_STATE_ONLINE 0x1
170    #define EVENT_NODE_STATE_OFFLINE 0x02
171    #define EVENT_NODE_STATE_INFO_CHANGED 0x04
172    #define EVENT_NODE_STATUS_CHANGED 0x08
173    #define EVENT_NODE_STATE_MASK 0xF
174
175    // Device information.
176    typedef struct {
177        char networkId[NETWORK_ID_BUF_LEN];
178        char deviceName[DEVICE_NAME_BUF_LEN];
179        uint16_t deviceTypeId;
180    } NodeBasicInfo;
181
182    // Device state event callbacks.
183    typedef struct {
184        uint32_t events; // Networking event mask.
185        void (*onNodeOnline)(NodeBasicInfo *info);   // Called when the device gets online.
186        void (*onNodeOffline)(NodeBasicInfo *info);  // Called when the device gets offline.
187        void (*onNodeBasicInfoChanged)(NodeBasicInfoType type, NodeBasicInfo *info); // Called when the device information changes.
188        void (*onNodeStatusChanged)(NodeStatusType type, NodeStatus *status); // Called when the device running status changes.
189    } INodeStateCb;
190
191    // Register the callback for device state events.
192    int32_t RegNodeDeviceStateCb(const char *pkgName, INodeStateCb *callback);
193
194    // Unregister the callback for device state events.
195    int32_t UnregNodeDeviceStateCb(INodeStateCb *callback);
196    ```
197
198**3. Transmission**
199
2001.  Create a **Socket** instance.
201
202    ```C
203    typedef struct {
204        char *name;               // Local socket name.
205        char *peerName;           // Peer socket name.
206        char *peerNetworkId;      // Peer network ID.
207        char *pkgName;            // Bundle name of the caller.
208        TransDataType dataType;   // Type of the data to be transmitted, which must be the same as that in the sender() method.
209    } SocketInfo;
210
211    // Create sockets.
212    int32_t Socket(SocketInfo info);
213    ```
214
2152.  Start listening for the socket on the server, and bind the socket on the client.
216
217    ```C
218    // Callbacks for the socket.
219    typedef struct {
220        void (*OnBind)(int32_t socket, PeerSocketInfo info);
221        void (*OnShutdown)(int32_t socket, ShutdownReason reason);
222        void (*OnBytes)(int32_t socket, const void *data, uint32_t dataLen);
223        void (*OnMessage)(int32_t socket, const void *data, uint32_t dataLen);
224        void (*OnStream)(int32_t socket, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param);
225        void (*OnFile)(int32_t socket, FileEvent *event);
226        void (*OnQos)(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount);
227    } ISocketListener;
228
229    typedef enum {
230        QOS_TYPE_MIN_BW,           // Minimum bandwidth.
231        QOS_TYPE_MAX_LATENCY,      // Maximum link setup latency.
232        QOS_TYPE_MIN_LATENCY,      // Minimum link setup latency.
233        QOS_TYPE_MAX_WAIT_TIMEOUT, // Maximum timeout period.
234        QOS_TYPE_MAX_BUFFER,       // Maximum buffer size.
235        QOS_TYPE_FIRST_PACKAGE,    // Size of the first packet.
236        QOS_TYPE_MAX_IDLE_TIMEOUT, // Maximum idle time.
237        QOS_TYPE_TRANS_RELIABILITY,// Transmission reliability.
238        QOS_TYPE_BUTT,
239    } QosType;
240
241    typedef struct {
242        QosType qos;
243        int32_t value;
244    } QosTV;
245
246    // Start listening for the socket on the server.
247    int32_t Listen(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener);
248
249    // Bind the socket on the client.
250    int32_t Bind(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener);
251    ```
252
2534. Send data to the peer device through the socket.
254
255    ```C
256    // Send bytes.
257    int32_t SendBytes(int32_t socket, const void *data, uint32_t len);
258    // Send messages.
259    int32_t SendMessage(int32_t socket, const void *data, uint32_t len);
260    // Send streams.
261    int32_t SendStream(int32_t socket, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param);
262    // Send a file.
263    int32_t SendFile(int32_t socket, const char *sFileList[], const char *dFileList[], uint32_t fileCnt);
264    ```
265
2665. Shut down the socket.
267
268    ```C
269    // Shut down the socket.
270    void Shutdown(int32_t socket);
271    ```
272
273## Repositories Involved
274
275[DSoftBus](https://gitee.com/openharmony/docs/blob/master/en/readme/dsoftbus.md)
276
277**communication_dsoftbus**
278
279[communication_bluetooth](https://gitee.com/openharmony/communication_bluetooth)
280
281[communication_ipc](https://gitee.com/openharmony/communication_ipc)
282
283[communication_wifi](https://gitee.com/openharmony/communication_wifi)
284