or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ai-ml-apis.mdapp-page-lifecycle.mdbluetooth-nfc-apis.mdcanvas-graphics.mdcloud-services.mdcomponent-system.mdcore-apis.mddevice-hardware-apis.mdevent-system.mdindex.mdpayment-apis.md

bluetooth-nfc-apis.mddocs/

0

# Bluetooth & NFC APIs

1

2

Comprehensive Bluetooth Low Energy (BLE) and Near Field Communication (NFC) APIs for WeChat Mini Programs, enabling IoT device integration and smart device connectivity.

3

4

## Capabilities

5

6

### Bluetooth Adapter Management

7

8

Core Bluetooth adapter initialization and management for WeChat Mini Programs.

9

10

```typescript { .api }

11

/**

12

* Initialize Bluetooth adapter

13

* @param option - Bluetooth adapter configuration

14

*/

15

function openBluetoothAdapter<T extends OpenBluetoothAdapterOption = OpenBluetoothAdapterOption>(

16

option?: T

17

): PromisifySuccessResult<T, OpenBluetoothAdapterOption>;

18

19

/**

20

* Close Bluetooth adapter and release resources

21

* @param option - Close adapter configuration

22

*/

23

function closeBluetoothAdapter<T extends CloseBluetoothAdapterOption = CloseBluetoothAdapterOption>(

24

option?: T

25

): PromisifySuccessResult<T, CloseBluetoothAdapterOption>;

26

27

/**

28

* Get current Bluetooth adapter state

29

* @param option - Get adapter state configuration

30

*/

31

function getBluetoothAdapterState<T extends GetBluetoothAdapterStateOption = GetBluetoothAdapterStateOption>(

32

option?: T

33

): PromisifySuccessResult<T, GetBluetoothAdapterStateOption>;

34

35

interface OpenBluetoothAdapterOption {

36

/** Operation mode for adapter */

37

mode?: 'central' | 'peripheral';

38

/** Success callback */

39

success?(res: OpenBluetoothAdapterSuccessCallbackResult): void;

40

/** Failure callback */

41

fail?(res: any): void;

42

/** Completion callback */

43

complete?(res: any): void;

44

}

45

46

interface GetBluetoothAdapterStateSuccessCallbackResult {

47

/** Whether Bluetooth adapter is available */

48

available: boolean;

49

/** Whether device discovery is in progress */

50

discovering: boolean;

51

/** Error message if adapter unavailable */

52

errMsg: string;

53

}

54

```

55

56

**Usage Examples:**

57

58

```typescript

59

// Initialize Bluetooth adapter

60

wx.openBluetoothAdapter({

61

success(res) {

62

console.log('Bluetooth adapter initialized:', res);

63

},

64

fail(err) {

65

console.error('Failed to initialize Bluetooth:', err);

66

}

67

});

68

69

// Check adapter state

70

wx.getBluetoothAdapterState({

71

success(res) {

72

console.log('Bluetooth available:', res.available);

73

console.log('Currently discovering:', res.discovering);

74

}

75

});

76

77

// Close adapter when done

78

wx.closeBluetoothAdapter({

79

success(res) {

80

console.log('Bluetooth adapter closed');

81

}

82

});

83

```

84

85

### Bluetooth Device Discovery

86

87

Device discovery and management for finding nearby Bluetooth devices.

88

89

