• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# communication\_dsoftbus<a name="EN-US_TOPIC_0000001103650648"></a>
2
3-   [Introduction](#section13587125816351)
4-   [Architecture](#section13587185873516)
5-   [Directory Structure](#section161941989596)
6-   [Constraints](#section119744591305)
7-   [Usage](#section1312121216216)
8    -   [Usage Guidelines](#section1698318421816)
9
10-   [Repositories Involved](#section1371113476307)
11
12## Introduction<a name="section13587125816351"></a>
13
14There are various communication modes \(such as Wi-Fi and Bluetooth\), and the usage of different communication modes varies greatly and often leads to problems. In addition, the convergence, sharing, and conflict of communication links cannot be handled. DSoftBus manages unified distributed communications between near-field devices and provides APIs for device discovery, connection, networking, and data transmission, regardless of the link type. It mainly provides the following capabilities:
15
16-   Device discovery and connection in various communication modes, such as WLAN and Bluetooth
17-   Unified device networking and topology management, and device information provisioning for data transmission
18-   Channel setup for transmitting messages and bytes
19
20You can use the APIs provided by DSoftBus to implement fast communications between devices without caring about the communication details, thereby deploying and running services across platforms.
21
22## Architecture<a name="section13587185873516"></a>
23
24**Figure  1**  DSoftBus architecture<a name="fig4460722185514"></a>
25
26
27![](figures/dsoftbus-architecture.png)
28
29## Directory Structure<a name="section161941989596"></a>
30
31The main code directory structure of DSoftBus is as follows:
32
33```
34/foundation/communication/dsoftbus
35├── interfaces            # APIs
36├── adapter               # Adapter code
37├── core                  # Core code
38│   ├── common            # Common code
39│   ├── authentication    # Authentication code
40│   ├── bus_center        # Networking code
41│   ├── connection        # Connection code
42│   ├── discovery         # Discovery code
43│   ├── transmission      # Transmission code
44│   └── frame             # Framework code
45├── sdk                   # Service process code
46│   ├── bus_center        # Networking code
47│   ├── discovery         # Discovery code
48│   ├── transmission      # Transmission code
49│   └── frame             # Framework code
50└── components            # Dependent component code
51```
52
53## Constraints<a name="section119744591305"></a>
54
55-   The devices between which you want to set up a connection must be in the same LAN.
56-   Before setting up a connection between two devices, you must bind the devices. For details about the binding process, see relevant descriptions in the Security subsystem readme file.
57
58## Usage<a name="section1312121216216"></a>
59
60### Usage Guidelines<a name="section1698318421816"></a>
61
62>**NOTICE:**
63>To use RPC across devices, you must have the  **ohos.permission.DISTRIBUTED\_DATASYNC**  permission \(which is a dangerous one\).
64
65>A device can proactively discover a smartphone only when the smartphone has the Visible to all nearby devices feature enabled. (This feature is available in Settings > Super Device > Visible to > All nearby devices.)
66
67**1. Discovery**
68
69-   **Publishing process**
70
711.  Publish a service of your application.
72
73    ```
74    // Callbacks for service publishing
75    typedef struct {
76        void (*OnPublishSuccess)(int publishId); // Called when the service is published successfully.
77        void (*OnPublishFail)(int publishId, PublishFailReason reason);// Called when the service fails to be published.
78    } IPublishCallback;
79
80    // Publish the service.
81    int PublishService(const char *pkgName, const PublishInfo *info, const IPublishCallback *cb);
82    ```
83
842.  Unpublish a service of your application.
85
86    ```
87    // Unpublish a service.
88    int UnPublishService(const char *pkgName, int publishId);
89    ```
90
91
92-   **Discovery process**
93
941.  Discovery a specified device.
95
96    ```
97    // Callbacks for device discovery
98    typedef struct {
99        void (*OnDeviceFound)(const DeviceInfo *device); // Called when a device is found.
100        void (*OnDiscoverFailed)(int subscribeId, DiscoveryFailReason failReason); // Called when the discovery fails to start.
101        void (*OnDiscoverySuccess)(int subscribeId); // Called when the discovery starts successfully.
102    } IDiscoveryCallback;
103
104    // Start a device discovery.
105    int StartDiscovery(const char *pkgName, const SubscribeInfo *info, const IDiscoveryCallback *cb);
106    ```
107
1082.  The DSoftBus notifies you of the device information via the callback once a device is found.
1093.  Stop the discovery as you need.
110
111    ```
112    // Stop the discovery.
113    int StopDiscovery(const char *pkgName, int subscribeId);
114    ```
115
116
117**2. Networking**
118
1191.  Initiate a connection request with the address of the target device and the connection callback.
120
121    ```
122    // Address to connect to
123    typedef struct {
124        ConnectionAddrType type;
125        union {
126            struct BrAddr {
127                char brMac[BT_MAC_LEN];
128            } br;
129            struct BleAddr {
130                char bleMac[BT_MAC_LEN];
131                uint8_t udidHash[UDID_HASH_LEN];
132            } ble;
133            struct IpAddr {
134                char ip[IP_STR_MAX_LEN];
135                uint16_t port;
136            } ip;
137        } info;
138        char peerUid[MAX_ACCOUNT_HASH_LEN];
139    } ConnectionAddr;
140
141    // Address types
142    typedef enum {
143        CONNECTION_ADDR_WLAN = 0,
144        CONNECTION_ADDR_BR,
145        CONNECTION_ADDR_BLE,
146        CONNECTION_ADDR_ETH,
147        CONNECTION_ADDR_MAX
148    } ConnectionAddrType;
149
150    // Callback for the connection result
151    typedef void (*OnJoinLNNResult)(ConnectionAddr *addr, const char *networkId, int32_t retCode);
152
153    // Initiate a connection request.
154    int32_t JoinLNN(const char *pkgName, ConnectionAddr *target, OnJoinLNNResult cb);
155    ```
156
1572.  Wait for the connection result. If  **JoinLNN\(\)**  returns success, the DSoftBus accepts the connection request and notifies you of the connection result through the callback. The  **addr**  parameter in the callback matches the  **target**  parameter in  **JoinLNN\(\)**. If  **retCode**  in the callback is  **0**, the connection is successful. 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.
1583.  Transmit data using transmission APIs.
1594.  Initiate a disconnection request with the  **networkId**  and the callback.
160
161    ```
162    // Callback for the disconnection result
163    typedef void (*OnLeaveLNNResult)(const char *networkId, int32_t retCode);
164
165    // Initiate a disconnection request.
166    int32_t LeaveLNN(const char *pkgName, const char *networkId, OnLeaveLNNResult cb);
167    ```
168
1695.  Wait until the disconnection is complete. The  **networkId**  parameter in  **OnLeaveLNNResult\(\)**  matches  **networkId**  in  **LeaveLNN\(\)**. If  **retCode**  in the callback is  **0**, the disconnection is successful; otherwise, the disconnection fails. If the disconnection is successful,  **networkId**  becomes invalid and can no longer be used.
1706.  Register and unregister callbacks for device state changes.
171
172    ```
173    // Device state events
174    #define EVENT_NODE_STATE_ONLINE 0x1
175    #define EVENT_NODE_STATE_OFFLINE 0x02
176    #define EVENT_NODE_STATE_INFO_CHANGED 0x04
177    #define EVENT_NODE_STATUS_CHANGED 0x08
178    #define EVENT_NODE_STATE_MASK 0xF
179
180    // Device information
181    typedef struct {
182        char networkId[NETWORK_ID_BUF_LEN];
183        char deviceName[DEVICE_NAME_BUF_LEN];
184        uint16_t deviceTypeId;
185    } NodeBasicInfo;
186
187    // Device state event callbacks
188    typedef struct {
189        uint32_t events; // Networking event mask
190        void (*onNodeOnline)(NodeBasicInfo *info);   // Called when the device gets online.
191        void (*onNodeOffline)(NodeBasicInfo *info);  // Called when the device gets offline.
192        void (*onNodeBasicInfoChanged)(NodeBasicInfoType type, NodeBasicInfo *info); // Called when the device information changes.
193        void (*onNodeStatusChanged)(NodeStatusType type, NodeStatus *status); // Called when the device status changed.
194    } INodeStateCb;
195
196    // Register the callback for device state events.
197    int32_t RegNodeDeviceStateCb(const char *pkgName, INodeStateCb *callback);
198
199    // Unregister the callback for device state events.
200    int32_t UnregNodeDeviceStateCb(INodeStateCb *callback);
201    ```
202
203
204**3. Transmission**
205
2061.  Create a session server with a listener. You can use the listener to monitor events such as opening and closing a session, and receiving messages or bytes.
207
208    ```
209    // Callbacks for session management
210    typedef struct {
211        int (*OnSessionOpened)(int sessionId, int result);
212        void (*OnSessionClosed)(int sessionId);
213        void (*OnBytesReceived)(int sessionId, const void *data, unsigned int dataLen);
214        void (*OnMessageReceived)(int sessionId, const void *data, unsigned int dataLen);
215        void (*OnStreamReceived)(int sessionId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param);
216        void (*OnQosEvent)(int sessionId, int eventId, int tvCount, const QosTv *tvList);
217    } ISessionListener;
218
219    // Create a session server.
220    int CreateSessionServer(const char *pkgName, const char *sessionName, const ISessionListener* listener);
221    ```
222
2232.  Open a session for sending and receiving data.
224
225    ```
226    // Open a session.
227    int OpenSession(const char *mySessionName, const char *peerSessionName, const char *peerNetworkId, const char *groupId, const SessionAttribute* attr);
228    ```
229
2303.  Send data to the peer device based on the session ID.
231
232    ```
233    // Send bytes.
234    int SendBytes(int sessionId, const void *data, unsigned int len);
235    // Send messages.
236    int SendMessage(int sessionId, const void *data, unsigned int len);
237    ```
238
2394.  Close a session with a specified ID.
240
241    ```
242    // Close a session.
243    void CloseSession(int sessionId);
244    ```
245
2465.  Remove the session server.
247
248    ```
249    // Remove the session server.
250    int RemoveSessionServer(const char *pkgName, const char *sessionName);
251    ```
252
253
254## Repositories Involved<a name="section1371113476307"></a>
255
256[DSoftBus subsystem](https://gitee.com/openharmony/docs/blob/master/en/readme/dsoftbus.md)
257
258**communication_dsoftbus**
259
260[communication_bluetooth](https://gitee.com/openharmony/communication_bluetooth)
261
262[communication_ipc](https://gitee.com/openharmony/communication_ipc)
263
264[communication_wifi](https://gitee.com/openharmony/communication_wifi)
265