source
stringlengths
14
113
code
stringlengths
10
21.3k
application-dev\basic-services\usb\usbManager\usbHost\isochronousTransfer.md
// Register a communication interface. If the registration is successful, 0 is returned; otherwise, other error codes are returned. let claimInterfaceResult: number = usbManager.claimInterface(devicePipe, usbInterface, true); if (claimInterfaceResult !== 0) { console.error(`claimInterface error = ${claimInterfaceResult}`) return; } // When the transfer is of the isochronous type, you need to register a device interface. If the registration is successful, 0 is returned; otherwise, other error codes are returned. if (this.type === usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS) { let setInterfaceResult = usbManager.setInterface(devicePipe, usbInterface); if (setInterfaceResult !== 0) { console.error(`setInterfaceResult error = ${setInterfaceResult}`) return; } }
application-dev\basic-services\usb\usbManager\usbHost\isochronousTransfer.md
try { // The communication interface is successfully registered and performs data transfer. let transferParams: usbManager.UsbDataTransferParams = { devPipe: devicePipe, flags: usbManager.UsbTransferFlags.USB_TRANSFER_SHORT_NOT_OK, endpoint: usbEndprint.address, type: usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS, timeout: 2000, length: 10, callback: () => {}, userData: new Uint8Array(10), buffer: new Uint8Array(10), isoPacketCount: 2, }; transferParams.callback = (err: Error, callBackData: usbManager.SubmitTransferCallback) => { console.info(`callBackData = ${callBackData}`); console.info('transfer success, result = ' + transferParams.buffer.toString()); } usbManager.usbSubmitTransfer(transferParams); console.info('USB transfer request submitted.'); } catch (error) { console.error(`USB transfer failed: ${error}`); }
application-dev\basic-services\usb\usbManager\usbHost\isochronousTransfer.md
usbManager.usbCancelTransfer(transferParams); usbManager.releaseInterface(devicePipe, usbInterface); usbManager.closePipe(devicePipe);
application-dev\basic-services\usb\usbSerial\usbSerial-communication.md
// Import the usbManager module. import serial from '@ohos.usbManager.serial'; import { buffer } from '@kit.ArkTS';
application-dev\basic-services\usb\usbSerial\usbSerial-communication.md
// Obtain the list of USB devices connected to the host. let portList: serial.SerialPort[] = serial.getPortList(); console.info(`usbSerial portList: ${portList}`); if (portList === undefined || portList.length === 0) { console.error('usbSerial portList is empty'); return; }
application-dev\basic-services\usb\usbSerial\usbSerial-communication.md
// Check whether the first USB device in the list has the access permission. let portId: number = portList[0].portId; if (!serial.hasSerialRight(portId)) { await serial.requestSerialRight(portId).then(result => { if(!result) { // If the device does not have the access permission and is not granted by the user, the device exits. console.error('The user does not have permission to perform this operation'); return; } }); }
application-dev\basic-services\usb\usbSerial\usbSerial-communication.md
try { serial.open(portId) console.info(`open usbSerial success, portId: ${portId}`); } catch (error) { console.error(`open usbSerial error: ${error}`); }
application-dev\basic-services\usb\usbSerial\usbSerial-communication.md
// Read data asynchronously. let readBuffer: Uint8Array = new Uint8Array(64); serial.read(portId, readBuffer, 2000).then((size: number) => { console.info(`read usbSerial success, readBuffer: ${readBuffer}`); }).catch((error: Error) => { console.error(`read usbSerial error: ${error}`); }) // Read data synchronously. let readSyncBuffer: Uint8Array = new Uint8Array(64); try { serial.readSync(portId, readSyncBuffer, 2000); console.info(`readSync usbSerial success, readSyncBuffer: ${readSyncBuffer}`); } catch (error) { console.error(`readSync usbSerial error: ${error}`); }
application-dev\basic-services\usb\usbSerial\usbSerial-communication.md
// Write data asynchronously. let writeBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer) serial.write(portId, writeBuffer, 2000).then((size: number) => { console.info(`write usbSerial success, writeBuffer: ${writeBuffer}`); }).catch((error: Error) => { console.error(`write usbSerial error: ${error}`); }) // Write data synchronously. let writeSyncBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer) try { serial.writeSync(portId, writeSyncBuffer, 2000); console.info(`writeSync usbSerial success, writeSyncBuffer: ${writeSyncBuffer}`); } catch (error) { console.error(`writeSync usbSerial error: ${error}`); }
application-dev\basic-services\usb\usbSerial\usbSerial-communication.md
try { serial.close(portId); console.info(`close usbSerial success, portId: ${portId}`); } catch (error) { console.error(`close usbSerial error: ${error}`); }
application-dev\basic-services\usb\usbSerial\usbSerial-configuration.md
// Import the usbManager module. import serial from '@ohos.usbManager.serial';
application-dev\basic-services\usb\usbSerial\usbSerial-configuration.md
// Obtain the list of USB devices connected to the host. let portList: serial.SerialPort[] = serial.getPortList(); console.info(`usbSerial portList: ${portList}`); if (portList === undefined || portList.length === 0) { console.error('usbSerial portList is empty'); return; }
application-dev\basic-services\usb\usbSerial\usbSerial-configuration.md
// Check whether the first USB device in the list has the access permission. let portId: number = portList[0].portId; if (!serial.hasSerialRight(portId)) { await serial.requestSerialRight(portId).then(result => { if(!result) { // If the device does not have the access permission and is not granted by the user, the device exits. console.error('The user does not have permission to perform this operation'); return; } }); }
application-dev\basic-services\usb\usbSerial\usbSerial-configuration.md
try { serial.open(portId) console.info(`open usbSerial success, portId: ${portId}`); } catch (error) { console.error(`open usbSerial error: ${error}`); }
application-dev\basic-services\usb\usbSerial\usbSerial-configuration.md
// Obtain the serial port configuration. try { let attribute: serial.SerialAttribute = serial.getAttribute(portId); if (attribute === undefined) { console.error('getAttribute usbSerial error, attribute is undefined'); } else { console.info(`getAttribute usbSerial success, attribute: ${attribute}`); } } catch (error) { console.error(`getAttribute usbSerial error: ${error}`); } // Set the serial port configuration. try { let attribute: serial.SerialAttribute = { baudRate: serial.BaudRates.BAUDRATE_9600, dataBits: serial.DataBits.DATABIT_8, parity: serial.Parity.PARITY_NONE, stopBits: serial.StopBits.STOPBIT_1 } serial.setAttribute(portId, attribute); console.info(`setAttribute usbSerial success, attribute: ${attribute}`); } catch (error) { console.error(`setAttribute usbSerial error: ${error}`); }
application-dev\calendarmanager\calendarmanager-calendar-developer.md
// EntryAbility.ets import { abilityAccessCtrl, AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { calendarManager } from '@kit.CalendarKit'; import { window } from '@kit.ArkUI';
application-dev\calendarmanager\calendarmanager-calendar-developer.md
// EntryAbility.ets export let calendarMgr: calendarManager.CalendarManager | null = null; export let mContext: common.UIAbilityContext | null = null; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { console.info("Ability onCreate"); } onDestroy(): void { console.info("Ability onDestroy"); } onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created, set main page for this ability console.info("Ability onWindowStageCreate"); windowStage.loadContent('pages/Index', (err, data) => { if (err.code) { console.error(`Failed to load the content. Code: ${err.code}, message: ${err.message}`); return; } console.info(`Succeeded in loading the content. Data: ${JSON.stringify(data)}`); }); mContext = this.context; const permissions: Permissions[] = ['ohos.permission.READ_CALENDAR', 'ohos.permission.WRITE_CALENDAR']; let atManager = abilityAccessCtrl.createAtManager(); atManager.requestPermissionsFromUser(mContext, permissions).then((result: PermissionRequestResult) => { console.info(`get Permission success, result: ${JSON.stringify(result)}`); calendarMgr = calendarManager.getCalendarManager(mContext); }).catch((error: BusinessError) => { console.error(`get Permission error, error. Code: ${error.code}, message: ${error.message}`); }) } onWindowStageDestroy(): void { // Main window is destroyed, release UI related resources console.info("Ability onWindowStageDestroy"); } onForeground(): void { // Ability has brought to foreground console.info("Ability onForeground"); } onBackground(): void { // Ability has back to background console.info("Ability onBackground"); } }
application-dev\calendarmanager\calendarmanager-calendar-developer.md
// Index.ets import { BusinessError } from '@kit.BasicServicesKit'; import { calendarMgr } from '../entryability/EntryAbility'; import { calendarManager } from '@kit.CalendarKit'; let calendar: calendarManager.Calendar | undefined = undefined; // Specify the calendar account information. const calendarAccount: calendarManager.CalendarAccount = { // Calendar name. name: 'MyCalendar', // Calendar type. type: calendarManager.CalendarType.LOCAL, // Display name of the calendar. If this field is left blank, the created calendar is displayed as an empty string on the UI. displayName: 'MyCalendar' }; // Create a calendar. calendarMgr?.createCalendar(calendarAccount).then((data: calendarManager.Calendar) => { console.info(`Succeeded in creating calendar data->${JSON.stringify(data)}`); calendar = data; // Ensure that the calendar account is created before performing subsequent operations. // ... }).catch((error: BusinessError) => { console.error(`Failed to create calendar. Code: ${error.code}, message: ${error.message}`); });
application-dev\calendarmanager\calendarmanager-calendar-developer.md
// Index.ets // Calendar configuration information. const config: calendarManager.CalendarConfig = { // Enable the event reminder. enableReminder: true, // Set the calendar color. color: '#aabbcc' }; // Set the calendar configuration information. calendar.setConfig(config).then(() => { console.info(`Succeeded in setting config, data->${JSON.stringify(config)}`); }).catch((err: BusinessError) => { console.error(`Failed to set config. Code: ${err.code}, message: ${err.message}`); });
application-dev\calendarmanager\calendarmanager-calendar-developer.md
// Index.ets calendarMgr?.getCalendar(calendarAccount).then((data: calendarManager.Calendar) => { console.info(`Succeeded in getting calendar, data -> ${JSON.stringify(data)}`); }).catch((err: BusinessError) => { console.error(`Failed to get calendar. Code: ${err.code}, message: ${err.message}`); });
application-dev\calendarmanager\calendarmanager-calendar-developer.md
// Index.ets calendarMgr?.getCalendar().then((data: calendarManager.Calendar) => { console.info(`Succeeded in getting calendar, data -> ${JSON.stringify(data)}`); }).catch((err: BusinessError) => { console.error(`Failed to get calendar. Code: ${err.code}, message: ${err.message}`); });
application-dev\calendarmanager\calendarmanager-calendar-developer.md
// Index.ets calendarMgr?.getAllCalendars().then((data: calendarManager.Calendar[]) => { console.info(`Succeeded in getting all calendars, data -> ${JSON.stringify(data)}`); data.forEach((calendar) => { const account = calendar.getAccount(); console.info(`account -> ${JSON.stringify(account)}`); }) }).catch((err: BusinessError) => { console.error(`Failed to get all calendars. Code: ${err.code}, message: ${err.message}`); });
application-dev\calendarmanager\calendarmanager-calendar-developer.md
// Index.ets calendarMgr?.deleteCalendar(calendar).then(() => { console.info("Succeeded in deleting calendar"); }).catch((err: BusinessError) => { console.error(`Failed to delete calendar. Code: ${err.code}, message: ${err.message}`); });
application-dev\calendarmanager\calendarmanager-event-developer.md
// entry/src/main/ets/entryability/EntryAbility.ets import { abilityAccessCtrl, AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { calendarManager } from '@kit.CalendarKit'; import { window } from '@kit.ArkUI';
application-dev\calendarmanager\calendarmanager-event-developer.md
// entry/src/main/ets/entryability/EntryAbility.ets export let calendarMgr: calendarManager.CalendarManager | null = null; export let mContext: common.UIAbilityContext | null = null; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { console.info("Ability onCreate"); } onDestroy(): void { console.info("Ability onDestroy"); } onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created, set main page for this ability console.info("Ability onWindowStageCreate"); windowStage.loadContent('pages/Index', (err, data) => { if (err.code) { console.error(`Failed to load the content. Code: ${err.code}, message: ${err.message}`); return; } console.info(`Succeeded in loading the content. Data: ${JSON.stringify(data)}`); }); mContext = this.context; const permissions: Permissions[] = ['ohos.permission.READ_CALENDAR', 'ohos.permission.WRITE_CALENDAR']; let atManager = abilityAccessCtrl.createAtManager(); atManager.requestPermissionsFromUser(mContext, permissions).then((result: PermissionRequestResult) => { console.info(`get Permission success, result: ${JSON.stringify(result)}`); calendarMgr = calendarManager.getCalendarManager(mContext); }).catch((error: BusinessError) => { console.error(`get Permission error, error. Code: ${error.code}, message: ${error.message}`); }) } onWindowStageDestroy(): void { // Main window is destroyed, release UI related resources console.info("Ability onWindowStageDestroy"); } onForeground(): void { // Ability has brought to foreground console.info("Ability onForeground"); } onBackground(): void { // Ability has back to background console.info("Ability onBackground"); } }
application-dev\calendarmanager\calendarmanager-event-developer.md
// Index.ets import { BusinessError } from '@kit.BasicServicesKit'; import { calendarMgr } from '../entryability/EntryAbility'; import { calendarManager } from '@kit.CalendarKit'; let calendar: calendarManager.Calendar | undefined = undefined; // Specify the calendar account information. const calendarAccount: calendarManager.CalendarAccount = { name: 'MyCalendar', type: calendarManager.CalendarType.LOCAL, // Display name of the calendar. If this field is left blank, the created calendar is displayed as an empty string on the UI. displayName: 'MyCalendar' }; // Calendar configuration information. const config: calendarManager.CalendarConfig = { // Enable the event reminder. enableReminder: true, // Set the calendar color. color: '#aabbcc' }; // Create a calendar. calendarMgr?.createCalendar(calendarAccount).then((data: calendarManager.Calendar) => { console.info(`Succeeded in creating calendar data->${JSON.stringify(data)}`); calendar = data; // Ensure that the calendar is successfully created before managing related events. // Set the calendar configuration information, including event reminder and calendar color. calendar.setConfig(config).then(() => { console.info(`Succeeded in setting config, data->${JSON.stringify(config)}`); }).catch((err: BusinessError) => { console.error(`Failed to set config. Code: ${err.code}, message: ${err.message}`); }); // ... }).catch((error: BusinessError) => { console.error(`Failed to create calendar. Code: ${error.code}, message: ${error.message}`); });
application-dev\calendarmanager\calendarmanager-event-developer.md
// Index.ets let eventId : number | undefined = undefined; const date = new Date(); const event: calendarManager.Event = { // Event title. title: 'title', // Event type. Third-party developers are not advised to use calendarManager.EventType.IMPORTANT. Important events do not support quick service redirection and custom reminder time. type: calendarManager.EventType.NORMAL, // Start time of the event. startTime: date.getTime(), // End time of the event. endTime: date.getTime() + 60 * 60 * 1000, // A 10-minute-countdown reminder before the start time. reminderTime: [10], // Event recurrence rule. Mandatory if the event is a periodic one; otherwise, optional. recurrenceRule: { // Event recurrence frequency, which can be daily, weekly, monthly, or yearly. recurrenceFrequency: calendarManager.RecurrenceFrequency.DAILY, // Number of event recurrence times. Either count or expire needs to be set. If both attributes are set, the value of the count attribute is used. count: 100, // Interval for event recurrence, which is related to recurrenceFrequency. This example indicates that the event is repeated every two days. interval: 2, // Event expiration time. Either count or expire needs to be set. If both attributes are set, the value of the count attribute is used. expire: date.getTime() + 60 * 60 * 1000 * 3, // Excluded date. If set, the specified date is excluded from the repeated event. excludedDates: [date.getTime() + 60 * 60 * 1000 * 2] }, // Event service (optional). Set this attribute for the event that requires the one-click service. service: { // Service type, for example, TRIP, MEETING, or WATCHING. type: calendarManager.ServiceType.TRIP, // Service URI, in the DeepLink format, which supports redirection to a specific page of a third-party application. To use the DeepLink mode, you need to register your application with the Huawei HAG Cloud with the registration information including the application bundle name and application service type. // DeepLink includes scheme, host, path, and parameters (excluding values). uri: 'xxx://xxx.xxx.com/xxx', // Service auxiliary description (optional). description: 'One-click service' } }; // Method 1 calendar.addEvent(event).then((data: number) => { console.info(`Succeeded in adding event, id -> ${data}`); eventId = data; }).catch((err: BusinessError) => { console.error(`Failed to addEvent. Code: ${err.code}, message: ${err.message}`); }); // Method 2 const eventInfo: calendarManager.Event = { // Event title. title: 'title', // Event type. type: calendarManager.EventType.NORMAL, // Start time of the event. startTime: date.getTime(), // End time of the event. endTime: date.getTime() + 60 * 60 * 1000 }; calendarMgr?.editEvent(eventInfo).then((id: number): void => { console.info(`create Event id = ${id}`); eventId = id; }).catch((err: BusinessError) => { console.error(`Failed to create Event. Code: ${err.code}, message: ${err.message}`); });
application-dev\calendarmanager\calendarmanager-event-developer.md
// Index.ets const updateEvent: calendarManager.Event = { title: 'updateTitle', description: 'updateEventTest', type: calendarManager.EventType.NORMAL, id: eventId, startTime: date.getTime(), endTime: date.getTime() + 60 * 60 * 1000 }; calendar.updateEvent(updateEvent).then(() => { console.info(`Succeeded in updating event`); }).catch((err: BusinessError) => { console.error(`Failed to update event. Code: ${err.code}, message: ${err.message}`); });
application-dev\calendarmanager\calendarmanager-event-developer.md
calendar.getEvents().then((data: calendarManager.Event[]) => { console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`); }).catch((err: BusinessError) => { console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`); });
application-dev\calendarmanager\calendarmanager-event-developer.md
// Query by the event ID. const filterId = calendarManager.EventFilter.filterById([eventId]); calendar.getEvents(filterId).then((data: calendarManager.Event[]) => { console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`); }).catch((err: BusinessError) => { console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`); }); // Query by the event title. const filterTitle = calendarManager.EventFilter.filterByTitle('update'); calendar.getEvents(filterTitle).then((data: calendarManager.Event[]) => { console.info(`Succeeded in getting events, data -> ${JSON.stringify(data)}`); }).catch((err: BusinessError) => { console.error(`Failed to get events. Code: ${err.code}, message: ${err.message}`); }); // Query by the start time and end time. const filterTime = calendarManager.EventFilter.filterByTime(1686931200000, 1687017600000); calendar.getEvents(filterTime).then((data: calendarManager.Event[]) => { console.info(`Succeeded in getting events filter by time, data -> ${JSON.stringify(data)}`); }).catch((err: BusinessError) => { console.error(`Failed to filter by time. Code: ${err.code}, message: ${err.message}`); });
application-dev\calendarmanager\calendarmanager-event-developer.md
// Index.ets calendar.deleteEvent(eventId).then(() => { console.info("Succeeded in deleting event"); }).catch((err: BusinessError) => { console.error(`Failed to delete event. Code: ${err.code}, message: ${err.message}`); });
application-dev\connectivity\bluetooth\ble-development-guide.md
import { ble } from '@kit.ConnectivityKit'; import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; const TAG: string = 'BleAdvertisingManager'; export class BleAdvertisingManager { private advHandle: number = 0xFF; // default invalid value // 1. Subscribe to BLE advertising state changes. public onAdvertisingStateChange() { try { ble.on('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => { console.info(TAG, 'bluetooth advertising state = ' + JSON.stringify(data)); AppStorage.setOrCreate('advertiserState', data.state); }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 2. Start BLE advertising the first time. public async startAdvertising() { // 2.1 Set BLE advertising parameters. let setting: ble.AdvertiseSetting = { interval: 160, txPower: 0, connectable: true }; // 2.2 Construct the data to be advertised. let manufactureValueBuffer = new Uint8Array(4); manufactureValueBuffer[0] = 1; manufactureValueBuffer[1] = 2; manufactureValueBuffer[2] = 3; manufactureValueBuffer[3] = 4; let serviceValueBuffer = new Uint8Array(4); serviceValueBuffer[0] = 5; serviceValueBuffer[1] = 6; serviceValueBuffer[2] = 7; serviceValueBuffer[3] = 8; let manufactureDataUnit: ble.ManufactureData = { manufactureId: 4567, manufactureValue: manufactureValueBuffer.buffer }; let serviceDataUnit: ble.ServiceData = { serviceUuid: "00001888-0000-1000-8000-00805f9b34fb", serviceValue: serviceValueBuffer.buffer }; let advData: ble.AdvertiseData = { serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"], manufactureData: [manufactureDataUnit], serviceData: [serviceDataUnit], includeDeviceName: false // Whether the device name is carried. This parameter is optional. Note that the length of an advertising packet including the device name cannot exceed 31 bytes. }; let advResponse: ble.AdvertiseData = { serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"], manufactureData: [manufactureDataUnit], serviceData: [serviceDataUnit] }; // 2.3 Construct AdvertisingParams for starting the BLE advertising. let advertisingParams: ble.AdvertisingParams = { advertisingSettings: setting, advertisingData: advData, advertisingResponse: advResponse, duration: 0 // This parameter is optional. If the value is greater than 0, the advertising stops temporarily after a period of time. You can restart it as required. } // 2.4 Start BLE advertising the first time. The ID of the BLE advertising is returned. try { this.onAdvertisingStateChange(); this.advHandle = await ble.startAdvertising(advertisingParams); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 4. Disable the BLE advertising temporarily. The advertising resources still exist. public async disableAdvertising() { // 4.1 Construct parameters for temporarily disabling the BLE advertising. let advertisingDisableParams: ble.AdvertisingDisableParams = { advertisingId: this.advHandle // Use the ID of the first BLE advertising. } // 4.2 Disable the BLE advertising temporarily. try { await ble.disableAdvertising(advertisingDisableParams); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 5. Enable the BLE advertising again. public async enableAdvertising(enableDuration: number) { // 5.1 Construct the parameters for temporarily enabling the advertising. let advertisingEnableParams: ble.AdvertisingEnableParams = { advertisingId: this.advHandle // Use the ID of the first BLE advertising. duration: enableDuration } // 5.2 Enable BLE advertising again. try { await ble.enableAdvertising(advertisingEnableParams); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 6. Stop BLE advertising and release related resources. public async stopAdvertising() { try { await ble.stopAdvertising(this.advHandle); ble.off('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => { console.info(TAG, 'bluetooth advertising state = ' + JSON.stringify(data)); }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } } let bleAdvertisingManager = new BleAdvertisingManager(); export default bleAdvertisingManager as BleAdvertisingManager;
application-dev\connectivity\bluetooth\ble-development-guide.md
import { ble } from '@kit.ConnectivityKit'; import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; const TAG: string = 'BleScanManager'; const BLE_ADV_TYPE_FLAG = 0x01; const BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_INCOMPLETE = 0x02; const BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_COMPLETE = 0x03; const BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_INCOMPLETE = 0x04; const BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_COMPLETE = 0x05; const BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_INCOMPLETE = 0x06; const BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_COMPLETE = 0x07; const BLE_ADV_TYPE_LOCAL_NAME_SHORT = 0x08; const BLE_ADV_TYPE_LOCAL_NAME_COMPLETE = 0x09; const BLE_ADV_TYPE_TX_POWER_LEVEL = 0x0A; const BLE_ADV_TYPE_16_BIT_SERVICE_SOLICITATION_UUIDS = 0x14; const BLE_ADV_TYPE_128_BIT_SERVICE_SOLICITATION_UUIDS = 0x15; const BLE_ADV_TYPE_32_BIT_SERVICE_SOLICITATION_UUIDS = 0x1F; const BLE_ADV_TYPE_16_BIT_SERVICE_DATA = 0x16; const BLE_ADV_TYPE_32_BIT_SERVICE_DATA = 0x20; const BLE_ADV_TYPE_128_BIT_SERVICE_DATA = 0x21; const BLE_ADV_TYPE_MANUFACTURER_SPECIFIC_DATA = 0xFF; const BLUETOOTH_UUID_16_BIT_LENGTH = 2; const BLUETOOTH_UUID_32_BIT_LENGTH = 4; const BLUETOOTH_UUID_128_BIT_LENGTH = 16; const BLUETOOTH_MANUFACTURE_ID_LENGTH = 2; export class BleScanManager { // 1. Subscribe to the scanning result. public onScanResult() { ble.on('BLEDeviceFind', (data: Array<ble.ScanResult>) => { if (data.length > 0) { console.info(TAG, 'BLE scan result = ' + data[0].deviceId); this.parseScanResult(data[0].data); } }); } private parseScanResult(data: ArrayBuffer) { let advData = new Uint8Array(data); if (advData.byteLength == 0) { console.warn(TAG, 'nothing, adv data length is 0'); return; } console.info(TAG, 'advData: ' + JSON.stringify(advData)); let advFlags: number = -1; let txPowerLevel: number = -1; let localName: string = ""; let serviceUuids: string[] = []; let serviceSolicitationUuids: string[] = []; let serviceDatas: Record<string, Uint8Array> = {}; let manufactureSpecificDatas: Record<number, Uint8Array> = {}; let curPos = 0; while (curPos < advData.byteLength) { let length = advData[curPos++]; if (length == 0) { break; } let advDataLength = length - 1; let advDataType = advData[curPos++]; switch (advDataType) { case BLE_ADV_TYPE_FLAG: advFlags = advData[curPos]; break; case BLE_ADV_TYPE_LOCAL_NAME_SHORT: case BLE_ADV_TYPE_LOCAL_NAME_COMPLETE: localName = advData.slice(curPos, curPos + advDataLength).toString(); break; case BLE_ADV_TYPE_TX_POWER_LEVEL: txPowerLevel = advData[curPos]; break; case BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_INCOMPLETE: case BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_COMPLETE: this.parseServiceUuid(BLUETOOTH_UUID_16_BIT_LENGTH, curPos, advDataLength, advData, serviceUuids); break; case BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_INCOMPLETE: case BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_COMPLETE: this.parseServiceUuid(BLUETOOTH_UUID_32_BIT_LENGTH, curPos, advDataLength, advData, serviceUuids); break; case BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_INCOMPLETE: case BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_COMPLETE: this.parseServiceUuid(BLUETOOTH_UUID_128_BIT_LENGTH, curPos, advDataLength, advData, serviceUuids); break; case BLE_ADV_TYPE_16_BIT_SERVICE_SOLICITATION_UUIDS: this.parseServiceSolicitationUuid(BLUETOOTH_UUID_16_BIT_LENGTH, curPos, advDataLength, advData, serviceSolicitationUuids); break; case BLE_ADV_TYPE_32_BIT_SERVICE_SOLICITATION_UUIDS: this.parseServiceSolicitationUuid(BLUETOOTH_UUID_32_BIT_LENGTH, curPos, advDataLength, advData, serviceSolicitationUuids); break; case BLE_ADV_TYPE_128_BIT_SERVICE_SOLICITATION_UUIDS: this.parseServiceSolicitationUuid(BLUETOOTH_UUID_128_BIT_LENGTH, curPos, advDataLength, advData, serviceSolicitationUuids); break; case BLE_ADV_TYPE_16_BIT_SERVICE_DATA: this.parseServiceData(BLUETOOTH_UUID_16_BIT_LENGTH, curPos, advDataLength, advData, serviceDatas); break; case BLE_ADV_TYPE_32_BIT_SERVICE_DATA: this.parseServiceData(BLUETOOTH_UUID_32_BIT_LENGTH, curPos, advDataLength, advData, serviceDatas); break; case BLE_ADV_TYPE_128_BIT_SERVICE_DATA: this.parseServiceData(BLUETOOTH_UUID_128_BIT_LENGTH, curPos, advDataLength, advData, serviceDatas); break; case BLE_ADV_TYPE_MANUFACTURER_SPECIFIC_DATA: this.parseManufactureData(curPos, advDataLength, advData, manufactureSpecificDatas); break; default: break; } curPos += advDataLength; } } private parseServiceUuid(uuidLength: number, curPos: number, advDataLength: number, advData: Uint8Array, serviceUuids: string[]) { while (advDataLength > 0) { let tmpData: Uint8Array = advData.slice(curPos, curPos + uuidLength); serviceUuids.push(this.getUuidFromUint8Array(uuidLength, tmpData)); advDataLength -= uuidLength; curPos += uuidLength; } } private parseServiceSolicitationUuid(uuidLength: number, curPos: number, advDataLength: number, advData: Uint8Array, serviceSolicitationUuids: string[]) { while (advDataLength > 0) { let tmpData: Uint8Array = advData.slice(curPos, curPos + uuidLength); serviceSolicitationUuids.push(this.getUuidFromUint8Array(uuidLength, tmpData)); advDataLength -= uuidLength; curPos += uuidLength; } } private getUuidFromUint8Array(uuidLength: number, uuidData: Uint8Array): string { let uuid = ""; let temp: string = ""; for (let i = uuidLength - 1; i > -1; i--) { temp += uuidData[i].toString(16).padStart(2, "0"); } switch (uuidLength) { case BLUETOOTH_UUID_16_BIT_LENGTH: uuid = `0000${temp}-0000-1000-8000-00805F9B34FB`; break; case BLUETOOTH_UUID_32_BIT_LENGTH: uuid = `${temp}-0000-1000-8000-00805F9B34FB`; break; case BLUETOOTH_UUID_128_BIT_LENGTH: uuid = `${temp.substring(0, 8)}-${temp.substring(8, 12)}-${temp.substring(12, 16)}-${temp.substring(16, 20)}-${temp.substring(20, 32)}`; break; default: break; } return uuid; } private parseServiceData(uuidLength: number, curPos: number, advDataLength: number, advData: Uint8Array, serviceDatas: Record<string, Uint8Array>) { let tmpUuid: Uint8Array = advData.slice(curPos, curPos + uuidLength); let tmpValue: Uint8Array = advData.slice(curPos + uuidLength, curPos + advDataLength); serviceDatas[tmpUuid.toString()] = tmpValue; } private parseManufactureData(curPos: number, advDataLength: number, advData: Uint8Array, manufactureSpecificDatas: Record<number, Uint8Array>) { let manufactureId: number = (advData[curPos + 1] << 8) + advData[curPos]; let tmpValue: Uint8Array = advData.slice(curPos + BLUETOOTH_MANUFACTURE_ID_LENGTH, curPos + advDataLength); manufactureSpecificDatas[manufactureId] = tmpValue; } // 2. Start scanning. public startScan() { // 2.1 Construct a scan filter that matches the expected advertising packet content. let manufactureId = 4567; let manufactureData: Uint8Array = new Uint8Array([1, 2, 3, 4]); let manufactureDataMask: Uint8Array = new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF]); let scanFilter: ble.ScanFilter = {// Define the filter based on service requirements. manufactureId: manufactureId, manufactureData: manufactureData.buffer, manufactureDataMask: manufactureDataMask.buffer }; // 2.2 Construct scanning parameters. let scanOptions: ble.ScanOptions = { interval: 0, dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER, matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE } try { this.onScanResult(); // Subscribe to the scanning result. ble.startBLEScan([scanFilter], scanOptions); console.info(TAG, 'startBleScan success'); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 3. Stop scanning. public stopScan() { try { ble.off('BLEDeviceFind', (data: Array<ble.ScanResult>) => { // Unsubscribe from the scanning result. console.info(TAG, 'off success'); }); ble.stopBLEScan(); console.info(TAG, 'stopBleScan success'); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } } let bleScanManager = new BleScanManager(); export default bleScanManager as BleScanManager;
application-dev\connectivity\bluetooth\br-development-guide.md
import { access } from '@kit.ConnectivityKit'; import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; // Enable Bluetooth. access.enableBluetooth(); access.on('stateChange', (data) => { let btStateMessage = ''; switch (data) { case 0: btStateMessage += 'STATE_OFF'; break; case 1: btStateMessage += 'STATE_TURNING_ON'; break; case 2: btStateMessage += 'STATE_ON'; break; case 3: btStateMessage += 'STATE_TURNING_OFF'; break; case 4: btStateMessage += 'STATE_BLE_TURNING_ON'; break; case 5: btStateMessage += 'STATE_BLE_ON'; break; case 6: btStateMessage += 'STATE_BLE_TURNING_OFF'; break; default: btStateMessage += 'unknown status'; break; } if (btStateMessage == 'STATE_ON') { access.off('stateChange'); } console.info('bluetooth statues: ' + btStateMessage); }) // Disable Bluetooth. access.disableBluetooth(); access.on('stateChange', (data) => { let btStateMessage = ''; switch (data) { case 0: btStateMessage += 'STATE_OFF'; break; case 1: btStateMessage += 'STATE_TURNING_ON'; break; case 2: btStateMessage += 'STATE_ON'; break; case 3: btStateMessage += 'STATE_TURNING_OFF'; break; case 4: btStateMessage += 'STATE_BLE_TURNING_ON'; break; case 5: btStateMessage += 'STATE_BLE_ON'; break; case 6: btStateMessage += 'STATE_BLE_TURNING_OFF'; break; default: btStateMessage += 'unknown status'; break; } if (btStateMessage == 'STATE_OFF') { access.off('stateChange'); } console.info("bluetooth statues: " + btStateMessage); })
application-dev\connectivity\bluetooth\br-discovery-development-guide.md
import { connection } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit';
application-dev\connectivity\bluetooth\br-discovery-development-guide.md
// Define the callback for scan result reporting events. function onReceiveEvent(data: Array<connection.DiscoveryResult>) { console.info('bluetooth device: '+ JSON.stringify(data)); } try { // Subscribe to scan result reporting events. connection.on('discoveryResult', onReceiveEvent); } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); }
application-dev\connectivity\bluetooth\br-discovery-development-guide.md
// Define the callback for scan result reporting events. function onReceiveEvent(data: Array<string>) { console.info('bluetooth device: '+ JSON.stringify(data)); } try { // Subscribe to scan result reporting events. connection.on('bluetoothDeviceFind', onReceiveEvent); } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); }
application-dev\connectivity\bluetooth\br-discovery-development-guide.md
try { // Check whether scanning is in progress on the local device. let scan = connection.isBluetoothDiscovering(); if (!scan) { // Start scanning for devices if a scan is not in progress. connection.startBluetoothDiscovery(); } } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); }
application-dev\connectivity\bluetooth\br-discovery-development-guide.md
// Define the callback for scan result reporting events. function onReceiveEvent(data: Array<string>) { console.info('bluetooth device: '+ JSON.stringify(data)); } try { // Check whether scanning is in progress on the local device. let scan = connection.isBluetoothDiscovering(); if (scan) { // Stop scanning for devices if a scan is in progress. connection.stopBluetoothDiscovery(); } // If scanning is no longer needed, unsubscribe from scan result reporting events. connection.off('bluetoothDeviceFind', onReceiveEvent); } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); }
application-dev\connectivity\bluetooth\br-discovery-development-guide.md
try { // Obtain the current scan mode of the local device. let scanMode: connection.ScanMode = connection.getBluetoothScanMode(); console.info('scanMode: ' + scanMode); if (scanMode != connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE) { // Set the scan mode of the local device to SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE. connection.setBluetoothScanMode(connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0); } } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); }
application-dev\connectivity\bluetooth\br-discovery-development-guide.md
try { // Obtain information about the paired devices. let devices = connection.getPairedDevices(); console.info('pairedDevices: ' + JSON.stringify(devices)); // If the device address is known, check whether the device has been paired. if (devices.length > 0) { let pairState = connection.getPairState(devices[0]); console.info('device: '+ devices[0] + ' pairState is ' + pairState); } } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); }
application-dev\connectivity\bluetooth\br-discovery-development-guide.md
import { connection } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit'; export class DiscoveryDeviceManager { // Define the callback for scan result reporting events. onReceiveEvent(data: Array<string>) { console.info('bluetooth device: '+ JSON.stringify(data)); } public startDiscovery() { try { connection.on('bluetoothDeviceFind', this.onReceiveEvent); } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } try { // Check whether scanning is in progress on the local device. let scan = connection.isBluetoothDiscovering(); if (!scan) { // Start scanning for devices if a scan is not in progress. connection.startBluetoothDiscovery(); } } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } public stopDiscovery() { try { // Check whether scanning is in progress on the local device. let scan = connection.isBluetoothDiscovering(); if (scan) { // Stop scanning for devices if a scan is in progress. connection.stopBluetoothDiscovery(); } // If scanning is no longer needed, unsubscribe from scan result reporting events. connection.off('bluetoothDeviceFind', this.onReceiveEvent); } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } public setScanMode() { try { // Obtain the current scan mode of the local device. let scanMode: connection.ScanMode = connection.getBluetoothScanMode(); console.info('scanMode: ' + scanMode); if (scanMode != connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE) { // Set the scan mode of the local device to SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE. connection.setBluetoothScanMode(connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0); } } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } public getPairedDevices() { try { // Obtain information about the paired devices. let devices = connection.getPairedDevices(); console.info('pairedDevices: ' + JSON.stringify(devices)); // If the device address is known, check whether the device has been paired. if (devices.length > 0) { let pairState = connection.getPairState(devices[0]); console.info('device: '+ devices[0] + ' pairState is ' + pairState); } } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } } let discoveryDeviceManager = new DiscoveryDeviceManager(); export default discoveryDeviceManager as DiscoveryDeviceManager;
application-dev\connectivity\bluetooth\br-pair-device-development-guide.md
import { connection, a2dp, hfp, hid, baseProfile, constant } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit';
application-dev\connectivity\bluetooth\br-pair-device-development-guide.md
// Define the callback for pairing status changes. function onReceiveEvent(data: connection.BondStateParam) { console.info('pair result: '+ JSON.stringify(data)); } try { // Subscribe to pairing status changes. connection.on('bondStateChange', onReceiveEvent); } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); }
application-dev\connectivity\bluetooth\br-pair-device-development-guide.md
// Obtain the device address through the device discovery process. let device = 'XX:XX:XX:XX:XX:XX'; try { // Initiate pairing. connection.pairDevice(device).then(() => { console.info('pairDevice'); }, (error: BusinessError) => { console.error('pairDevice: errCode:' + error.code + ',errMessage' + error.message); }); } catch (err) { console.error('startPair: errCode:' + err.code + ',errMessage' + err.message); }
application-dev\connectivity\bluetooth\br-pair-device-development-guide.md
// Device address of the paired device let device = 'XX:XX:XX:XX:XX:XX'; // Create an A2DP, HFP, or HID instance. let a2dpSrc = a2dp.createA2dpSrcProfile(); let hfpAg = hfp.createHfpAgProfile(); let hidHost = hid.createHidHostProfile(); //Define the callback function for A2DP connection status changes. function onA2dpConnectStateChange(data: baseProfile.StateChangeParam) { console.info(`A2DP State: ${JSON.stringify(data)}`); } // Define the callback for HFP connection status change events. function onHfpConnectStateChange(data: baseProfile.StateChangeParam) { console.info(`HFP State: ${JSON.stringify(data)}`); } // Define the callback for HID connection status change events. function onHidConnectStateChange(data: baseProfile.StateChangeParam) { console.info(`HID State: ${JSON.stringify(data)}`); } try { // Check whether the target device supports the A2DP, HFP, and HID profiles. // Subscribe to connection status change events depending on the supported profile. a2dpSrc.on('connectionStateChange', onA2dpConnectStateChange); hfpAg.on('connectionStateChange', onHfpConnectStateChange); hidHost.on('connectionStateChange', onHidConnectStateChange); // Initiate a connection to the profile. connection.connectAllowedProfiles(device).then(() => { console.info('connectAllowedProfiles'); }, (error: BusinessError) => { console.error('errCode:' + error.code + ',errMessage' + error.message); }); } catch (err) { console.error('errCode:' + err.code + ',errMessage' + err.message); }
application-dev\connectivity\bluetooth\br-pair-device-development-guide.md
import { connection, a2dp, hfp, hid, baseProfile, constant } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit'; export class PairDeviceManager { device: string | null = null; pairState: connection.BondState = connection.BondState.BOND_STATE_INVALID; a2dpSrc = a2dp.createA2dpSrcProfile(); hfpAg = hfp.createHfpAgProfile(); hidHost = hid.createHidHostProfile(); // Define the callback for pairing status change events. onBondStateEvent(data: connection.BondStateParam) { console.info('pair result: '+ JSON.stringify(data)); if (data && data.deviceId == this.device) { this.pairState = data.state; // Save the pairing status of the target device. } } // Initiate pairing. The device address can be obtained through the device discovery process. public startPair(device: string) { this.device = device; try { // Subscribe to pairing status change events. connection.on('bondStateChange', this.onBondStateEvent); } catch (err) { console.error('bondStateChange errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } try { // Initiate pairing. connection.pairDevice(device).then(() => { console.info('pairDevice'); }, (error: BusinessError) => { console.error('pairDevice: errCode:' + error.code + ',errMessage' + error.message); }); } catch (err) { console.error('startPair: errCode:' + err.code + ',errMessage' + err.message); } } // Define the callback for A2DP connection status change events. onA2dpConnectStateChange(data: baseProfile.StateChangeParam) { console.info(`A2DP State: ${JSON.stringify(data)}`); } // Define the callback for HFP connection status change events. onHfpConnectStateChange(data: baseProfile.StateChangeParam) { console.info(`HFP State: ${JSON.stringify(data)}`); } // Define the callback for HID connection status change events. onHidConnectStateChange(data: baseProfile.StateChangeParam) { console.info(`HID State: ${JSON.stringify(data)}`); } // Initiate a connection. public async connect(device: string) { try { let uuids = await connection.getRemoteProfileUuids(device); console.info('device: ' + device + ' remoteUuids: '+ JSON.stringify(uuids)); let allowedProfiles = 0; // If an applicable profile exists, enable listening for connection status changes of the profile. if (uuids.some(uuid => uuid == constant.ProfileUuids.PROFILE_UUID_A2DP_SINK.toLowerCase())) { console.info('device supports a2dp'); allowedProfiles++; this.a2dpSrc.on('connectionStateChange', this.onA2dpConnectStateChange); } if (uuids.some(uuid => uuid == constant.ProfileUuids.PROFILE_UUID_HFP_HF.toLowerCase())) { console.info('device supports hfp'); allowedProfiles++; this.hfpAg.on('connectionStateChange', this.onHfpConnectStateChange); } if (uuids.some(uuid => uuid == constant.ProfileUuids.PROFILE_UUID_HID.toLowerCase()) || uuids.some(uuid => uuid == constant.ProfileUuids.PROFILE_UUID_HOGP.toLowerCase())) { console.info('device supports hid'); allowedProfiles++; this.hidHost.on('connectionStateChange', this.onHidConnectStateChange); } if (allowedProfiles > 0) { // If there is an applicable profile, initiate a connection. connection.connectAllowedProfiles(device).then(() => { console.info('connectAllowedProfiles'); }, (error: BusinessError) => { console.error('errCode:' + error.code + ',errMessage' + error.message); }); } } catch (err) { console.error('errCode:' + err.code + ',errMessage' + err.message); } } } let pairDeviceManager = new PairDeviceManager(); export default pairDeviceManager as PairDeviceManager;
application-dev\connectivity\bluetooth\gatt-development-guide.md
import { ble } from '@kit.ConnectivityKit'; import { constant } from '@kit.ConnectivityKit'; import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; const TAG: string = 'GattClientManager'; export class GattClientManager { device: string | undefined = undefined; gattClient: ble.GattClientDevice | undefined = undefined; connectState: ble.ProfileConnectionState = constant.ProfileConnectionState.STATE_DISCONNECTED; myServiceUuid: string = '00001810-0000-1000-8000-00805F9B34FB'; myCharacteristicUuid: string = '00001820-0000-1000-8000-00805F9B34FB'; myFirstDescriptorUuid: string = '00002902-0000-1000-8000-00805F9B34FB'; // 2902 is generally used for notification or indication. mySecondDescriptorUuid: string = '00002903-0000-1000-8000-00805F9B34FB'; found: boolean = false; // Construct BLEDescriptor. private initDescriptor(des: string, value: ArrayBuffer): ble.BLEDescriptor { let descriptor: ble.BLEDescriptor = { serviceUuid: this.myServiceUuid, characteristicUuid: this.myCharacteristicUuid, descriptorUuid: des, descriptorValue: value }; return descriptor; } // Construct BLECharacteristic. private initCharacteristic(): ble.BLECharacteristic { let descriptors: Array<ble.BLEDescriptor> = []; let descBuffer = new ArrayBuffer(2); let descValue = new Uint8Array(descBuffer); descValue[0] = 11; descValue[1] = 12; descriptors[0] = this.initDescriptor(this.myFirstDescriptorUuid, new ArrayBuffer(2)); descriptors[1] = this.initDescriptor(this.mySecondDescriptorUuid, descBuffer); let charBuffer = new ArrayBuffer(2); let charValue = new Uint8Array(charBuffer); charValue[0] = 1; charValue[1] = 2; let characteristic: ble.BLECharacteristic = { serviceUuid: this.myServiceUuid, characteristicUuid: this.myCharacteristicUuid, characteristicValue: charBuffer, descriptors: descriptors }; return characteristic; } private logCharacteristic(char: ble.BLECharacteristic) { let message = 'logCharacteristic uuid:' + char.characteristicUuid + '\n'; let value = new Uint8Array(char.characteristicValue); message += 'logCharacteristic value: '; for (let i = 0; i < char.characteristicValue.byteLength; i++) { message += value[i] + ' '; } console.info(TAG, message); } private logDescriptor(des: ble.BLEDescriptor) { let message = 'logDescriptor uuid:' + des.descriptorUuid + '\n'; let value = new Uint8Array(des.descriptorValue); message += 'logDescriptor value: '; for (let i = 0; i < des.descriptorValue.byteLength; i++) { message += value[i] + ' '; } console.info(TAG, message); } private checkService(services: Array<ble.GattService>): boolean { for (let i = 0; i < services.length; i++) { if (services[i].serviceUuid != this.myServiceUuid) { continue; } for (let j = 0; j < services[i].characteristics.length; j++) { if (services[i].characteristics[j].characteristicUuid != this.myCharacteristicUuid) { continue; } for (let k = 0; k < services[i].characteristics[j].descriptors.length; k++) { if (services[i].characteristics[j].descriptors[k].descriptorUuid == this.myFirstDescriptorUuid) { console.info(TAG, 'find expected service from server'); return true; } } } } console.error(TAG, 'no expected service from server'); return false; } // 1. Subscribe to the connection status change event. public onGattClientStateChange() { if (!this.gattClient) { console.error(TAG, 'no gattClient'); return; } try { this.gattClient.on('BLEConnectionStateChange', (stateInfo: ble.BLEConnectionChangeState) => { let state = ''; switch (stateInfo.state) { case 0: state = 'DISCONNECTED'; break; case 1: state = 'CONNECTING'; break; case 2: state = 'CONNECTED'; break; case 3: state = 'DISCONNECTING'; break; default: state = 'undefined'; break; } console.info(TAG, 'onGattClientStateChange: device=' + stateInfo.deviceId + ', state=' + state); if (stateInfo.deviceId == this.device) { this.connectState = stateInfo.state; } }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 2. Called when the client proactively connects to the server. public startConnect(peerDevice: string) {// The peer device is generally discovered through BLE scan. if (this.connectState != constant.ProfileConnectionState.STATE_DISCONNECTED) { console.error(TAG, 'startConnect failed'); return; } console.info(TAG, 'startConnect ' + peerDevice); this.device = peerDevice; // 2.1 Use device to construct gattClient. This instance is used for subsequent interactions. this.gattClient = ble.createGattClientDevice(peerDevice); try { this.onGattClientStateChange(); // 2.2 Subscribe to the connection status. this.gattClient.connect(); // 2.3 Initiate a connection. } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 3. After the client is connected, start service discovery. public discoverServices() { if (!this.gattClient) { console.info(TAG, 'no gattClient'); return; } console.info(TAG, 'discoverServices'); try { this.gattClient.getServices().then((result: Array<ble.GattService>) => { console.info(TAG, 'getServices success: ' + JSON.stringify(result)); this.found = this.checkService(result); // Ensure that the service required exists on the server. }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 4. Read a specific characteristic after obtaining the services on the server. public readCharacteristicValue() { if (!this.gattClient || this.connectState != constant.ProfileConnectionState.STATE_CONNECTED) { console.error(TAG, 'no gattClient or not connected'); return; } if (!this.found) {// Ensure that the server has the corresponding characteristic. console.error(TAG, 'no characteristic from server'); return; } let characteristic = this.initCharacteristic(); console.info(TAG, 'readCharacteristicValue'); try { this.gattClient.readCharacteristicValue(characteristic).then((outData: ble.BLECharacteristic) => { this.logCharacteristic(outData); }) } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 5. Write a characteristic value after obtaining the services on the server. public writeCharacteristicValue() { if (!this.gattClient || this.connectState != constant.ProfileConnectionState.STATE_CONNECTED) { console.error(TAG, 'no gattClient or not connected'); return; } if (!this.found) {// Ensure that the server has the corresponding characteristic. console.error(TAG, 'no characteristic from server'); return; } let characteristic = this.initCharacteristic(); console.info(TAG, 'writeCharacteristicValue'); try { this.gattClient.writeCharacteristicValue(characteristic, ble.GattWriteType.WRITE, (err) => { if (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); return; } console.info(TAG, 'writeCharacteristicValue success'); }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 6. Read a specific service descriptor after obtaining the services on the server. public readDescriptorValue() { if (!this.gattClient || this.connectState != constant.ProfileConnectionState.STATE_CONNECTED) { console.error(TAG, 'no gattClient or not connected'); return; } if (!this.found) {// Ensure that the server has the corresponding descriptor. console.error(TAG, 'no descriptor from server'); return; } let descBuffer = new ArrayBuffer(0); let descriptor = this.initDescriptor(this.mySecondDescriptorUuid, descBuffer); console.info(TAG, 'readDescriptorValue'); try { this.gattClient.readDescriptorValue(descriptor).then((outData: ble.BLEDescriptor) => { this.logDescriptor(outData); }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 7. Write a service descriptor after obtaining the services on the server. public writeDescriptorValue() { if (!this.gattClient || this.connectState != constant.ProfileConnectionState.STATE_CONNECTED) { console.error(TAG, 'no gattClient or not connected'); return; } if (!this.found) {// Ensure that the server has the corresponding descriptor. console.error(TAG, 'no descriptor from server'); return; } let descBuffer = new ArrayBuffer(2); let descValue = new Uint8Array(descBuffer); descValue[0] = 11; descValue[1] = 12; let descriptor = this.initDescriptor(this.mySecondDescriptorUuid, descBuffer); console.info(TAG, 'writeDescriptorValue'); try { this.gattClient.writeDescriptorValue(descriptor, (err) => { if (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); return; } console.info(TAG, 'writeDescriptorValue success'); }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 8. The client proactively disconnects from the server. public stopConnect() { if (!this.gattClient || this.connectState != constant.ProfileConnectionState.STATE_CONNECTED) { console.error(TAG, 'no gattClient or not connected'); return; } console.info(TAG, 'stopConnect ' + this.device); try { this.gattClient.disconnect (); // 8.1 Disconnect from the server. this.gattClient.off('BLEConnectionStateChange', (stateInfo: ble.BLEConnectionChangeState) => { }); this.gattClient.close () // 8.2 Close this gattClient if it is no longer required. } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } } let gattClientManager = new GattClientManager(); export default gattClientManager as GattClientManager;
application-dev\connectivity\bluetooth\gatt-development-guide.md
import { ble } from '@kit.ConnectivityKit'; import { constant } from '@kit.ConnectivityKit'; import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; const TAG: string = 'GattServerManager'; export class GattServerManager { gattServer: ble.GattServer | undefined = undefined; connectState: ble.ProfileConnectionState = constant.ProfileConnectionState.STATE_DISCONNECTED; myServiceUuid: string = '00001810-0000-1000-8000-00805F9B34FB'; myCharacteristicUuid: string = '00001820-0000-1000-8000-00805F9B34FB'; myFirstDescriptorUuid: string = '00002902-0000-1000-8000-00805F9B34FB'; // 2902 is generally used for notification or indication. mySecondDescriptorUuid: string = '00002903-0000-1000-8000-00805F9B34FB'; // Construct BLEDescriptor. private initDescriptor(des: string, value: ArrayBuffer): ble.BLEDescriptor { let descriptor: ble.BLEDescriptor = { serviceUuid: this.myServiceUuid, characteristicUuid: this.myCharacteristicUuid, descriptorUuid: des, descriptorValue: value }; return descriptor; } // Construct BLECharacteristic. private initCharacteristic(): ble.BLECharacteristic { let descriptors: Array<ble.BLEDescriptor> = []; let descBuffer = new ArrayBuffer(2); let descValue = new Uint8Array(descBuffer); descValue[0] = 31; descValue[1] = 32; descriptors[0] = this.initDescriptor(this.myFirstDescriptorUuid, new ArrayBuffer(2)); descriptors[1] = this.initDescriptor(this.mySecondDescriptorUuid, descBuffer); let charBuffer = new ArrayBuffer(2); let charValue = new Uint8Array(charBuffer); charValue[0] = 21; charValue[1] = 22; let characteristic: ble.BLECharacteristic = { serviceUuid: this.myServiceUuid, characteristicUuid: this.myCharacteristicUuid, characteristicValue: charBuffer, descriptors: descriptors }; return characteristic; } // 1. Subscribe to the connection status change event. public onGattServerStateChange() { if (!this.gattServer) { console.error(TAG, 'no gattServer'); return; } try { this.gattServer.on('connectionStateChange', (stateInfo: ble.BLEConnectionChangeState) => { let state = ''; switch (stateInfo.state) { case 0: state = 'DISCONNECTED'; break; case 1: state = 'CONNECTING'; break; case 2: state = 'CONNECTED'; break; case 3: state = 'DISCONNECTING'; break; default: state = 'undefined'; break; } console.info(TAG, 'onGattServerStateChange: device=' + stateInfo.deviceId + ', state=' + state); }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 2. Register a service with the server. public registerServer() { let characteristics: Array<ble.BLECharacteristic> = []; let characteristic = this.initCharacteristic(); characteristics.push(characteristic); let gattService: ble.GattService = { serviceUuid: this.myServiceUuid, isPrimary: true, characteristics: characteristics }; console.info(TAG, 'registerServer ' + this.myServiceUuid); try { The this.gattServer = ble.createGattServer(); // 2.1 Create a gattServer instance, which is used in subsequent interactions. this.onGattServerStateChange(); // 2.2 Subscribe to the connection status. this.gattServer.addService(gattService); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 3. Subscribe to the characteristic read requests from the gattClient. public onCharacteristicRead() { if (!this.gattServer) { console.error(TAG, 'no gattServer'); return; } console.info(TAG, 'onCharacteristicRead'); try { this.gattServer.on('characteristicRead', (charReq: ble.CharacteristicReadRequest) => { let deviceId: string = charReq.deviceId; let transId: number = charReq.transId; let offset: number = charReq.offset; console.info(TAG, 'receive characteristicRead'); let rspBuffer = new ArrayBuffer(2); let rspValue = new Uint8Array(rspBuffer); rspValue[0] = 21; rspValue[1] = 22; let serverResponse: ble.ServerResponse = { deviceId: deviceId, transId: transId, status: 0, // The value 0 indicates the operation is successful. offset: offset, value: rspBuffer }; try { this.gattServer.sendResponse(serverResponse); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 4. Subscribe to the characteristic write requests from the gattClient. public onCharacteristicWrite() { if (!this.gattServer) { console.error(TAG, 'no gattServer'); return; } console.info(TAG, 'onCharacteristicWrite'); try { this.gattServer.on('characteristicWrite', (charReq: ble.CharacteristicWriteRequest) => { let deviceId: string = charReq.deviceId; let transId: number = charReq.transId; let offset: number = charReq.offset; console.info(TAG, 'receive characteristicWrite: needRsp=' + charReq.needRsp); if (!charReq.needRsp) { return; } let rspBuffer = new ArrayBuffer(0); let serverResponse: ble.ServerResponse = { deviceId: deviceId, transId: transId, status: 0, // The value 0 indicates the operation is successful. offset: offset, value: rspBuffer }; try { this.gattServer.sendResponse(serverResponse); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 5. Subscribe to the descriptor read requests from the gattClient. public onDescriptorRead() { if (!this.gattServer) { console.error(TAG, 'no gattServer'); return; } console.info(TAG, 'onDescriptorRead'); try { this.gattServer.on('descriptorRead', (desReq: ble.DescriptorReadRequest) => { let deviceId: string = desReq.deviceId; let transId: number = desReq.transId; let offset: number = desReq.offset; console.info(TAG, 'receive descriptorRead'); let rspBuffer = new ArrayBuffer(2); let rspValue = new Uint8Array(rspBuffer); rspValue[0] = 31; rspValue[1] = 32; let serverResponse: ble.ServerResponse = { deviceId: deviceId, transId: transId, status: 0, // The value 0 indicates the operation is successful. offset: offset, value: rspBuffer }; try { this.gattServer.sendResponse(serverResponse); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 6. Subscribe to the descriptor write requests from the gattClient. public onDescriptorWrite() { if (!this.gattServer) { console.error(TAG, 'no gattServer'); return; } console.info(TAG, 'onDescriptorWrite'); try { this.gattServer.on('descriptorWrite', (desReq: ble.DescriptorWriteRequest) => { let deviceId: string = desReq.deviceId; let transId: number = desReq.transId; let offset: number = desReq.offset; console.info(TAG, 'receive descriptorWrite: needRsp=' + desReq.needRsp); if (!desReq.needRsp) { return; } let rspBuffer = new ArrayBuffer(0); let serverResponse: ble.ServerResponse = { deviceId: deviceId, transId: transId, status: 0, // The value 0 indicates the operation is successful. offset: offset, value: rspBuffer }; try { this.gattServer.sendResponse(serverResponse); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } }); } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } // 7. Unregister the service that is not required from the server. public unRegisterServer() { if (!this.gattServer) { console.error(TAG, 'no gattServer'); return; } console.info(TAG, 'unRegisterServer ' + this.myServiceUuid); try { this.gattServer.removeService (this.myServiceUuid); // 7.1 Remove the service. this.gattServer.off('connectionStateChange', (stateInfo: ble.BLEConnectionChangeState) => { // 7.2 Unsubscribe from the connection state changes. }); this.gattServer.close() // 7.3 Close the gattServer if it is no longer required. } catch (err) { console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } } } let gattServerManager = new GattServerManager(); export default gattServerManager as GattServerManager;
application-dev\connectivity\bluetooth\spp-development-guide.md
import { socket } from '@kit.ConnectivityKit'; import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; // Create a server listening socket. serverId is returned if the socket is created. let serverNumber = -1; let sppOption: socket.SppOptions = { uuid: '00001101-0000-1000-8000-00805f9b34fb', secure: true, type: 0 }; socket.sppListen('server1', sppOption, (code, serverSocketID) => { if (code != null) { console.error('sppListen error, code is ' + (code as BusinessError).code); return; } else { serverNumber = serverSocketID; console.info('sppListen success, serverNumber = ' + serverNumber); } }); // Establish a connection between the server socket and client socket. If the connection is successful, clientId is returned. let clientNumber = -1; socket.sppAccept(serverNumber, (code, clientSocketID) => { if (code != null) { console.error('sppAccept error, code is ' + (code as BusinessError).code); return; } else { clientNumber = clientSocketID; console.info('accept the client success'); } }) console.info('waiting for client connection'); // Write data to the client. let array = new Uint8Array(990); array[0] = 'A'.charCodeAt(0); array[1] = 'B'.charCodeAt(0); array[2] = 'C'.charCodeAt(0); array[3] = 'D'.charCodeAt(0); socket.sppWrite(clientNumber, array.buffer); console.info('sppWrite success'); // Subscribe to the read request event. socket.on('sppRead', clientNumber, (dataBuffer: ArrayBuffer) => { const data = new Uint8Array(dataBuffer); if (data != null) { console.info('sppRead success, data = ' + JSON.stringify(data)); } else { console.error('sppRead error, data is null'); } }); // Unsubscribe from the read request event. socket.off('sppRead', clientNumber, (dataBuffer: ArrayBuffer) => { const data = new Uint8Array(dataBuffer); if (data != null) { console.info('offSppRead success, data = ' + JSON.stringify(data)); } else { console.error('offSppRead error, data is null'); } }); // Close the server socket. socket.sppCloseServerSocket(serverNumber); console.info('sppCloseServerSocket success'); // Close the client socket. socket.sppCloseClientSocket(clientNumber); console.info('sppCloseClientSocket success');
application-dev\connectivity\bluetooth\spp-development-guide.md
import { socket } from '@kit.ConnectivityKit'; import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; // Start Bluetooth scanning to obtain the MAC address of the peer device. let deviceId = 'xx:xx:xx:xx:xx:xx'; // Connect to the peer device. socket.sppConnect(deviceId, { uuid: '00001101-0000-1000-8000-00805f9b34fb', secure: true, type: 0 }, (code, socketID) => { if (code != null) { console.error('sppConnect error, code = ' + (code as BusinessError).code); return; } console.info('sppConnect success, socketId = ' + socketID); })
application-dev\connectivity\nfc\nfc-hce-guide.md
"abilities": [ { "name": "EntryAbility", "srcEntry": "./ets/entryability/EntryAbility.ts", "description": "$string:EntryAbility_desc", "icon": "$media:icon", "label": "$string:EntryAbility_label", "startWindowIcon": "$media:icon", "startWindowBackground": "$color:start_window_background", "exported": true, "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home", // Make sure that ohos.nfc.cardemulation.action.HOST_APDU_SERVICE is present in actions. "ohos.nfc.cardemulation.action.HOST_APDU_SERVICE" ] } ] } ], "requestPermissions": [ { // Add the permission required for NFC card emulation. "name": "ohos.permission.NFC_CARD_EMULATION", "reason": "$string:app_name", } ]
application-dev\connectivity\nfc\nfc-hce-guide.md
import { cardEmulation } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { AsyncCallback } from '@kit.BasicServicesKit'; import { AbilityConstant, UIAbility, Want, bundleManager } from '@kit.AbilityKit'; let hceElementName: bundleManager.ElementName; let hceService: cardEmulation.HceService; const hceCommandCb : AsyncCallback<number[]> = (error : BusinessError, hceCommand : number[]) => { if (!error) { if (hceCommand == null || hceCommand == undefined) { hilog.error(0x0000, 'testTag', 'hceCommandCb has invalid hceCommand.'); return; } // Check the command and send a response. hilog.info(0x0000, 'testTag', 'hceCommand = %{public}s', JSON.stringify(hceCommand)); let responseData = [0x90, 0x00]; // Modify the response based on the received command. hceService.transmit(responseData).then(() => { hilog.info(0x0000, 'testTag', 'hceService transmit Promise success.'); }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', 'hceService transmit Promise error = %{public}s', JSON.stringify(err)); }); } else { hilog.error(0x0000, 'testTag', 'hceCommandCb error %{public}s', JSON.stringify(error)); } } export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); // Check whether the device supports the NFC and HCE capabilities. if (!canIUse("SystemCapability.Communication.NFC.Core")) { hilog.error(0x0000, 'testTag', 'nfc unavailable.'); return; } if (!cardEmulation.hasHceCapability()) { hilog.error(0x0000, 'testTag', 'hce unavailable.'); return; } hceElementName = { bundleName: want.bundleName ?? '', abilityName: want.abilityName ?? '', moduleName: want.moduleName, } hceService = new cardEmulation.HceService(); } onForeground() { // Switch the application to the foreground. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); if (hceElementName != undefined) { try { // Enable the foreground HCE application to preferentially process NFC card swiping. let aidList = ["A0000000031010," "A0000000031011"]; // Set the AID list correctly. hceService.start(hceElementName, aidList); // Subscribe to the reception of HCE APDU data. hceService.on('hceCmd', hceCommandCb); } catch (error) { hilog.error(0x0000, 'testTag', 'hceService.start error = %{public}s', JSON.stringify(error)); } } } onBackground() { // Switch the application to the background. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); // When exiting the NFC tag page of the application, call the tag module API to exit the foreground mode. if (hceElementName != undefined) { try { hceService.stop(hceElementName); } catch (error) { hilog.error(0x0000, 'testTag', 'hceService.stop error = %{public}s', JSON.stringify(error)); } } } }
application-dev\connectivity\nfc\nfc-hce-guide.md
"abilities": [ { "name": "EntryAbility", "srcEntry": "./ets/entryability/EntryAbility.ts", "description": "$string:EntryAbility_desc", "icon": "$media:icon", "label": "$string:EntryAbility_label", "startWindowIcon": "$media:icon", "startWindowBackground": "$color:start_window_background", "exported": true, "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home", // Make sure that ohos.nfc.cardemulation.action.HOST_APDU_SERVICE is present in actions. "ohos.nfc.cardemulation.action.HOST_APDU_SERVICE" ] } ], "metadata": [ { "name": "payment-aid", "value": "A0000000031010" // Set a correct AID. }, { "name": "other-aid", "value": "A0000000031011" // Set a correct AID. } ] } ], "requestPermissions": [ { // Add the permission required for NFC card emulation. "name": "ohos.permission.NFC_CARD_EMULATION", "reason": "$string:app_name", } ]
application-dev\connectivity\nfc\nfc-hce-guide.md
import { cardEmulation } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { AsyncCallback } from '@kit.BasicServicesKit'; import { AbilityConstant, UIAbility, Want, bundleManager } from '@kit.AbilityKit'; let hceElementName : bundleManager.ElementName; let hceService: cardEmulation.HceService; const hceCommandCb : AsyncCallback<number[]> = (error : BusinessError, hceCommand : number[]) => { if (!error) { if (hceCommand == null || hceCommand == undefined) { hilog.error(0x0000, 'testTag', 'hceCommandCb has invalid hceCommand.'); return; } // Check the command and send a response. hilog.info(0x0000, 'testTag', 'hceCommand = %{public}s', JSON.stringify(hceCommand)); let responseData = [0x90, 0x00]; // change the response depend on different received command. hceService.transmit(responseData).then(() => { hilog.info(0x0000, 'testTag', 'hceService transmit Promise success.'); }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', 'hceService transmit Promise error = %{public}s', JSON.stringify(err)); }); } else { hilog.error(0x0000, 'testTag', 'hceCommandCb error %{public}s', JSON.stringify(error)); } } export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); // Check whether the device supports the NFC and HCE capabilities. if (!canIUse("SystemCapability.Communication.NFC.Core")) { hilog.error(0x0000, 'testTag', 'nfc unavailable.'); return; } if (!cardEmulation.hasHceCapability()) { hilog.error(0x0000, 'testTag', 'hce unavailable.'); return; } hceElementName = { bundleName: want.bundleName ?? '', abilityName: want.abilityName ?? '', moduleName: want.moduleName, } hceService = new cardEmulation.HceService(); hceService.on('hceCmd', hceCommandCb); } onForeground() { // Switch the application to the foreground. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); } onDestroy() { // Exit the application. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); // When exiting the NFC tag page of the application, call the tag module API to exit the foreground mode. if (hceElementName != undefined) { try { hceService.stop(hceElementName); } catch (error) { hilog.error(0x0000, 'testTag', 'hceService.stop error = %{public}s', JSON.stringify(error)); } } } }
application-dev\connectivity\nfc\nfc-se-access-guide.md
import { omapi } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; let seService : omapi.SEService; let seReaders : omapi.Reader[]; let seSession : omapi.Session; let seChannel : omapi.Channel; let aidArray : number[] = [0xA0, 0x00, 0x00, 0x00, 0x03, 0x10, 0x10]; let p2 : number = 0x00; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); // Check whether the device supports SEs. if (!canIUse("SystemCapability.Communication.SecureElement")) { hilog.error(0x0000, 'testTag', 'secure element unavailable.'); return; } hilog.info(0x0000, 'testTag', 'secure element available.'); this.omaTest(); } private async omaTest () { // Obtain the service. await omapi.createService().then((data) => { if (data == undefined || !data.isConnected()) { hilog.error(0x0000, 'testTag', 'secure element service disconnected.'); return; } seService = data; hilog.info(0x0000, 'testTag', 'secure element service connected.'); }).catch((error: BusinessError) => { hilog.error(0x0000, 'testTag', 'createService error %{public}s', JSON.stringify(error)); return; }); // Obtain readers. try { seReaders = seService.getReaders(); } catch (error) { hilog.error(0x0000, 'testTag', 'getReaders error %{public}s', JSON.stringify(error)); } if (seReaders == undefined || seReaders.length == 0) { hilog.error(0x0000, 'testTag', 'no valid reader found.'); seService.shutdown(); return; } let reader: (omapi.Reader | undefined); for (let i = 0; i < seReaders.length; ++i) { let r = seReaders[i]; if (r.getName().includes("SIM")) { reader = r; break; } } if (reader == undefined) { hilog.error(0x0000, 'testTag', 'no valid sim reader.'); return; } hilog.info(0x0000, 'testTag', 'reader is %{public}s', reader?.getName()); // Obtain the session. try { seSession = reader?.openSession() as omapi.Session; } catch (error) { hilog.error(0x0000, 'testTag', 'openSession error %{public}s', JSON.stringify(error)); } if (seSession == undefined) { hilog.error(0x0000, 'testTag', 'seSession invalid.'); seService.shutdown(); return; } // Obtain the channel. try { // change the aid value for open logical channel // Change the value to the AID of the application for which the logical channel is opened. seChannel = await seSession.openLogicalChannel(aidArray, p2); } catch (exception) { hilog.error(0x0000, 'testTag', 'openLogicalChannel exception %{public}s', JSON.stringify(exception)); } if (seChannel == undefined) { hilog.error(0x0000, 'testTag', 'seChannel invalid.'); return; } // Send data. let cmdData = [0x01, 0x02, 0x03, 0x04]; // Set command data correctly. try { let response: number[] = await seChannel.transmit(cmdData) hilog.info(0x0000, 'testTag', 'seChannel.transmit() response = %{public}s.', JSON.stringify(response)); } catch (exception) { hilog.error(0x0000, 'testTag', 'seChannel.transmit() exception = %{public}s.', JSON.stringify(exception)); } // Close the channel. After performing the operation, make sure that the channel is truly closed. try { seChannel.close(); } catch (exception) { hilog.error(0x0000, 'testTag', 'seChannel.close() exception = %{public}s.', JSON.stringify(exception)); } } }
application-dev\connectivity\nfc\nfc-tag-access-guide.md
"abilities": [ { "name": "EntryAbility", "srcEntry": "./ets/entryability/EntryAbility.ts", "description": "$string:EntryAbility_desc", "icon": "$media:icon", "label": "$string:EntryAbility_label", "startWindowIcon": "$media:icon", "startWindowBackground": "$color:start_window_background", "exported": true, "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home", // Make sure that ohos.nfc.tag.action.TAG_FOUND is present in actions. "ohos.nfc.tag.action.TAG_FOUND" ] } ] } ], "requestPermissions": [ { // Add the NFC tag operation permission. "name": "ohos.permission.NFC_TAG", "reason": "$string:app_name", } ]
application-dev\connectivity\nfc\nfc-tag-access-guide.md
import { tag } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { AbilityConstant, UIAbility, Want, bundleManager } from '@kit.AbilityKit'; let nfcTagElementName: bundleManager.ElementName; let foregroundRegister: boolean; async function readerModeCb(error : BusinessError, tagInfo : tag.TagInfo) { if (!error) { // Obtain an NFC tag object of the specific technology type. if (tagInfo == null || tagInfo == undefined) { hilog.error(0x0000, 'testTag', 'readerModeCb tagInfo is invalid'); return; } if (tagInfo.uid == null || tagInfo.uid == undefined) { hilog.error(0x0000, 'testTag', 'readerModeCb uid is invalid'); return; } if (tagInfo.technology == null || tagInfo.technology == undefined || tagInfo.technology.length == 0) { hilog.error(0x0000, 'testTag', 'readerModeCb technology is invalid'); return; } // Read and write the tag data. // Access the NFC tag using IsoDep. let isoDep : tag.IsoDepTag | null = null; for (let i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.ISO_DEP) { try { isoDep = tag.getIsoDep(tagInfo); } catch (error) { hilog.error(0x0000, 'testTag', 'readerModeCb getIsoDep error = %{public}s', JSON.stringify(error)); return; } } // Access the NFC tag using other technologies. } if (isoDep == undefined) { hilog.error(0x0000, 'testTag', 'readerModeCb getIsoDep is invalid'); return; } // Connect to the NFC tag using IsoDep. try { isoDep.connect(); } catch (error) { hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.connect() error = %{public}s', JSON.stringify(error)); return; } if (!isoDep.isConnected()) { hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.isConnected() false.'); return; } // Send an instruction to the connected tag. let cmdData = [0x01, 0x02, 0x03, 0x04]; // Specify the instruction of the protocol corresponding to the tag type. try { isoDep.transmit(cmdData).then((response : number[]) => { hilog.info(0x0000, 'testTag', 'readerModeCb isoDep.transmit() response = %{public}s.', JSON.stringify(response)); }).catch((err : BusinessError)=> { hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.transmit() err = %{public}s.', JSON.stringify(err)); return; }); } catch (businessError) { hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.transmit() businessError = %{public}s.', JSON.stringify(businessError)); return; } } else { hilog.info(0x0000, 'testTag', 'readerModeCb readerModeCb error %{public}s', JSON.stringify(error)); } } export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); // Check whether the device supports the NFC feature. if (!canIUse("SystemCapability.Communication.NFC.Core")) { hilog.error(0x0000, 'testTag', 'nfc unavailable.'); return; } nfcTagElementName = { bundleName: want.bundleName ?? '', abilityName: want.abilityName ?? '', moduleName: want.moduleName, } } onForeground() { // Switch the application to the foreground. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); if (nfcTagElementName != undefined) { // Register a listener for the NFC tag read event so that the tag can be preferentially dispatched to a foreground application. let techList : number[] = [tag.NFC_A, tag.NFC_B, tag.NFC_F, tag.NFC_V]; try { tag.on('readerMode', nfcTagElementName, techList, readerModeCb); foregroundRegister = true; } catch (error) { hilog.error(0x0000, 'testTag', 'on readerMode error = %{public}s', JSON.stringify(error)); } } } onBackground() { // Switch the application to the background. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); // When exiting the NFC tag page of the application, call the tag module API to exit the foreground mode. if (foregroundRegister) { foregroundRegister = false; try { tag.off('readerMode', nfcTagElementName); } catch (error) { hilog.error(0x0000, 'testTag', 'off readerMode error = %{public}s', JSON.stringify(error)); } } } }
application-dev\connectivity\nfc\nfc-tag-access-guide.md
"abilities": [ { "name": "EntryAbility", "srcEntry": "./ets/entryability/EntryAbility.ts", "description": "$string:EntryAbility_desc", "icon": "$media:icon", "label": "$string:EntryAbility_label", "startWindowIcon": "$media:icon", "startWindowBackground": "$color:start_window_background", "exported": true, "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home", // Make sure that ohos.nfc.tag.action.TAG_FOUND is present in actions. "ohos.nfc.tag.action.TAG_FOUND" ], "uris": [ { "type":"tag-tech/NfcA" }, { "type":"tag-tech/IsoDep" } // Add other technologies if necessary. // Example: NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable ] } ] } ], "requestPermissions": [ { // Add NFC tag operation permission. "name": "ohos.permission.NFC_TAG", "reason": "$string:app_name", } ]
application-dev\connectivity\nfc\nfc-tag-access-guide.md
import { tag } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); // Obtain an NFC tag object of the specific technology type. let tagInfo : tag.TagInfo; try { tagInfo = tag.getTagInfo(want); } catch (error) { hilog.error(0x0000, 'testTag', 'getTagInfo error = %{public}s', JSON.stringify(error)); return; } if (tagInfo == null || tagInfo == undefined) { hilog.error(0x0000, 'testTag', 'tagInfo is invalid'); return; } if (tagInfo.uid == null || tagInfo.uid == undefined) { hilog.error(0x0000, 'testTag', 'uid is invalid'); return; } if (tagInfo.technology == null || tagInfo.technology == undefined || tagInfo.technology.length == 0) { hilog.error(0x0000, 'testTag', 'technology is invalid'); return; } // Read and write the tag data. // Access the NFC tag using IsoDep. let isoDep : tag.IsoDepTag | null = null; for (let i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.ISO_DEP) { try { isoDep = tag.getIsoDep(tagInfo); } catch (error) { hilog.error(0x0000, 'testTag', 'getIsoDep error = %{public}s', JSON.stringify(error)); return; } } // Access the NFC tag using other technologies. } if (isoDep == undefined) { hilog.error(0x0000, 'testTag', 'getIsoDep is invalid'); return; } // Connect to the NFC tag using IsoDep. try { isoDep.connect(); } catch (error) { hilog.error(0x0000, 'testTag', 'isoDep.connect() error = %{public}s', JSON.stringify(error)); return; } if (!isoDep.isConnected()) { hilog.error(0x0000, 'testTag', 'isoDep.isConnected() false.'); return; } // Send an instruction to the connected tag. let cmdData = [0x01, 0x02, 0x03, 0x04]; // Specify the instruction of the protocol corresponding to the tag type. try { isoDep.transmit(cmdData).then((response : number[]) => { hilog.info(0x0000, 'testTag', 'isoDep.transmit() response = %{public}s.', JSON.stringify(response)); }).catch((err : BusinessError)=> { hilog.error(0x0000, 'testTag', 'isoDep.transmit() err = %{public}s.', JSON.stringify(err)); return; }); } catch (businessError) { hilog.error(0x0000, 'testTag', 'isoDep.transmit() businessError = %{public}s.', JSON.stringify(businessError)); return; } } }
application-dev\connectivity\wlan\p2p-development-guide.md
import { wifiManager } from '@kit.ConnectivityKit'; // Create a P2P group. To use the current device as the group owner (GO), set: // netId: The value -1 means to create a temporary P2P group. When a device in the group is to be connected next time, GO negotiation and WPS key negotiation must be performed again. // The value -2 means to create a persistent group. The device in the group can be reconnected without GO negotiation or WPS key negotiation. let recvP2pPersistentGroupChangeFunc = () => { console.info("p2p persistent group change receive event"); // Services to be processed after the persistent group is created. } // Create a persistent group, and register a listener callback for the persistent group status changes. wifiManager.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); try { let config:wifiManager.WifiP2PConfig = { deviceAddress: "00:11:22:33:44:55", deviceAddressType: 1, netId: -2, passphrase: "12345678", groupName: "testGroup", goBand: 0 } wifiManager.createGroup(config); }catch(error){ console.error("failed:" + JSON.stringify(error)); } // Remove a P2P group. try { wifiManager.removeGroup(); }catch(error){ console.error("failed:" + JSON.stringify(error)); }
application-dev\connectivity\wlan\p2p-development-guide.md
import { wifiManager } from '@kit.ConnectivityKit'; let recvP2pConnectionChangeFunc = (result:wifiManager.WifiP2pLinkedInfo) => { console.info("p2p connection change receive event: " + JSON.stringify(result)); wifiManager.getP2pLinkedInfo((err, data) => { if (err) { console.error("failed to get P2pLinkedInfo: " + JSON.stringify(err)); return; } console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); // Add the service processing logic after a successful or failed P2P connection. }); } // After the P2P connection is set up, the callback for p2pConnectionChange will be called. wifiManager.on("p2pConnectionChange", recvP2pConnectionChangeFunc); let recvP2pPeerDeviceChangeFunc = (result:wifiManager.WifiP2pDevice[]) => { console.info("p2p peer device change receive event: " + JSON.stringify(result)); wifiManager.getP2pPeerDevices((err, data) => { if (err) { console.error("failed to get peer devices: " + JSON.stringify(err)); return; } console.info("get peer devices: " + JSON.stringify(data)); let len = data.length; for (let i = 0; i < len; ++i) { // Select the peer P2P device that meets the conditions. if (data[i].deviceName === "my_test_device") { console.info("p2p connect to test device: " + data[i].deviceAddress); let config:wifiManager.WifiP2PConfig = { deviceAddress:data[i].deviceAddress, deviceAddressType: 1, netId:-2, passphrase:"", groupName:"", goBand:0, } // Set up a P2P connection. The GO cannot initiate connections. wifiManager.p2pConnect(config); } } }); } // The callback for p2pPeerDeviceChange will be called when the P2P scanning result is reported. wifiManager.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); setTimeout(() => {wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); setTimeout(() => {wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); // Start to discover P2P devices, that is, start P2P scanning. console.info("start discover devices -> " + wifiManager.startDiscoverDevices());
application-dev\connectivity\wlan\scan-development-guide.md
import { wifiManager } from '@kit.ConnectivityKit'; try { let recvWifiScanStateChangeFunc = (result:number) => { console.info("Receive Wifi scan state change event: " + result); } // Obtain the scan status. The value 1 indicates that the scan is successful, and the value 0 indicates the opposite. wifiManager.on("wifiScanStateChange", recvWifiScanStateChangeFunc); let isWifiActive = wifiManager.isWifiActive(); if (!isWifiActive) { console.error("wifi not enable"); // Enable Wi-Fi manually. return; } let scanInfoList = wifiManager.getScanInfoList(); let len = scanInfoList.length; console.info("wifi received scan info: " + len); if(len > 0){ for (let i = 0; i < len; ++i) { console.info("ssid: " + scanInfoList[i].ssid); console.info("bssid: " + scanInfoList[i].bssid); console.info("capabilities: " + scanInfoList[i].capabilities); console.info("securityType: " + scanInfoList[i].securityType); console.info("rssi: " + scanInfoList[i].rssi); console.info("band: " + scanInfoList[i].band); console.info("frequency: " + scanInfoList[i].frequency); console.info("channelWidth: " + scanInfoList[i].channelWidth); console.info("timestamp: " + scanInfoList[i].timestamp); console.info("supportedWifiCategory: " + scanInfoList[i].supportedWifiCategory); console.info("isHiLinkNetwork: " + scanInfoList[i].isHiLinkNetwork); } } // Unsubscribe from Wi-Fi scan state changes. wifiManager.off("wifiScanStateChange", recvWifiScanStateChangeFunc); }
application-dev\connectivity\wlan\sta-development-guide.md
import { wifiManager } from '@kit.ConnectivityKit'; try { let recvPowerNotifyFunc = (result:number) => { let wifiState = ""; switch (result) { case 0: wifiState += 'DISABLING'; break; case 1: wifiState += 'DISABLED'; break; case 2: wifiState += 'ENABLING'; break; case 3: wifiState += 'ENABLED'; break; default: wifiState += 'UNKNOWN STATUS'; break; } } // Subscribe to Wi-Fi connection state changes. wifiManager.on("wifiStateChange", recvPowerNotifyFunc); // Check whether Wi-Fi is enabled. let isWifiActive = wifiManager.isWifiActive(); if (!isWifiActive) { console.info("Wi-Fi not enabled"); // Enable Wi-Fi manually. return; } wifiManager.off("wifiStateChange", recvPowerNotifyFunc); }
application-dev\connectivity\wlan\sta-development-guide.md
import { wifiManager } from '@kit.ConnectivityKit'; try { let recvWifiConnectionChangeFunc = (result:number) => { console.info("Receive wifi connection change event: " + result); } let config:wifiManager.WifiDeviceConfig = { ssid : "****", bssid : "****", preSharedKey : "****", securityType : 0 } // Update the current Wi-Fi connection status. wifiManager.on("wifiConnectionChange", recvWifiConnectionChangeFunc); // Add candidate network configurations. wifiManager.addCandidateConfig(config).then(result => { // Connect to the specified network. wifiManager.connectToCandidateConfig(result); }); if (!wifiManager.isConnected()) { console.info("Wi-Fi not connected"); } // Obtain link information. wifiManager.getLinkedInfo().then(data => { console.info("get Wi-Fi linked info: " + JSON.stringify(data)); }) // Query the signal strength. let level = wifiManager.getSignalLevel(rssi,band); console.info("level:" + JSON.stringify(level)); // Unsubscribe from Wi-Fi connection state changes. wifiManager.off("wifiConnectionChange", recvWifiConnectionChangeFunc); }
application-dev\contacts\contacts-intro.md
import { contact } from '@kit.ContactsKit'; import { BusinessError } from '@kit.BasicServicesKit';
application-dev\contacts\contacts-intro.md
contact.selectContacts({ isMultiSelect:false },(err: BusinessError, data) => { if (err) { console.error(`selectContact callback: err->${JSON.stringify(err)}`); return; } console.log(`selectContact callback: success data->${JSON.stringify(data)}`); });
application-dev\contacts\contacts-intro.md
import { common, abilityAccessCtrl, Permissions } from '@kit.AbilityKit'; import { contact } from '@kit.ContactsKit'; let context = getContext(this) as common.UIAbilityContext; const permissions: Array<Permissions> = ['ohos.permission.WRITE_CONTACTS']; abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context, permissions).then(() => { try { contact.selectContacts(); } catch(err) { console.error('errCode: ' + err.code + ', errMessage: ' + err.message); } })
application-dev\contacts\contacts-intro.md
// Sample code import { common, abilityAccessCtrl, Permissions } from '@kit.AbilityKit'; import { contact } from '@kit.ContactsKit'; @Entry @Component struct Contact { addContactByPermissions() { let context = getContext(this) as common.UIAbilityContext; const permissions: Array<Permissions> = ['ohos.permission.WRITE_CONTACTS']; const contactInfo: contact.Contact = { name: { fullName: 'Wang Xiaoming' }, phoneNumbers: [{ phoneNumber: '13912345678' }] } abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context, permissions).then(() => { try { contact.addContact(context, contactInfo, (err, data) => { if (err) { console.log('addContact callback: err->' + JSON.stringify(err)); return; } console.log('addContact callback: data->' + JSON.stringify(data)); }) } catch (err) { console.error('errCode: ' + err.code + ', errMessage: ' + err.message); } }) } build() { Row() { Column() { Button ('Add Contact') .onClick(() => { this.addContactByPermissions(); }) } .width('100%') } .height('100%') } }
application-dev\database\access-control-by-device-and-data-level.md
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { distributedKVStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); let kvManager: distributedKVStore.KVManager; let kvStore: distributedKVStore.SingleKVStore; let context = this.context; const kvManagerConfig: distributedKVStore.KVManagerConfig = { context: context, bundleName: 'com.example.datamanagertest' } try { kvManager = distributedKVStore.createKVManager(kvManagerConfig); console.info('Succeeded in creating KVManager.'); try { const options: distributedKVStore.Options = { createIfMissing: true, encrypt: true, backup: false, autoSync: false, kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, securityLevel: distributedKVStore.SecurityLevel.S3 }; kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options, (err, store: distributedKVStore.SingleKVStore) => { if (err) { console.error(`Failed to get KVStore. Code:${err.code},message:${err.message}`); return; } console.info('Succeeded in getting KVStore.'); kvStore = store; }); } catch (e) { let error = e as BusinessError; console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); } } catch (e) { let error = e as BusinessError; console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`); } } }
application-dev\database\access-control-by-device-and-data-level.md
import { UIAbility } from '@kit.AbilityKit'; import { relationalStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { async onCreate(): Promise<void> { let store: relationalStore.RdbStore | undefined = undefined; let context = this.context; try { const STORE_CONFIG: relationalStore.StoreConfig = { name: 'RdbTest.db', securityLevel: relationalStore.SecurityLevel.S3 }; store = await relationalStore.getRdbStore(context, STORE_CONFIG); console.info('Succeeded in getting RdbStore.') } catch (e) { const err = e as BusinessError; console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); } } }
application-dev\database\aip-data-intelligence-embedding.md
import { intelligence } from '@kit.ArkData';
application-dev\database\aip-data-intelligence-embedding.md
import { BusinessError } from '@kit.BasicServicesKit'; let textConfig:intelligence.ModelConfig = { version:intelligence.ModelVersion.BASIC_MODEL, isNpuAvailable:false, cachePath:"/data" } let textEmbedding:intelligence.TextEmbedding; intelligence.getTextEmbeddingModel(textConfig) .then((data:intelligence.TextEmbedding) => { console.info("Succeeded in getting TextModel"); textEmbedding = data; }) .catch((err:BusinessError) => { console.error("Failed to get TextModel and code is " + err.code); })
application-dev\database\aip-data-intelligence-embedding.md
textEmbedding.loadModel() .then(() => { console.info("Succeeded in loading Model"); }) .catch((err:BusinessError) => { console.error("Failed to load Model and code is " + err.code); })
application-dev\database\aip-data-intelligence-embedding.md
let splitConfig:intelligence.SplitConfig = { size:10, overlapRatio:0.1 } let splitText = 'text'; intelligence.splitText(splitText, splitConfig) .then((data:Array<string>) => { console.info("Succeeded in splitting Text"); }) .catch((err:BusinessError) => { console.error("Failed to split Text and code is " + err.code); })
application-dev\database\aip-data-intelligence-embedding.md
let text = 'text'; textEmbedding.getEmbedding(text) .then((data:Array<number>) => { console.info("Succeeded in getting Embedding"); }) .catch((err:BusinessError) => { console.error("Failed to get Embedding and code is " + err.code); })
application-dev\database\aip-data-intelligence-embedding.md
let batchTexts = ['text1','text2']; textEmbedding.getEmbedding(batchTexts) .then((data:Array<Array<number>>) => { console.info("Succeeded in getting Embedding"); }) .catch((err:BusinessError) => { console.error("Failed to get Embedding and code is " + err.code); })
application-dev\database\aip-data-intelligence-embedding.md
textEmbedding.releaseModel() .then(() => { console.info("Succeeded in releasing Model"); }) .catch((err:BusinessError) => { console.error("Failed to release Model and code is " + err.code); })
application-dev\database\aip-data-intelligence-embedding.md
let imageConfig:intelligence.ModelConfig = { version:intelligence.ModelVersion.BASIC_MODEL, isNpuAvailable:false, cachePath:"/data" } let imageEmbedding:intelligence.ImageEmbedding; intelligence.getImageEmbeddingModel(imageConfig) .then((data:intelligence.ImageEmbedding) => { console.info("Succeeded in getting ImageModel"); imageEmbedding = data; }) .catch((err:BusinessError) => { console.error("Failed to get ImageModel and code is " + err.code); })
application-dev\database\aip-data-intelligence-embedding.md
imageEmbedding.loadModel() .then(() => { console.info("Succeeded in loading Model"); }) .catch((err:BusinessError) => { console.error("Failed to load Model and code is " + err.code); })
application-dev\database\aip-data-intelligence-embedding.md
let image = "file://<packageName>/data/storage/el2/base/haps/entry/files/xxx.jpg"; imageEmbedding.getEmbedding(image) .then((data:Array<number>) => { console.info("Succeeded in getting Embedding"); }) .catch((err:BusinessError) => { console.error("Failed to get Embedding and code is " + err.code); })
application-dev\database\aip-data-intelligence-embedding.md
imageEmbedding.releaseModel() .then(() => { console.info("Succeeded in releasing Model"); }) .catch((err:BusinessError) => { console.error("Failed to release Model and code is " + err.code); })
application-dev\database\data-backup-and-restore.md
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { distributedKVStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); let kvManager: distributedKVStore.KVManager; let kvStore: distributedKVStore.SingleKVStore | undefined = undefined; let context = this.context; const kvManagerConfig: distributedKVStore.KVManagerConfig = { context: context, bundleName: 'com.example.datamanagertest' } try { kvManager = distributedKVStore.createKVManager(kvManagerConfig); console.info('Succeeded in creating KVManager.'); try { const options: distributedKVStore.Options = { createIfMissing: true, encrypt: true, backup: false, autoSync: false, kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, securityLevel: distributedKVStore.SecurityLevel.S3 }; kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options, (err, store: distributedKVStore.SingleKVStore) => { if (err) { console.error(`Failed to get KVStore. Code:${err.code},message:${err.message}`); return; } console.info('Succeeded in getting KVStore.'); kvStore = store; }); } catch (e) { let error = e as BusinessError; console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); } } catch (e) { let error = e as BusinessError; console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`); } if (kvStore !== undefined) { kvStore = kvStore as distributedKVStore.SingleKVStore; // Perform subsequent operations. //... } } }
application-dev\database\data-backup-and-restore.md
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value_test_string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => { if (err !== undefined) { console.error(`Fail to put data. Code:${err.code},message:${err.message}`); return; } console.info('Succeeded in putting data.'); }); } catch (e) { let error = e as BusinessError; console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); }
application-dev\database\data-backup-and-restore.md
let backupFile = 'BK001'; try { kvStore.backup(backupFile, (err) => { if (err) { console.error(`Fail to backup data.code:${err.code},message:${err.message}`); } else { console.info('Succeeded in backupping data.'); } }); } catch (e) { let error = e as BusinessError; console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); }
application-dev\database\data-backup-and-restore.md
try { kvStore.delete(KEY_TEST_STRING_ELEMENT, (err) => { if (err !== undefined) { console.error(`Fail to delete data. Code:${err.code},message:${err.message}`); return; } console.info('Succeeded in deleting data.'); }); } catch (e) { let error = e as BusinessError; console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); }
application-dev\database\data-backup-and-restore.md
try { kvStore.restore(backupFile, (err) => { if (err) { console.error(`Fail to restore data. Code:${err.code},message:${err.message}`); } else { console.info('Succeeded in restoring data.'); } }); } catch (e) { let error = e as BusinessError; console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); }
application-dev\database\data-backup-and-restore.md
let files = [backupFile]; try { kvStore.deleteBackup(files).then((data) => { console.info(`Succeed in deleting Backup. Data:filename is ${data[0]},result is ${data[1]}.`); }).catch((err: BusinessError) => { console.error(`Fail to delete Backup. Code:${err.code},message:${err.message}`); }) } catch (e) { let error = e as BusinessError; console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); }
application-dev\database\data-backup-and-restore.md
import { UIAbility } from '@kit.AbilityKit'; import { relationalStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { async onCreate(): Promise<void> { let store: relationalStore.RdbStore | undefined = undefined; let context = this.context; const STORE_CONFIG: relationalStore.StoreConfig = { name: 'RdbTest.db', securityLevel: relationalStore.SecurityLevel.S3, allowRebuild: true }; try { store = await relationalStore.getRdbStore(context, STORE_CONFIG); await store.executeSql('CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)'); console.info('Succeeded in getting RdbStore.'); } catch (e) { const err = e as BusinessError; console.error(`Failed to get RdbStore. Code:${err.code},message:${err.message}`); } if (!store) { return; } try { /** * Backup.db specifies the database backup file. By default, it is in the same directory as the RDB store. * You can also specify an absolute path, for example, /data/storage/el2/database/Backup.db. The file path must exist and will not be automatically created. */ await store.backup("Backup.db"); console.info(`Succeeded in backing up RdbStore.`); } catch (e) { const err = e as BusinessError; console.error(`Failed to backup RdbStore. Code:${err.code}, message:${err.message}`); } } }
application-dev\database\data-backup-and-restore.md
import { UIAbility } from '@kit.AbilityKit'; import { relationalStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { async onCreate(): Promise<void> { let store: relationalStore.RdbStore | undefined = undefined; let context = this.context; try { // Set haMode of StoreConfig to MAIN_REPLICA. const AUTO_BACKUP_CONFIG: relationalStore.StoreConfig = { name: "BackupRestoreTest.db", securityLevel: relationalStore.SecurityLevel.S3, haMode: relationalStore.HAMode.MAIN_REPLICA, // Data is written to the main and replica stores on a real-time basis. allowRebuild: true } // Call getRdbStore() to create an RDB store instance. store = await relationalStore.getRdbStore(context, AUTO_BACKUP_CONFIG); console.info('Succeeded in getting RdbStore.'); } catch (e) { const err = e as BusinessError; console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); } } }
application-dev\database\data-backup-and-restore.md
import { UIAbility } from '@kit.AbilityKit'; import { relationalStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { async onCreate(): Promise<void> { let store: relationalStore.RdbStore | undefined = undefined; let context = this.context; try { const STORE_CONFIG: relationalStore.StoreConfig = { name: 'RdbTest.db', securityLevel: relationalStore.SecurityLevel.S3, allowRebuild: true }; store = await relationalStore.getRdbStore(context, STORE_CONFIG); await store.executeSql('CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)'); console.info('Succeeded in getting RdbStore.'); } catch (e) { const err = e as BusinessError; console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); } } }
application-dev\database\data-backup-and-restore.md
let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); if (store != undefined) { (store as relationalStore.RdbStore).query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((result: relationalStore.ResultSet) => { let resultSet = result; try { /* ... Logic for adding, deleting, and modifying data. ... */ // Throw an exception. if (resultSet?.rowCount == -1) { resultSet ?.isColumnNull(0); } // Call other APIs such as resultSet.goToFirstRow() and resultSet.count(), which also throw exceptions. while (resultSet.goToNextRow()) { console.info(JSON.stringify(resultSet.getRow())) } resultSet.close(); } catch (err) { if (err.code === 14800011) { // Perform step 2 (close result sets and then restore data). } console.error(JSON.stringify(err)); } }) }
application-dev\database\data-backup-and-restore.md
// Obtain all opened result sets. let resultSets: Array<relationalStore.ResultSet> = []; // Call resultSet.close() to close all opened result sets. for (let resultSet of resultSets) { try { resultSet.close(); } catch (e) { if (e.code !== 14800014) { console.error(`Code:${e.code}, message:${e.message}`); } } }
application-dev\database\data-backup-and-restore.md
import { UIAbility } from '@kit.AbilityKit'; import { relationalStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; import { fileIo } from '@kit.CoreFileKit'; export default class EntryAbility extends UIAbility { async onCreate(): Promise<void> { let store: relationalStore.RdbStore | undefined = undefined; let context = this.context; let STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S3, allowRebuild: true } try { /** * Backup.db specifies the database backup file. By default, it is in the same directory as the current database. * If an absolute path is specified for the database backup file, for example, /data/storage/el2/database/Backup.db, pass in the absolute path. */ let backupFilePath = context.databaseDir + '/rdb/Backup.db'; const backupExist = await fileIo.access(backupFilePath); if (!backupExist) { console.info("Backup is not exist."); // Open the rebuilt RDB store and create tables. // Generate data. return; } } catch (e) { console.error(`Code:${e.code}, message:${e.message}`); } try { store = await relationalStore.getRdbStore(context, STORE_CONFIG); // Call restore() to restore data. await store.restore("Backup.db"); console.log("Restore from back success.") } catch (e) { const err = e as BusinessError; console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); } } }
application-dev\database\data-backup-and-restore.md
if (store !== undefined) { try { // Add, delete, modify, and query data. } catch (err) { if (err.code == 14800011) { // Obtain all opened result sets. let resultSets: Array<relationalStore.ResultSet> = []; // Call resultSet.close() to close all opened result sets. for (let resultSet of resultSets) { try { resultSet.close(); } catch (e) { if (e.code !== 14800014) { console.info(`Code:${err.code}, message:${err.message}`); } } } (store as relationalStore.RdbStore).restore("Backup.db", (err: BusinessError) => { if (err) { console.error(`Failed to restore RdbStore. Code:${err.code}, message:${err.message}`); return; } console.info(`Succeeded in restoring RdbStore.`); }) } console.info(`Code:${err.code}, message:${err.message}`); } }
application-dev\database\data-encryption.md
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { distributedKVStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); let kvManager: distributedKVStore.KVManager | undefined = undefined; let kvStore: distributedKVStore.SingleKVStore | undefined = undefined; let context = this.context; const kvManagerConfig: distributedKVStore.KVManagerConfig = { context: context, bundleName: 'com.example.datamanagertest', } try { kvManager = distributedKVStore.createKVManager(kvManagerConfig); console.info('Succeeded in creating KVManager.'); } catch (e) { let error = e as BusinessError; console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`); } if (kvManager !== undefined) { kvManager = kvManager as distributedKVStore.KVManager; try { const options: distributedKVStore.Options = { createIfMissing: true, // Whether to encrypt the KV store. encrypt: true, backup: false, autoSync: false, kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, securityLevel: distributedKVStore.SecurityLevel.S3 }; kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options, (err, store: distributedKVStore.SingleKVStore) => { if (err) { console.error(`Fail to get KVStore. Code:${err.code},message:${err.message}`); return; } console.info('Succeeded in getting KVStore.'); kvStore = store; }); } catch (e) { let error = e as BusinessError; console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); } } if (kvStore !== undefined) { kvStore = kvStore as distributedKVStore.SingleKVStore; // Perform subsequent operations. //... } } }
application-dev\database\data-encryption.md
import { UIAbility } from '@kit.AbilityKit'; import { relationalStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { async onCreate(): Promise<void> { let store: relationalStore.RdbStore | undefined = undefined; let context = this.context; try { const STORE_CONFIG: relationalStore.StoreConfig = { name: 'RdbTest.db', securityLevel: relationalStore.SecurityLevel.S3, encrypt: true }; store = await relationalStore.getRdbStore(context, STORE_CONFIG); console.info('Succeeded in getting RdbStore.'); } catch (e) { const err = e as BusinessError; console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); } } }
application-dev\database\data-encryption.md
import { UIAbility } from '@kit.AbilityKit'; import { relationalStore } from '@kit.ArkData'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { async onCreate(): Promise<void> { let store: relationalStore.RdbStore | undefined = undefined; let context = this.context; // Initialize the key to be used. let key = new Uint8Array(32); for (let i = 0; i < 32; i++) { key[i] = i; } // Initialize the encryption algorithm. const CRYPTO_PARAM: relationalStore.CryptoParam = { encryptionKey: key, // (Mandatory) Key used to open the encrypted database. If this parameter is not specified, the database generates and saves the key and uses the generated key to open the database file. iterationCount: 25000, // (Optional) Number of iterations. The value must be greater than or equal to 0. If this parameter is not specified or is set to 0, the default value 10000 and the default encryption algorithm are used. encryptionAlgo: relationalStore.EncryptionAlgo.AES_256_CBC, // (Optional) Encryption/Decryption algorithm. If this parameter is not specified, the default algorithm AES_256_GCM is used. hmacAlgo: relationalStore.HmacAlgo.SHA256, // (Optional) HMAC algorithm. If this parameter is not specified, the default value SHA256 is used. kdfAlgo: relationalStore.KdfAlgo.KDF_SHA512, // (Optional) KDF algorithm. If this parameter is not specified, the default value (same as the HMAC algorithm) is used. cryptoPageSize: 2048 // (Optional) Page size used for encryption/decryption. The value must be an integer within the range of 1024 to 65536 and a power of 2. The default value is 1024. } const STORE_CONFIG: relationalStore.StoreConfig = { name: "encrypted.db", securityLevel: relationalStore.SecurityLevel.S3, encrypt: true, cryptoParam: CRYPTO_PARAM } try { let store = await relationalStore.getRdbStore(context, STORE_CONFIG); if (store == null) { console.error('Failed to get RdbStore.'); } else { console.info('Succeeded in getting RdbStore.'); } // Clear the key. CRYPTO_PARAM.encryptionKey.fill(0); } catch (e) { const err = e as BusinessError; console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); } } }
application-dev\database\data-persistence-by-graph-store.md
const CREATE_GRAPH = "CREATE GRAPH test { (person:Person {name STRING, age INT}),(person)-[:Friend {year INT}]->(person) };" const INSERT_VERTEX = "INSERT (:Person {name: 'name_1', age: 11});" const QUERY_VERTEX = "MATCH (person:Person) RETURN person;" const QUERY_EDGE = "MATCH ()-[relation:Friend]->() RETURN relation;" const QUERY_PATH = "MATCH path=(a:Person {name: 'name_1'})-[]->{2, 2}(b:Person {name: 'name_3'}) RETURN path;"
application-dev\database\data-persistence-by-graph-store.md
import { graphStore } from '@kit.ArkData'; // Import the graphStore module. import { UIAbility } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { window } from '@kit.ArkUI'; let store: graphStore.GraphStore | null = null; const STORE_CONFIG: graphStore.StoreConfig = { name: "testGraphDb," // Database file name without the file name extension .db. securityLevel: graphStore.SecurityLevel.S2, // Database security level. encrypt: false, // Whether to encrypt the database. This parameter is optional. By default, the database is not encrypted. }; const STORE_CONFIG_NEW: graphStore.StoreConfig = { name: "testGraphDb", // The database file name must be the same as the file name used for creating the database. securityLevel: graphStore.SecurityLevel.S3, encrypt: true, }; // In this example, EntryAbility is used to obtain a GraphStore instance. You can use other implementations as required. class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { graphStore.getStore(this.context, STORE_CONFIG).then(async (gdb: graphStore.GraphStore) => { store = gdb; console.info('Get GraphStore successfully.') }).catch((err: BusinessError) => { console.error(`Get GraphStore failed, code is ${err.code}, message is ${err.message}`); }) // Before changing the database security level and encryption property, call close() to close the database. if(store != null) { (store as graphStore.GraphStore).close().then(() => { console.info(`Close successfully`); graphStore.getStore(this.context, STORE_CONFIG_NEW).then(async (gdb: graphStore.GraphStore) => { store = gdb; console.info('Update StoreConfig successfully.') }).catch((err: BusinessError) => { console.error(`Update StoreConfig failed, code is ${err.code}, message is ${err.message}`); }) }).catch ((err: BusinessError) => { console.error(`Close failed, code is ${err.code}, message is ${err.message}`); }) } } }