```typescript { .api }

90

/**

91

* Start discovering Bluetooth devices

92

* @param option - Discovery configuration

93

*/

94

function startBluetoothDevicesDiscovery<T extends StartBluetoothDevicesDiscoveryOption = StartBluetoothDevicesDiscoveryOption>(

95

option?: T

96

): PromisifySuccessResult<T, StartBluetoothDevicesDiscoveryOption>;

97

98

/**

99

* Stop discovering Bluetooth devices

100

* @param option - Stop discovery configuration

101

*/

102

function stopBluetoothDevicesDiscovery<T extends StopBluetoothDevicesDiscoveryOption = StopBluetoothDevicesDiscoveryOption>(

103

option?: T

104

): PromisifySuccessResult<T, StopBluetoothDevicesDiscoveryOption>;

105

106

/**

107

* Get discovered Bluetooth devices

108

* @param option - Get devices configuration

109

*/

110

function getBluetoothDevices<T extends GetBluetoothDevicesOption = GetBluetoothDevicesOption>(

111

option?: T

112

): PromisifySuccessResult<T, GetBluetoothDevicesOption>;

113

114

interface StartBluetoothDevicesDiscoveryOption {

115

/** List of service UUIDs to filter devices */

116

services?: string[];

117

/** Whether to allow duplicate device reports */

118

allowDuplicatesKey?: boolean;

119

/** Discovery interval in milliseconds */

120

interval?: number;

121

/** Discovery power level */

122

powerLevel?: 'low' | 'balanced' | 'high';

123

/** Success callback */

124

success?(res: any): void;

125

/** Failure callback */

126

fail?(res: any): void;

127

/** Completion callback */

128

complete?(res: any): void;

129

}

130

131

interface GetBluetoothDevicesSuccessCallbackResult {

132

/** Array of discovered devices */

133

devices: BluetoothDeviceInfo[];

134

/** Success message */

135

errMsg: string;

136

}

137

138

interface BluetoothDeviceInfo {

139

/** Device ID */

140

deviceId: string;

141

/** Device name */

142

name: string;

143

/** Device MAC address */

144

RSSI: number;

145

/** Advertisement data */

146

advertisData: ArrayBuffer;

147

/** Scan response data */

148

advertisServiceUUIDs: string[];

149

/** Local name */

150

localName: string;

151

/** Service data */

152

serviceData: Record<string, ArrayBuffer>;

153

}

154

```

155

156

**Usage Examples:**

157

158

```typescript

159

// Start device discovery

160

wx.startBluetoothDevicesDiscovery({

161

services: ['FEE7'], // Filter for specific service UUID

162

allowDuplicatesKey: false,

163

success(res) {

164

console.log('Started device discovery');

165

}

166

});

167

168

// Listen for device found events

169

wx.onBluetoothDeviceFound((res) => {

170

console.log('Found devices:', res.devices);

171

res.devices.forEach(device => {

172

console.log(`Device: ${device.name} (${device.deviceId})`);

173

console.log(`RSSI: ${device.RSSI}`);

174

});

175

});

176

177

// Get all discovered devices

178

wx.getBluetoothDevices({

179

success(res) {

180

console.log('All discovered devices:', res.devices);

181

}

182

});

183

184

// Stop discovery when done

185

wx.stopBluetoothDevicesDiscovery({

186

success(res) {

187

console.log('Stopped device discovery');

188

}

189

});

190

```

191

192

### BLE Connection Management

193

194

Bluetooth Low Energy connection establishment and management.

195

196

```typescript { .api }

197

/**

198

* Create BLE connection to device

199

* @param option - BLE connection configuration

200

*/

201

function createBLEConnection<T extends CreateBLEConnectionOption = CreateBLEConnectionOption>(

202

option: T

203

): PromisifySuccessResult<T, CreateBLEConnectionOption>;

204

205

/**

206

* Close BLE connection to device

207

* @param option - Close BLE connection configuration

208

*/

209

function closeBLEConnection<T extends CloseBLEConnectionOption = CloseBLEConnectionOption>(

210

option: T

211

): PromisifySuccessResult<T, CloseBLEConnectionOption>;

212

213

/**

214

* Get BLE device services

215

* @param option - Get services configuration

216

*/

217

function getBLEDeviceServices<T extends GetBLEDeviceServicesOption = GetBLEDeviceServicesOption>(

218

option: T

219

): PromisifySuccessResult<T, GetBLEDeviceServicesOption>;

220

221

interface CreateBLEConnectionOption {

222

/** Device ID from discovery */

223

deviceId: string;

224

/** Connection timeout in milliseconds */

225

timeout?: number;

226

/** Success callback */

227

success?(res: any): void;

228

/** Failure callback */

229

fail?(res: any): void;

230

/** Completion callback */

231

complete?(res: any): void;

232

}

233

234

interface GetBLEDeviceServicesSuccessCallbackResult {

235

/** Array of device services */

236

services: BLEService[];

237

/** Success message */

238

errMsg: string;

239

}

240

241

interface BLEService {

242

/** Service UUID */

243

uuid: string;

244

/** Whether service is primary */

245

isPrimary: boolean;

246

}

247

```

