• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Device Management
2
3The **DeviceManager** module provides APIs for distributed device management.
4
5System applications can call the APIs to do the following:
6
7- Subscribe to or unsubscribe from device state changes.
8- Discover peripheral untrusted devices.
9- Authenticate or deauthenticate a device.
10- Query the trusted device list.
11- Query local device information, including the device name, type, and ID.
12
13> **NOTE**
14>
15> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
16> - The APIs of this module are system APIs and cannot be called by third-party applications.
17
18
19## Modules to Import
20
21```
22import deviceManager from '@ohos.distributedHardware.deviceManager';
23```
24
25
26## deviceManager.createDeviceManager
27
28createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager>): void
29
30Creates a **DeviceManager** instance.
31
32**System capability**: SystemCapability.DistributedHardware.DeviceManager
33
34- **Parameters**
35  | Name       | Type                                      | Mandatory  | Description                                  |
36  | ---------- | ---------------------------------------- | ---- | ------------------------------------ |
37  | bundleName | string                                   | Yes   | Bundle name of an application.                          |
38  | callback   | AsyncCallback<[DeviceManager](#devicemanager)> | Yes   | Callback used to return the **DeviceManager** instance created.|
39
40- Example
41  ```
42  deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => {
43      if (err) {
44          console.info("createDeviceManager err:" + JSON.stringify(err));
45          return;
46      }
47      console.info("createDeviceManager success");
48      let dmInstance = data;
49  });
50  ```
51
52## DeviceInfo
53
54Defines device information.
55
56**System capability**: SystemCapability.DistributedHardware.DeviceManager
57
58| Name                    | Type                       | Mandatory  | Description      |
59| ---------------------- | ------------------------- | ---- | -------- |
60| deviceId               | string                    | Yes   | Unique identifier of a device.|
61| deviceName             | string                    | Yes   | Device name.   |
62| deviceType             | [DeviceType](#devicetype) | Yes   | Device type.   |
63| networkId<sup>8+</sup> | string                    | Yes   | Network ID of the device. |
64
65
66## DeviceType
67
68Enumerates the device types.
69
70**System capability**: SystemCapability.DistributedHardware.DeviceManager
71
72| Name          | Default Value | Description  |
73| ------------ | ---- | ---- |
74| SPEAKER      | 0x0A | Smart speaker.|
75| PHONE        | 0x0E | Phone.  |
76| TABLET       | 0x11 | Tablet.  |
77| WEARABLE     | 0x6D | Wearable.|
78| TV           | 0x9C | Smart TV. |
79| CAR          | 0x83 | Car.   |
80| UNKNOWN_TYPE | 0    | Unknown device type.|
81
82
83## DeviceStateChangeAction
84
85Enumerates the device states.
86
87**System capability**: SystemCapability.DistributedHardware.DeviceManager
88
89| Name     | Default Value | Description             |
90| ------- | ---- | --------------- |
91| ONLINE  | 0    | The device is online.          |
92| READY   | 1    | The device is ready, and the device information has been synchronized.|
93| OFFLINE | 2    | The device is offline.          |
94| CHANGE  | 3    | The device information is changed.        |
95
96## SubscribeInfo
97
98Defines subscription information.
99
100**System capability**: SystemCapability.DistributedHardware.DeviceManager
101
102| Name           | Type                               | Mandatory  | Description               |
103| ------------- | --------------------------------- | ---- | ----------------- |
104| subscribeId   | number                            | Yes   | Subscription ID, used to identify a device discovery period.|
105| mode          | [DiscoverMode ](#discovermode)    | No   | Device discovery mode.            |
106| medium        | [ExchangeMedium](#exchangemedium) | No   | Medium used for device discovery.            |
107| freq          | [ExchangeFreq](#exchangefreq)     | No   | Frequency of device discovery.            |
108| isSameAccount | boolean                           | No   | Whether the same account is used on the discovered device.           |
109| isWakeRemote  | boolean                           | No   | Whether to wake up the discovered device.          |
110| capability    | [SubscribeCap](#subscribecap)     | No   | Discovery capability.            |
111
112
113## DiscoverMode
114
115Enumerates the device discovery modes.
116
117**System capability**: SystemCapability.DistributedHardware.DeviceManager
118
119| Name                   | Default Value | Description   |
120| --------------------- | ---- | ----- |
121| DISCOVER_MODE_PASSIVE | 0x55 | Passive discovery.|
122| DISCOVER_MODE_ACTIVE  | 0xAA | Active discovery.|
123
124
125## ExchangeMedium
126
127Enumerates the media used for device discovery.
128
129**System capability**: SystemCapability.DistributedHardware.DeviceManager
130
131| Name  | Default Value | Description       |
132| ---- | ---- | --------- |
133| AUTO | 0    | Automatic.  |
134| BLE  | 1    | Bluetooth.  |
135| COAP | 2    | Wi-Fi.|
136| USB  | 3    | USB. |
137
138## ExchangeFreq
139
140Enumerates the device discovery frequencies.
141
142**System capability**: SystemCapability.DistributedHardware.DeviceManager
143
144| Name        | Default Value | Description   |
145| ---------- | ---- | ----- |
146| LOW        | 0    | Low frequency. |
147| MID        | 1    | Medium frequency. |
148| HIGH       | 2    | High frequency. |
149| SUPER_HIGH | 3    | Ultra-high frequency.|
150
151
152## SubscribeCap
153
154Enumerates the discovery capabilities.
155
156**System capability**: SystemCapability.DistributedHardware.DeviceManager
157
158| Name                       | Default Value | Description            |
159| ------------------------- | ---- | -------------- |
160| SUBSCRIBE_CAPABILITY_DDMP | 0    | DDMP capability. This will be deprecated later.|
161| SUBSCRIBE_CAPABILITY_OSD  | 1    | OSD capability.        |
162
163
164## AuthParam
165
166Defines the authentication parameters.
167
168**System capability**: SystemCapability.DistributedHardware.DeviceManager
169
170| Name       | Type                  | Mandatory  | Description        |
171| --------- | -------------------- | ---- | ---------- |
172| authType  | number               | Yes   | Authentication type.     |
173| extraInfo | {[key:string] : any} | No   | Extended field.|
174
175## AuthInfo
176
177Defines authentication information.
178
179**System capability**: SystemCapability.DistributedHardware.DeviceManager
180
181| Name       | Type                  | Mandatory  | Description        |
182| --------- | -------------------- | ---- | ---------- |
183| authType  | number               | Yes   | Authentication type.     |
184| token     | number               | Yes   | Authentication token.  |
185| extraInfo | {[key:string] : any} | No   | Extended field.|
186
187
188## DeviceManager
189
190Provides APIs to obtain information about trusted devices and local devices. Before calling any API in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**.
191
192
193### release
194
195release(): void
196
197Releases this **DeviceManager** instance when it is no longer used.
198
199**System capability**: SystemCapability.DistributedHardware.DeviceManager
200
201- Example
202  ```js
203  dmInstance.release();
204  ```
205
206
207### getTrustedDeviceListSync
208
209getTrustedDeviceListSync(): Array&lt;DeviceInfo&gt;
210
211Obtains all trusted devices synchronously.
212
213**System capability**: SystemCapability.DistributedHardware.DeviceManager
214
215- Return value
216  | Name                                    | Description       |
217  | -------------------------------------- | --------- |
218  | Array&lt;[DeviceInfo](#deviceinfo)&gt; | List of trusted devices obtained.|
219
220- Example
221  ```js
222  var deviceInfoList = dmInstance.getTrustedDeviceListSync();
223  ```
224
225
226### getTrustedDeviceList<sup>8+</sup>
227
228getTrustedDeviceList(callback:AsyncCallback&lt;Array&lt;DeviceInfo&gt;&gt;): void
229
230Obtains all trusted devices. This API uses an asynchronous callback to return the result.
231
232**System capability**: SystemCapability.DistributedHardware.DeviceManager
233
234- **Parameters**
235  | Name      | Type                                    | Mandatory  | Description                   |
236  | -------- | ---------------------------------------- | ---- | --------------------- |
237  | callback | AsyncCallback&lt;Array&lt;[DeviceInfo](#deviceinfo)&gt;&gt; | Yes   | Callback used to return the list of trusted devices.|
238
239- Example
240  ```js
241  dmInstance.getTrustedDeviceList((err, data) => {
242      console.log("getTrustedDeviceList err: " + JSON.stringify(err));
243      console.log('get trusted device info: ' + JSON.stringify(data));
244    }
245  );
246  ```
247
248### getTrustedDeviceList<sup>8+</sup>
249
250getTrustedDeviceList(): Promise&lt;Array&lt;DeviceInfo&gt;&gt;
251
252Obtains all trusted devices. This API uses a promise to return the result.
253
254**System capability**: SystemCapability.DistributedHardware.DeviceManager
255
256- Return value
257  | Type                                      | Description                   |
258  | ---------------------------------------- | --------------------- |
259  | Promise&lt;Array&lt;[DeviceInfo](#deviceinfo)&gt;&gt; | Promise used to return the list of trusted devices.|
260
261- Example
262  ```js
263  dmInstance.getTrustedDeviceList().then((data) => {
264      console.log('get trusted device info: ' + JSON.stringify(data));
265  }).catch((err) => {
266      console.log("getTrustedDeviceList err: " + JSON.stringify(err));
267  });
268  ```
269
270### getLocalDeviceInfoSync<sup>8+</sup>
271
272getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo)
273
274Obtains local device information synchronously.
275
276**System capability**: SystemCapability.DistributedHardware.DeviceManager
277
278- Return value
279  | Name                                    | Description       |
280  | -------------------------------------- | --------- |
281  | Array&lt;[DeviceInfo](#deviceinfo)&gt; | List of local devices obtained.|
282
283- Example
284  ```js
285  var deviceInfo = dmInstance.getLocalDeviceInfoSync();
286  ```
287
288
289### getLocalDeviceInfo<sup>8+</sup>
290
291getLocalDeviceInfo(callback:AsyncCallback&lt;DeviceInfo&gt;): void
292
293Obtains local device information. This API uses an asynchronous callback to return the result.
294
295**System capability**: SystemCapability.DistributedHardware.DeviceManager
296
297- **Parameters**
298  | Name      | Type                                    | Mandatory  | Description       |
299  | -------- | ---------------------------------------- | ---- | --------- |
300  | callback | AsyncCallback&lt;[DeviceInfo](#deviceinfo)&gt; | Yes   | Callback used to return the local device information.|
301
302- Example
303  ```js
304  dmInstance.getLocalDeviceInfo((err, data) => {
305      console.log("getLocalDeviceInfo err: " + JSON.stringify(err));
306      console.log('get local device info: ' + JSON.stringify(data));
307    }
308  );
309  ```
310
311### getLocalDeviceInfo<sup>8+</sup>
312
313getLocalDeviceInfo(): Promise&lt;DeviceInfo&gt;
314
315Obtains local device information. This API uses a promise to return the result.
316
317**System capability**: SystemCapability.DistributedHardware.DeviceManager
318
319- Return value
320  | Type                                      | Description                   |
321  | ---------------------------------------- | --------------------- |
322  | Promise&lt;[DeviceInfo](#deviceinfo)&gt; | Promise used to return the local device information.|
323
324- Example
325  ```js
326  dmInstance.getLocalDeviceInfo().then((data) => {
327      console.log('get local device info: ' + JSON.stringify(data));
328  }).catch((err) => {
329      console.log("getLocalDeviceInfo err: " + JSON.stringify(err));
330  });
331  ```
332
333### startDeviceDiscovery
334
335startDeviceDiscovery(subscribeInfo: SubscribeInfo): void
336
337Starts to discover peripheral devices.
338
339**System capability**: SystemCapability.DistributedHardware.DeviceManager
340
341- **Parameters**
342  | Name           | Type                           | Mandatory  | Description   |
343  | ------------- | ------------------------------- | ---- | ----- |
344  | subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes   | Subscription information.|
345
346- Example
347  ```js
348  // Automatically generate a unique subscription ID.
349  var subscribeId = Math.floor(Math.random() * 10000 + 1000);
350  var subscribeInfo = {
351      "subscribeId": subscribeId,
352      "mode": 0xAA, // Active discovery
353      "medium": 0, // Automatic. Multiple media can be used for device discovery.
354      "freq": 2, // High frequency
355      "isSameAccount": false,
356      "isWakeRemote": false,
357      "capability": 1
358  };
359  dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered.
360  ```
361
362### stopDeviceDiscovery
363
364stopDeviceDiscovery(subscribeId: number): void
365
366Stops device discovery.
367
368**System capability**: SystemCapability.DistributedHardware.DeviceManager
369
370- **Parameters**
371  | Name         | Type  | Mandatory  | Description   |
372  | ----------- | ------ | ---- | ----- |
373  | subscribeId | number | Yes   | Subscription ID.|
374
375- Example
376  ```js
377  // The subscribeId input must be the same as that automatically generated in startDeviceDiscovery.
378  dmInstance.stopDeviceDiscovery(subscribeId);
379  ```
380
381### authenticateDevice
382
383authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: AsyncCallback<{deviceId: string, pinToken ?: number}>): void
384
385Authenticates a device.
386
387**System capability**: SystemCapability.DistributedHardware.DeviceManager
388
389- **Parameters**
390  | Name        | Type                                    | Mandatory  | Description     |
391  | ---------- | ---------------------------------------- | ---- | ------- |
392  | deviceInfo | [DeviceInfo](#deviceinfo)                | Yes   | Device information.  |
393  | authParam  | [AuthParam](#authparam)                  | Yes   | Authentication parameter.  |
394  | callback   | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes   | Callback used to return the authentication result.|
395
396- Example
397  ```js
398  // Information about the device to authenticate. The information can be obtained from the device discovery result.
399  var deviceInfo ={
400      "deviceId": "XXXXXXXX",
401      "deviceName": "",
402      deviceType: 0x0E
403  };
404  let authParam = {
405      "authType": 1, // Authentication type. The value 1 means no account PIN authentication.
406      "extraInfo": {}
407  }
408  dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => {
409      if (err) {
410          console.info(TAG + "authenticateDevice err:" + JSON.stringify(err));
411          return;
412      }
413      console.info(TAG + "authenticateDevice result:" + JSON.stringify(data));
414      token = data.pinToken;
415  });
416  ```
417
418### unAuthenticateDevice<sup>8+</sup>
419
420unAuthenticateDevice(deviceInfo: DeviceInfo): void
421
422Deauthenticates a device.
423
424**System capability**: SystemCapability.DistributedHardware.DeviceManager
425
426- **Parameters**
427  | Name        | Type                     | Mandatory  | Description   |
428  | ---------- | ------------------------- | ---- | ----- |
429  | deviceInfo | [DeviceInfo](#deviceinfo) | Yes   | Device information.|
430
431- Example
432  ```js
433  dmInstance.unAuthenticateDevice(deviceInfo);
434  ```
435
436
437### verifyAuthInfo
438
439verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void
440
441Verifies authentication information.
442
443**System capability**: SystemCapability.DistributedHardware.DeviceManager
444
445- **Parameters**
446  | Name      | Type                                    | Mandatory  | Description     |
447  | -------- | ---------------------------------------- | ---- | ------- |
448  | authInfo | [AuthInfo](#authinfo)                    | Yes   | Authentication information.  |
449  | authInfo | AsyncCallback<{ deviceId: string, level: number }> | Yes   | Callback used to return the verification result.|
450
451- Example
452  ```js
453  let authInfo = {
454    "authType": 1,
455    "token": xxxxxx,
456    "extraInfo": {}
457  }
458  dmInstance.verifyAuthInfo(authInfo, (err, data) => {
459    if (err) {
460        console.info(TAG + "verifyAuthInfo err:" + JSON.stringify(err));
461        return;
462    }
463    console.info(TAG + "verifyAuthInfo result:" + JSON.stringify(data));
464  });
465  ```
466
467
468### on('deviceStateChange')
469
470on(type: 'deviceStateChange',  callback: Callback&lt;{ action: DeviceStateChangeAction, device: DeviceInfo }&gt;): void
471
472Subscribes to changes in the device state.
473
474**System capability**: SystemCapability.DistributedHardware.DeviceManager
475
476- **Parameters**
477  | Name      | Type                                    | Mandatory  | Description                            |
478  | -------- | ---------------------------------------- | ---- | ------------------------------ |
479  | type     | string                                   | Yes   | Event type. The value **'deviceStateChange'** indicates a device state change event.|
480  | callback | Callback&lt;{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }&gt; | Yes   | Callback invoked to return the device information and state.     |
481
482- Example
483  ```js
484  dmInstance.on('deviceStateChange', (data) => {
485        console.info("deviceStateChange on:" + JSON.stringify(data));
486      }
487  );
488  ```
489
490
491### off('deviceStateChange')
492
493off(type: 'deviceStateChange', callback?: Callback&lt;{ action: DeviceStateChangeAction, device: DeviceInfo }&gt;): void
494
495Unsubscribes from changes in the device state.
496
497**System capability**: SystemCapability.DistributedHardware.DeviceManager
498
499- **Parameters**
500  | Name      | Type                                    | Mandatory  | Description                         |
501  | -------- | ---------------------------------------- | ---- | --------------------------- |
502  | type     | string                                   | Yes   | Event type. The value **'deviceStateChange'** indicates a device state change event.       |
503  | callback | Callback&lt;{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }&gt; | Yes   | Callback invoked to return the device information and state.|
504
505- Example
506  ```js
507  dmInstance.off('deviceStateChange', (data) => {
508        console.info('deviceStateChange' + JSON.stringify(data));
509     }
510  );
511  ```
512
513
514### on('deviceFound')
515
516on(type: 'deviceFound', callback: Callback&lt;{ subscribeId: number, device: DeviceInfo }&gt;): void
517
518Subscribes to device discovery events.
519
520**System capability**: SystemCapability.DistributedHardware.DeviceManager
521
522- **Parameters**
523  | Name      | Type                                    | Mandatory  | Description                        |
524  | -------- | ---------------------------------------- | ---- | -------------------------- |
525  | type     | string                                   | Yes   | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.|
526  | callback | Callback&lt;{ subscribeId: number, device: DeviceInfo }&gt; | Yes   | Callback used for device discovery.              |
527
528- Example
529  ```js
530  dmInstance.on('deviceFound', (data) => {
531        console.info("deviceFound:" + JSON.stringify(data));
532      }
533  );
534  ```
535
536### off('deviceFound')
537
538off(type: 'deviceFound', callback?: Callback&lt;{ subscribeId: number, device: DeviceInfo }&gt;): void
539
540Unsubscribes from device discovery events.
541
542**System capability**: SystemCapability.DistributedHardware.DeviceManager
543
544- **Parameters**
545  | Name      | Type                                    | Mandatory  | Description                         |
546  | -------- | ---------------------------------------- | ---- | --------------------------- |
547  | type     | string                                   | Yes   | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.                |
548  | callback | Callback&lt;{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }&gt; | Yes   | Callback used for device discovery, which is invoked to return the device information and state.|
549
550- Example
551  ```js
552  dmInstance.off('deviceFound', (data) => {
553        console.info('deviceFound' + JSON.stringify(data));
554      }
555  );
556  ```
557
558### on('discoverFail')
559
560on(type: 'discoverFail', callback: Callback&lt;{ subscribeId: number, reason: number }&gt;): void
561
562Subscribes to device discovery failures.
563
564**System capability**: SystemCapability.DistributedHardware.DeviceManager
565
566- **Parameters**
567  | Name      | Type                                    | Mandatory  | Description                            |
568  | -------- | ---------------------------------------- | ---- | ------------------------------ |
569  | type     | string                                   | Yes   | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.|
570  | callback | Callback&lt;{ subscribeId: number, reason: number }&gt; | Yes   | Callback used for the device discovery failure.                |
571
572- Example
573  ```js
574  dmInstance.on('discoverFail', (data) => {
575        this.log("discoverFail on:" + JSON.stringify(data));
576      }
577  );
578  ```
579
580### off('discoverFail')
581
582off(type: 'discoverFail', callback?: Callback&lt;{ subscribeId: number, reason: number }&gt;): void
583
584Unsubscribes from device discovery failures.
585
586**System capability**: SystemCapability.DistributedHardware.DeviceManager
587
588- **Parameters**
589  | Name      | Type                                    | Mandatory  | Description               |
590  | -------- | ---------------------------------------- | ---- | ----------------- |
591  | type     | string                                   | Yes   | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.    |
592  | callback | Callback&lt;{ subscribeId: number, reason: number }&gt; | Yes   | Callback used for the device discovery failure.|
593
594- Example
595  ```js
596  dmInstance.off('deviceFound', (data) => {
597        console.info('deviceFound' + JSON.stringify(data));
598      }
599  );
600  ```
601
602
603### on('serviceDie')
604
605on(type: 'serviceDie', callback: () =&gt; void): void
606
607Subscribes to dead events of the **DeviceManager** service.
608
609**System capability**: SystemCapability.DistributedHardware.DeviceManager
610
611- **Parameters**
612  | Name      | Type                   | Mandatory  | Description                                      |
613  | -------- | ----------------------- | ---- | ---------------------------------------- |
614  | type     | string                  | Yes   | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.|
615  | callback | () =&gt; void | Yes   | Callback invoked when a dead event of the **DeviceManager** service occurs.                      |
616
617- Example
618  ```js
619  dmInstance.on("serviceDie", () => {
620        console.info("serviceDie on");
621     }
622  );
623  ```
624
625
626### off('serviceDie')
627
628off(type: 'serviceDie', callback?: () =&gt; void): void
629
630Unsubscribes from dead events of the **DeviceManager** service.
631
632**System capability**: SystemCapability.DistributedHardware.DeviceManager
633
634- **Parameters**
635  | Name      | Type                   | Mandatory  | Description                                      |
636  | -------- | ----------------------- | ---- | ---------------------------------------- |
637  | type     | string                  | Yes   | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.|
638  | callback | () =&gt; void | No   | Callback used to return the dead event of the **DeviceManager** service.                    |
639
640- Example
641  ```js
642  dmInstance.off("serviceDie", () => {
643        console.info("serviceDie off");
644    }
645  );
646  ```
647