CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-miniprogram-api-typings

Type definitions for APIs of WeChat Mini Program in TypeScript

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

bluetooth-nfc-apis.mddocs/

Bluetooth & NFC APIs

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

Capabilities

Bluetooth Adapter Management

Core Bluetooth adapter initialization and management for WeChat Mini Programs.

/**
 * Initialize Bluetooth adapter
 * @param option - Bluetooth adapter configuration
 */
function openBluetoothAdapter<T extends OpenBluetoothAdapterOption = OpenBluetoothAdapterOption>(
  option?: T
): PromisifySuccessResult<T, OpenBluetoothAdapterOption>;

/**
 * Close Bluetooth adapter and release resources
 * @param option - Close adapter configuration
 */
function closeBluetoothAdapter<T extends CloseBluetoothAdapterOption = CloseBluetoothAdapterOption>(
  option?: T
): PromisifySuccessResult<T, CloseBluetoothAdapterOption>;

/**
 * Get current Bluetooth adapter state
 * @param option - Get adapter state configuration
 */
function getBluetoothAdapterState<T extends GetBluetoothAdapterStateOption = GetBluetoothAdapterStateOption>(
  option?: T
): PromisifySuccessResult<T, GetBluetoothAdapterStateOption>;

interface OpenBluetoothAdapterOption {
  /** Operation mode for adapter */
  mode?: 'central' | 'peripheral';
  /** Success callback */
  success?(res: OpenBluetoothAdapterSuccessCallbackResult): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface GetBluetoothAdapterStateSuccessCallbackResult {
  /** Whether Bluetooth adapter is available */
  available: boolean;
  /** Whether device discovery is in progress */
  discovering: boolean;
  /** Error message if adapter unavailable */
  errMsg: string;
}

Usage Examples:

// Initialize Bluetooth adapter
wx.openBluetoothAdapter({
  success(res) {
    console.log('Bluetooth adapter initialized:', res);
  },
  fail(err) {
    console.error('Failed to initialize Bluetooth:', err);
  }
});

// Check adapter state
wx.getBluetoothAdapterState({
  success(res) {
    console.log('Bluetooth available:', res.available);
    console.log('Currently discovering:', res.discovering);
  }
});

// Close adapter when done
wx.closeBluetoothAdapter({
  success(res) {
    console.log('Bluetooth adapter closed');
  }
});

Bluetooth Device Discovery

Device discovery and management for finding nearby Bluetooth devices.

/**
 * Start discovering Bluetooth devices
 * @param option - Discovery configuration
 */
function startBluetoothDevicesDiscovery<T extends StartBluetoothDevicesDiscoveryOption = StartBluetoothDevicesDiscoveryOption>(
  option?: T
): PromisifySuccessResult<T, StartBluetoothDevicesDiscoveryOption>;

/**
 * Stop discovering Bluetooth devices
 * @param option - Stop discovery configuration
 */
function stopBluetoothDevicesDiscovery<T extends StopBluetoothDevicesDiscoveryOption = StopBluetoothDevicesDiscoveryOption>(
  option?: T
): PromisifySuccessResult<T, StopBluetoothDevicesDiscoveryOption>;

/**
 * Get discovered Bluetooth devices
 * @param option - Get devices configuration
 */
function getBluetoothDevices<T extends GetBluetoothDevicesOption = GetBluetoothDevicesOption>(
  option?: T
): PromisifySuccessResult<T, GetBluetoothDevicesOption>;

interface StartBluetoothDevicesDiscoveryOption {
  /** List of service UUIDs to filter devices */
  services?: string[];
  /** Whether to allow duplicate device reports */
  allowDuplicatesKey?: boolean;
  /** Discovery interval in milliseconds */
  interval?: number;
  /** Discovery power level */
  powerLevel?: 'low' | 'balanced' | 'high';
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface GetBluetoothDevicesSuccessCallbackResult {
  /** Array of discovered devices */
  devices: BluetoothDeviceInfo[];
  /** Success message */
  errMsg: string;
}

interface BluetoothDeviceInfo {
  /** Device ID */
  deviceId: string;
  /** Device name */
  name: string;
  /** Device MAC address */
  RSSI: number;
  /** Advertisement data */
  advertisData: ArrayBuffer;
  /** Scan response data */
  advertisServiceUUIDs: string[];
  /** Local name */
  localName: string;
  /** Service data */
  serviceData: Record<string, ArrayBuffer>;
}

Usage Examples:

// Start device discovery
wx.startBluetoothDevicesDiscovery({
  services: ['FEE7'], // Filter for specific service UUID
  allowDuplicatesKey: false,
  success(res) {
    console.log('Started device discovery');
  }
});

// Listen for device found events
wx.onBluetoothDeviceFound((res) => {
  console.log('Found devices:', res.devices);
  res.devices.forEach(device => {
    console.log(`Device: ${device.name} (${device.deviceId})`);
    console.log(`RSSI: ${device.RSSI}`);
  });
});

// Get all discovered devices
wx.getBluetoothDevices({
  success(res) {
    console.log('All discovered devices:', res.devices);
  }
});

// Stop discovery when done
wx.stopBluetoothDevicesDiscovery({
  success(res) {
    console.log('Stopped device discovery');
  }
});

BLE Connection Management

Bluetooth Low Energy connection establishment and management.

/**
 * Create BLE connection to device
 * @param option - BLE connection configuration
 */
function createBLEConnection<T extends CreateBLEConnectionOption = CreateBLEConnectionOption>(
  option: T
): PromisifySuccessResult<T, CreateBLEConnectionOption>;

/**
 * Close BLE connection to device
 * @param option - Close BLE connection configuration
 */
function closeBLEConnection<T extends CloseBLEConnectionOption = CloseBLEConnectionOption>(
  option: T
): PromisifySuccessResult<T, CloseBLEConnectionOption>;

/**
 * Get BLE device services
 * @param option - Get services configuration
 */
function getBLEDeviceServices<T extends GetBLEDeviceServicesOption = GetBLEDeviceServicesOption>(
  option: T
): PromisifySuccessResult<T, GetBLEDeviceServicesOption>;

interface CreateBLEConnectionOption {
  /** Device ID from discovery */
  deviceId: string;
  /** Connection timeout in milliseconds */
  timeout?: number;
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface GetBLEDeviceServicesSuccessCallbackResult {
  /** Array of device services */
  services: BLEService[];
  /** Success message */
  errMsg: string;
}

interface BLEService {
  /** Service UUID */
  uuid: string;
  /** Whether service is primary */
  isPrimary: boolean;
}

Usage Examples:

// Connect to BLE device
wx.createBLEConnection({
  deviceId: 'device_id_from_discovery',
  success(res) {
    console.log('BLE connection established');
    
    // Get device services
    wx.getBLEDeviceServices({
      deviceId: 'device_id_from_discovery',
      success(res) {
        console.log('Device services:', res.services);
        res.services.forEach(service => {
          console.log(`Service UUID: ${service.uuid}`);
        });
      }
    });
  },
  fail(err) {
    console.error('BLE connection failed:', err);
  }
});

// Monitor connection state changes
wx.onBLEConnectionStateChange((res) => {
  console.log('Connection state changed:');
  console.log(`Device: ${res.deviceId}`);
  console.log(`Connected: ${res.connected}`);
  
  if (!res.connected) {
    console.log('Device disconnected, attempting reconnection...');
    // Implement reconnection logic
  }
});

// Close connection when done
wx.closeBLEConnection({
  deviceId: 'device_id_from_discovery',
  success(res) {
    console.log('BLE connection closed');
  }
});

BLE Characteristic Operations

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

/**
 * Get BLE device characteristics for a service
 * @param option - Get characteristics configuration
 */
function getBLEDeviceCharacteristics<T extends GetBLEDeviceCharacteristicsOption = GetBLEDeviceCharacteristicsOption>(
  option: T
): PromisifySuccessResult<T, GetBLEDeviceCharacteristicsOption>;

/**
 * Read BLE characteristic value
 * @param option - Read characteristic configuration
 */
function readBLECharacteristicValue<T extends ReadBLECharacteristicValueOption = ReadBLECharacteristicValueOption>(
  option: T
): PromisifySuccessResult<T, ReadBLECharacteristicValueOption>;

/**
 * Write BLE characteristic value
 * @param option - Write characteristic configuration
 */
function writeBLECharacteristicValue<T extends WriteBLECharacteristicValueOption = WriteBLECharacteristicValueOption>(
  option: T
): PromisifySuccessResult<T, WriteBLECharacteristicValueOption>;

/**
 * Enable/disable BLE characteristic value change notifications
 * @param option - Notification configuration
 */
function notifyBLECharacteristicValueChange<T extends NotifyBLECharacteristicValueChangeOption = NotifyBLECharacteristicValueChangeOption>(
  option: T
): PromisifySuccessResult<T, NotifyBLECharacteristicValueChangeOption>;

interface GetBLEDeviceCharacteristicsOption {
  /** Device ID */
  deviceId: string;
  /** Service UUID */
  serviceId: string;
  /** Success callback */
  success?(res: GetBLEDeviceCharacteristicsSuccessCallbackResult): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface GetBLEDeviceCharacteristicsSuccessCallbackResult {
  /** Array of characteristics */
  characteristics: BLECharacteristic[];
  /** Success message */
  errMsg: string;
}

interface BLECharacteristic {
  /** Characteristic UUID */
  uuid: string;
  /** Characteristic properties */
  properties: BLECharacteristicProperties;
}

interface BLECharacteristicProperties {
  /** Supports read operations */
  read: boolean;
  /** Supports write operations */
  write: boolean;
  /** Supports notifications */
  notify: boolean;
  /** Supports indications */
  indicate: boolean;
}

interface WriteBLECharacteristicValueOption {
  /** Device ID */
  deviceId: string;
  /** Service UUID */
  serviceId: string;
  /** Characteristic UUID */
  characteristicId: string;
  /** Data to write */
  value: ArrayBuffer;
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface NotifyBLECharacteristicValueChangeOption {
  /** Device ID */
  deviceId: string;
  /** Service UUID */
  serviceId: string;
  /** Characteristic UUID */
  characteristicId: string;
  /** Enable or disable notifications */
  state: boolean;
  /** Notification type */
  type?: 'notification' | 'indication';
  /** Success callback */
  success?(res: any): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

Usage Examples:

// Get characteristics for a service
wx.getBLEDeviceCharacteristics({
  deviceId: 'device_id',
  serviceId: 'service_uuid',
  success(res) {
    console.log('Device characteristics:', res.characteristics);
    
    res.characteristics.forEach(char => {
      console.log(`Characteristic: ${char.uuid}`);
      console.log(`Properties:`, char.properties);
      
      // Enable notifications if supported
      if (char.properties.notify) {
        wx.notifyBLECharacteristicValueChange({
          deviceId: 'device_id',
          serviceId: 'service_uuid',
          characteristicId: char.uuid,
          state: true,
          success(res) {
            console.log('Notifications enabled for', char.uuid);
          }
        });
      }
    });
  }
});

// Listen for characteristic value changes
wx.onBLECharacteristicValueChange((res) => {
  console.log('Characteristic value changed:');
  console.log(`Device: ${res.deviceId}`);
  console.log(`Service: ${res.serviceId}`);
  console.log(`Characteristic: ${res.characteristicId}`);
  console.log(`Value:`, res.value);
  
  // Process the received data
  const dataView = new DataView(res.value);
  const temperature = dataView.getFloat32(0, true);
  console.log(`Temperature: ${temperature}°C`);
});

// Write data to characteristic
const data = new ArrayBuffer(4);
const dataView = new DataView(data);
dataView.setUint32(0, 12345, true);

wx.writeBLECharacteristicValue({
  deviceId: 'device_id',
  serviceId: 'service_uuid',
  characteristicId: 'characteristic_uuid',
  value: data,
  success(res) {
    console.log('Data written successfully');
  },
  fail(err) {
    console.error('Write failed:', err);
  }
});

// Read characteristic value
wx.readBLECharacteristicValue({
  deviceId: 'device_id',
  serviceId: 'service_uuid',
  characteristicId: 'characteristic_uuid',
  success(res) {
    console.log('Read successful');
  }
});

NFC Support

Near Field Communication functionality for WeChat Mini Programs.

/**
 * Get NFC adapter instance
 * @returns NFC adapter for tag operations
 */
function getNFCAdapter(): NFCAdapter;

interface NFCAdapter {
  /**
   * Start NFC discovery session
   * @param option - NFC discovery configuration
   */
  startDiscovery(option: NFCStartDiscoveryOption): Promise<any>;
  
  /**
   * Stop NFC discovery session
   * @param option - Stop discovery configuration
   */
  stopDiscovery(option?: NFCStopDiscoveryOption): Promise<any>;
  
  /**
   * Listen for NFC tag discovery events
   * @param callback - Tag discovery callback
   */
  onDiscovered(callback: (res: NFCTagInfo) => void): void;
  
  /**
   * Remove NFC tag discovery listeners
   * @param callback - Callback to remove
   */
  offDiscovered(callback?: (res: NFCTagInfo) => void): void;
}

interface NFCStartDiscoveryOption {
  /** PowerLevel for NFC discovery */
  powerLevel?: 'low' | 'balanced' | 'high';
  /** Array of tag technologies to discover */
  techTypes?: NFCTechType[];
}

interface NFCTagInfo {
  /** NFC tag ID */
  id: string;
  /** Supported technologies */
  techs: NFCTechType[];
  /** NDEF messages if available */
  messages?: NDEFMessage[];
}

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

interface NDEFMessage {
  /** NDEF records */
  records: NDEFRecord[];
}

interface NDEFRecord {
  /** Record type */
  type: ArrayBuffer;
  /** Record ID */
  id?: ArrayBuffer;
  /** Record payload */
  payload: ArrayBuffer;
}

Usage Examples:

// Initialize NFC adapter
const nfcAdapter = wx.getNFCAdapter();

// Start NFC discovery
nfcAdapter.startDiscovery({
  techTypes: ['Ndef', 'NfcA'],
  powerLevel: 'balanced'
}).then(() => {
  console.log('NFC discovery started');
}).catch(err => {
  console.error('Failed to start NFC discovery:', err);
});

// Listen for NFC tag discovery
nfcAdapter.onDiscovered((res) => {
  console.log('NFC tag discovered:');
  console.log(`Tag ID: ${res.id}`);
  console.log(`Technologies: ${res.techs.join(', ')}`);
  
  if (res.messages) {
    res.messages.forEach((message, msgIndex) => {
      console.log(`Message ${msgIndex}:`);
      message.records.forEach((record, recIndex) => {
        console.log(`  Record ${recIndex}:`);
        console.log(`    Type: ${new TextDecoder().decode(record.type)}`);
        console.log(`    Payload: ${new TextDecoder().decode(record.payload)}`);
      });
    });
  }
});

// Stop NFC discovery when done
setTimeout(() => {
  nfcAdapter.stopDiscovery().then(() => {
    console.log('NFC discovery stopped');
  });
}, 30000); // Stop after 30 seconds

Event Listeners

// Bluetooth event listeners
function onBluetoothAdapterStateChange(callback: (res: BluetoothAdapterStateInfo) => void): void;
function offBluetoothAdapterStateChange(callback?: (res: BluetoothAdapterStateInfo) => void): void;

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

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

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

interface BluetoothAdapterStateInfo {
  /** Whether adapter is available */
  available: boolean;
  /** Whether discovery is active */
  discovering: boolean;
}

interface BluetoothDeviceFoundInfo {
  /** Array of newly found devices */
  devices: BluetoothDeviceInfo[];
}

interface BLEConnectionStateInfo {
  /** Device ID */
  deviceId: string;
  /** Connection state */
  connected: boolean;
}

interface BLECharacteristicValueInfo {
  /** Device ID */
  deviceId: string;
  /** Service UUID */
  serviceId: string;
  /** Characteristic UUID */
  characteristicId: string;
  /** Characteristic value */
  value: ArrayBuffer;
}

docs

ai-ml-apis.md

app-page-lifecycle.md

bluetooth-nfc-apis.md

canvas-graphics.md

cloud-services.md

component-system.md

core-apis.md

device-hardware-apis.md

event-system.md

index.md

payment-apis.md

tile.json