248

249

**Usage Examples:**

250

251

```typescript

252

// Connect to BLE device

253

wx.createBLEConnection({

254

deviceId: 'device_id_from_discovery',

255

success(res) {

256

console.log('BLE connection established');

257

258

// Get device services

259

wx.getBLEDeviceServices({

260

deviceId: 'device_id_from_discovery',

261

success(res) {

262

console.log('Device services:', res.services);

263

res.services.forEach(service => {

264

console.log(`Service UUID: ${service.uuid}`);

265

});

266

}

267

});

268

},

269

fail(err) {

270

console.error('BLE connection failed:', err);

271

}

272

});

273

274

// Monitor connection state changes

275

wx.onBLEConnectionStateChange((res) => {

276

console.log('Connection state changed:');

277

console.log(`Device: ${res.deviceId}`);

278

console.log(`Connected: ${res.connected}`);

279

280

if (!res.connected) {

281

console.log('Device disconnected, attempting reconnection...');

282

// Implement reconnection logic

283

}

284

});

285

286

// Close connection when done

287

wx.closeBLEConnection({

288

deviceId: 'device_id_from_discovery',

289

success(res) {

290

console.log('BLE connection closed');

291

}

292

});

293

```

294

295

### BLE Characteristic Operations

296

297

BLE characteristic discovery, reading, writing, and notification management.

298

299

```typescript { .api }

300

/**

301

* Get BLE device characteristics for a service

302

* @param option - Get characteristics configuration

303

*/

304

function getBLEDeviceCharacteristics<T extends GetBLEDeviceCharacteristicsOption = GetBLEDeviceCharacteristicsOption>(

305

option: T

306

): PromisifySuccessResult<T, GetBLEDeviceCharacteristicsOption>;

307

308

/**

309

* Read BLE characteristic value

310

* @param option - Read characteristic configuration

311

*/

312

function readBLECharacteristicValue<T extends ReadBLECharacteristicValueOption = ReadBLECharacteristicValueOption>(

313

option: T

314

): PromisifySuccessResult<T, ReadBLECharacteristicValueOption>;

315

316

/**

317

* Write BLE characteristic value

318

* @param option - Write characteristic configuration

319

*/

320

function writeBLECharacteristicValue<T extends WriteBLECharacteristicValueOption = WriteBLECharacteristicValueOption>(

321

option: T

322

): PromisifySuccessResult<T, WriteBLECharacteristicValueOption>;

323

324

/**

325

* Enable/disable BLE characteristic value change notifications

326

* @param option - Notification configuration

327

*/

328

function notifyBLECharacteristicValueChange<T extends NotifyBLECharacteristicValueChangeOption = NotifyBLECharacteristicValueChangeOption>(

329

option: T

330

): PromisifySuccessResult<T, NotifyBLECharacteristicValueChangeOption>;

331

332

interface GetBLEDeviceCharacteristicsOption {

333

/** Device ID */

334

deviceId: string;

335

/** Service UUID */

336

serviceId: string;

337

/** Success callback */

338

success?(res: GetBLEDeviceCharacteristicsSuccessCallbackResult): void;

339

/** Failure callback */

340

fail?(res: any): void;

341

/** Completion callback */

342

complete?(res: any): void;

343

}

344

345

interface GetBLEDeviceCharacteristicsSuccessCallbackResult {

346

/** Array of characteristics */

347

characteristics: BLECharacteristic[];

348

/** Success message */

349

errMsg: string;

350

}

351

352

interface BLECharacteristic {

353

/** Characteristic UUID */

354

uuid: string;

355

/** Characteristic properties */

356

properties: BLECharacteristicProperties;

357

}

358

359

interface BLECharacteristicProperties {

360

/** Supports read operations */

361

read: boolean;

362

/** Supports write operations */

363

write: boolean;

364

/** Supports notifications */

365

notify: boolean;

366

/** Supports indications */

367

indicate: boolean;

368

}

369

370

interface WriteBLECharacteristicValueOption {

371

/** Device ID */

372

deviceId: string;

373

/** Service UUID */

374

serviceId: string;

375

/** Characteristic UUID */

376

characteristicId: string;

377

/** Data to write */

378

value: ArrayBuffer;

379

/** Success callback */

380

success?(res: any): void;

381

/** Failure callback */

382

fail?(res: any): void;

383

/** Completion callback */

384

complete?(res: any): void;

385

}

386

387

interface NotifyBLECharacteristicValueChangeOption {

388

/** Device ID */

389

deviceId: string;

390

/** Service UUID */

391

serviceId: string;

392

/** Characteristic UUID */

393

characteristicId: string;

394

/** Enable or disable notifications */

395

state: boolean;

396

/** Notification type */

397

type?: 'notification' | 'indication';

398

/** Success callback */

399

success?(res: any): void;

400

/** Failure callback */

401

fail?(res: any): void;

402

/** Completion callback */

403

complete?(res: any): void;

404

}

405

```

406

407

**Usage Examples:**

408

409

```typescript

410

// Get characteristics for a service

411

wx.getBLEDeviceCharacteristics({

412

deviceId: 'device_id',

413

serviceId: 'service_uuid',

414

success(res) {

415

console.log('Device characteristics:', res.characteristics);

416

417

res.characteristics.forEach(char => {

418

console.log(`Characteristic: ${char.uuid}`);

419

console.log(`Properties:`, char.properties);

420

421

// Enable notifications if supported

422

if (char.properties.notify) {

423

wx.notifyBLECharacteristicValueChange({

424

deviceId: 'device_id',

425

serviceId: 'service_uuid',

426

characteristicId: char.uuid,

427

state: true,

428

success(res) {

429

console.log('Notifications enabled for', char.uuid);

430

}

431

});

432

}

433

});

434

}

435

});

436

437

// Listen for characteristic value changes

438

wx.onBLECharacteristicValueChange((res) => {

439

console.log('Characteristic value changed:');

440

console.log(`Device: ${res.deviceId}`);

441

console.log(`Service: ${res.serviceId}`);

442

console.log(`Characteristic: ${res.characteristicId}`);

443

console.log(`Value:`, res.value);

444

445

// Process the received data

446

const dataView = new DataView(res.value);

447

const temperature = dataView.getFloat32(0, true);

448

console.log(`Temperature: ${temperature}°C`);

449

});

450

451

// Write data to characteristic

452

const data = new ArrayBuffer(4);

453

const dataView = new DataView(data);

454

dataView.setUint32(0, 12345, true);

455

456

wx.writeBLECharacteristicValue({

457

deviceId: 'device_id',

458

serviceId: 'service_uuid',

459

characteristicId: 'characteristic_uuid',

460

value: data,

461

success(res) {

462

console.log('Data written successfully');

463

},

464

fail(err) {

465

console.error('Write failed:', err);

466

}

467

});

468

469

// Read characteristic value

470

wx.readBLECharacteristicValue({

471

deviceId: 'device_id',

472

serviceId: 'service_uuid',

473

characteristicId: 'characteristic_uuid',

474

success(res) {

475

console.log('Read successful');

476

}

477

});

478

```

479

480

### NFC Support

481

482

Near Field Communication functionality for WeChat Mini Programs.

483

484

```typescript { .api }

485

/**

486

* Get NFC adapter instance

487

* @returns NFC adapter for tag operations

488

*/

489

function getNFCAdapter(): NFCAdapter;

490

491

interface NFCAdapter {

492

/**

493

* Start NFC discovery session

494

* @param option - NFC discovery configuration

495

*/

496

startDiscovery(option: NFCStartDiscoveryOption): Promise<any>;

497

498

/**

499

* Stop NFC discovery session

500

* @param option - Stop discovery configuration

501

*/

502

stopDiscovery(option?: NFCStopDiscoveryOption): Promise<any>;

503

504

/**

505

* Listen for NFC tag discovery events

506

* @param callback - Tag discovery callback

507

*/

508

onDiscovered(callback: (res: NFCTagInfo) => void): void;

509

510

/**

511

* Remove NFC tag discovery listeners

512

* @param callback - Callback to remove

513

*/

514

offDiscovered(callback?: (res: NFCTagInfo) => void): void;

515

}

516

517

interface NFCStartDiscoveryOption {

518

/** PowerLevel for NFC discovery */

519

powerLevel?: 'low' | 'balanced' | 'high';

520

/** Array of tag technologies to discover */

521

techTypes?: NFCTechType[];

522

}

523

524

interface NFCTagInfo {

525

/** NFC tag ID */

526

id: string;

527

/** Supported technologies */

528

techs: NFCTechType[];

529

/** NDEF messages if available */

530

messages?: NDEFMessage[];

531

}

532

533

type NFCTechType = 'NfcA' | 'NfcB' | 'NfcF' | 'NfcV' | 'IsoDep' | 'MifareClassic' | 'MifareUltralight' | 'Ndef' | 'NdefFormatable';

534

535

interface NDEFMessage {

536

/** NDEF records */

537

records: NDEFRecord[];

538

}

539

540

interface NDEFRecord {

541

/** Record type */

542

type: ArrayBuffer;

543

/** Record ID */

544

id?: ArrayBuffer;

545

/** Record payload */

546

payload: ArrayBuffer;

547

}

548

```

549

550

**Usage Examples:**

551

552

```typescript

553

// Initialize NFC adapter

554

const nfcAdapter = wx.getNFCAdapter();

555

556

// Start NFC discovery

557

nfcAdapter.startDiscovery({

558

techTypes: ['Ndef', 'NfcA'],

559

powerLevel: 'balanced'

560

}).then(() => {

561

console.log('NFC discovery started');

562

}).catch(err => {

563

console.error('Failed to start NFC discovery:', err);

564

});

565

566

// Listen for NFC tag discovery

567

nfcAdapter.onDiscovered((res) => {

568

console.log('NFC tag discovered:');

569

console.log(`Tag ID: ${res.id}`);

570

console.log(`Technologies: ${res.techs.join(', ')}`);

571

572

if (res.messages) {

573

res.messages.forEach((message, msgIndex) => {

574

console.log(`Message ${msgIndex}:`);

575

message.records.forEach((record, recIndex) => {

576

console.log(` Record ${recIndex}:`);

577

console.log(` Type: ${new TextDecoder().decode(record.type)}`);

578

console.log(` Payload: ${new TextDecoder().decode(record.payload)}`);

579

});

580

});

581

}

582

});

583

584

// Stop NFC discovery when done

585

setTimeout(() => {

586

nfcAdapter.stopDiscovery().then(() => {

587

console.log('NFC discovery stopped');

588

});

589

}, 30000); // Stop after 30 seconds

590

```

591

592

## Event Listeners

593

594

```typescript { .api }

595

// Bluetooth event listeners

596

function onBluetoothAdapterStateChange(callback: (res: BluetoothAdapterStateInfo) => void): void;

597

function offBluetoothAdapterStateChange(callback?: (res: BluetoothAdapterStateInfo) => void): void;

598

599

function onBluetoothDeviceFound(callback: (res: BluetoothDeviceFoundInfo) => void): void;

600

function offBluetoothDeviceFound(callback?: (res: BluetoothDeviceFoundInfo) => void): void;

601

602

function onBLEConnectionStateChange(callback: (res: BLEConnectionStateInfo) => void): void;

603

function offBLEConnectionStateChange(callback?: (res: BLEConnectionStateInfo) => void): void;

604

605

function onBLECharacteristicValueChange(callback: (res: BLECharacteristicValueInfo) => void): void;

606

function offBLECharacteristicValueChange(callback?: (res: BLECharacteristicValueInfo) => void): void;

607

608

interface BluetoothAdapterStateInfo {

609

/** Whether adapter is available */

610

available: boolean;

611

/** Whether discovery is active */

612

discovering: boolean;

613

}

614

615

interface BluetoothDeviceFoundInfo {

616

/** Array of newly found devices */

617

devices: BluetoothDeviceInfo[];

618

}

619

620

interface BLEConnectionStateInfo {

621

/** Device ID */

622

deviceId: string;

623

/** Connection state */

624

connected: boolean;

625

}

626

627

interface BLECharacteristicValueInfo {

628

/** Device ID */

629

deviceId: string;

630

/** Service UUID */

631

serviceId: string;

632

/** Characteristic UUID */

633

characteristicId: string;

634

/** Characteristic value */

635

value: ArrayBuffer;

636

}

637

```