123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367 |
- // 引入必要的微信小程序 API
- // const wx = require('wx');
- class bleManager {
- constructor() {
- this.hasPermission = false;
- this.isAvailable = false;
- // this.devices = [];
- this.connectedDeviceId = null;
- // this.services = [];
- this.serviceId = null;
- this.deviceId = null;
- this.characteristicId = null;
- }
- // 检查蓝牙权限
- async checkBluetoothPermission() {
- return new Promise((resolve, reject) => {
- // 获取蓝牙权限
- const _this = getApp();
- wx.getSetting({
- success(res) {
- if (res.authSetting["scope.bluetooth"]) {
- _this.globalData.scopeBluetooth = true;
- resolve(true);
- } else if (res.authSetting["scope.bluetooth"] === undefined) {
- _this.globalData.scopeBluetooth = false;
- wx.authorize({
- scope: "scope.bluetooth",
- complete() {
- _this.getBluetoothStatus();
- }
- });
- resolve(false);
- } else {
- _this.globalData.scopeBluetooth = false;
- wx.showModal({
- title: '请打开系统蓝牙进行配网',
- content: '如已打开蓝牙仍然弹框,请尝试重启小程序',
- success(res) {
- if (res.confirm) {
- console.log('用户点击确定')
- wx.openSetting({
- complete() {
- // _this.getBluetoothStatus();
- }
- })
- } else if (res.cancel) {
- console.log('用户点击取消')
- }
- }
- })
- resolve(false);
- };
- }
- })
- })
- }
- // 初始化蓝牙适配器
- initBluetoothAdapter() {
- return new Promise((resolve, reject) => {
- wx.openBluetoothAdapter({
- success: (res) => {
- this.isAvailable = true;
- resolve(true);
- },
- fail: (err) => {
- this.isAvailable = false;
- reject(false);
- }
- });
- });
- }
- // 获取已连接的蓝牙设备
- getConnectedDevices() {
- return new Promise((resolve, reject) => {
- wx.getConnectedBluetoothDevices({
- services: ["ffc0", "ab00", "ffe5"],
- // services: ["0000ab00-0000-1000-8000-00805f9b34fb"
- // , "0000ffc0-0000-1000-8000-00805f9b34fb"
- // ],
- success: (res) => {
- // const connectedDevices = res.devices.map(device => ({
- // deviceId: device.deviceId,
- // name: device.name || device.localName
- // }));
- console.log('已连接的蓝牙设备:', res.devices);
- resolve(res.devices);
- },
- fail: (err) => {
- console.error('获取已连接的蓝牙设备失败:', err);
- reject(new Error('获取已连接的蓝牙设备失败'));
- }
- });
- });
- }
- // 断开与指定设备的连接
- disconnect(deviceId) {
- return new Promise((resolve, reject) => {
- wx.closeBLEConnection({
- deviceId: deviceId,
- success: (res) => {
- this.connectedDeviceId = null;
- console.log('断开连接成功:', res);
- resolve(res);
- },
- fail: (err) => {
- console.error('断开连接失败:', err);
- reject(new Error('断开连接失败'));
- }
- });
- });
- }
- // 发送数据到指定设备
- sendData(data) {
- return new Promise((resolve, reject) => {
- const buffer = new ArrayBuffer(data.length);
- const view = new Uint8Array(buffer);
- for (let i = 0; i < data.length; i++) {
- view[i] = data.charCodeAt(i);
- }
- wx.writeBLECharacteristicValue({
- deviceId: this.deviceId,
- serviceId: this.serviceId,
- characteristicId: this.characteristicId,
- value: buffer,
- success: (res) => {
- console.log('数据发送成功:', res);
- resolve(res);
- },
- fail: (err) => {
- console.error('数据发送失败:', err);
- reject(new Error('数据发送失败'));
- }
- });
- });
- }
- getSetting() {
- const _this = this;
- wx.getSetting({
- success(res) {
- if (res.authSetting["scope.userFuzzyLocation"]) {
- // 成功
- _this.getBluetoothStatus();
- } else if (res.authSetting["scope.userFuzzyLocation"] === undefined) {
- wx.authorize({
- scope: "scope.userFuzzyLocation",
- success() {
- _this.getSetting();
- }
- });
- } else {
- wx.showModal({
- title: '请打开系统位置获取',
- success(res) {
- if (res.confirm) {
- console.log('用户点击确定')
- wx.openSetting({
- complete() {
- // _this.getSetting();
- }
- })
- } else if (res.cancel) {
- console.log('用户点击取消');
- }
- }
- })
- }
- }
- })
- }
- // 开始搜索蓝牙设备
- startScan(success, fail) {
- wx.startBluetoothDevicesDiscovery({
- services: ["ffc0", "ab00", "ffe5"],
- success: (res) => {
- // this.onBluetoothDeviceFound();
- console.log('蓝牙设备搜索已启动:', res);
- if (success) {
- success(res);
- }
- // resolve(res);
- },
- fail: (err) => {
- if (fail) {
- fail(err);
- }
- console.log('启动蓝牙设备搜索失败', err ?? "err is null");
- // reject(new Error('启动蓝牙设备搜索失败', err ?? "err is null"));
- }
- });
- // return new Promise((resolve, reject) => {
- // wx.startBluetoothDevicesDiscovery({
- // services: ["ffc0", "ab00", "ffe5"],
- // success: (res) => {
- // // this.onBluetoothDeviceFound();
- // console.log('蓝牙设备搜索已启动:', res);
- // resolve(res);
- // },
- // fail: (err) => {
- // reject(new Error('启动蓝牙设备搜索失败', err ?? "err is null"));
- // }
- // });
- // });
- }
- // 监听发现新设备的事件
- onBluetoothDeviceFound(callback) {
- wx.onBluetoothDeviceFound((res) => {
- const devices = res.devices.map(device => ({
- deviceId: device.deviceId,
- name: device.name || device.localName
- }));
- // this.devices.push(...devices);
- console.log('发现设备:', this.devices);
- if (callback) {
- callback(devices);
- }
- });
- }
- // 连接到指定设备
- connectToDevice(deviceId) {
- return new Promise((resolve, reject) => {
- wx.createBLEConnection({
- deviceId: deviceId,
- success: (res) => {
- this.connectedDeviceId = deviceId;
- console.log('连接成功:', res);
- resolve(res);
- },
- fail: (err) => {
- console.error('连接失败:', err);
- reject(new Error('连接失败'));
- }
- });
- });
- }
- // 停止搜索
- stopScan() {
- return new Promise((resolve, reject) => {
- wx.stopBluetoothDevicesDiscovery({
- success: (res) => {
- console.log('停止搜索成功:', res);
- resolve(res);
- },
- fail: (err) => {
- console.error('停止搜索失败:', err);
- reject(new Error('停止搜索失败'));
- }
- });
- });
- }
- // 发现服务
- discoverServices(deviceId) {
- return new Promise((resolve, reject) => {
- wx.getBLEDeviceServices({
- deviceId: deviceId,
- success: (res) => {
- this.services = res.services;
- console.log('发现服务:', this.services);
- resolve(res.services);
- },
- fail: (err) => {
- console.error('发现服务失败:', err);
- reject(new Error('发现服务失败'));
- }
- });
- });
- }
- // 发现特征值
- discoverCharacteristics(deviceId, serviceId) {
- return new Promise((resolve, reject) => {
- wx.getBLEDeviceCharacteristics({
- deviceId: deviceId,
- serviceId: serviceId,
- success: (res) => {
- // this.characteristics[serviceId] = res.characteristics;
- this.characteristicId = res.characteristics;
- console.log('发现特征值:', this.characteristicId);
- resolve(res.characteristics);
- },
- fail: (err) => {
- console.error('发现特征值失败:', err);
- reject(new Error('发现特征值失败'));
- }
- });
- });
- }
- // 读取特征值
- readCharacteristicValue(deviceId, serviceId, characteristicId) {
- return new Promise((resolve, reject) => {
- wx.readBLECharacteristicValue({
- deviceId: deviceId,
- serviceId: serviceId,
- characteristicId: characteristicId,
- success: (res) => {
- console.log('读取特征值成功:', res);
- resolve(res);
- },
- fail: (err) => {
- console.error('读取特征值失败:', err);
- reject(new Error('读取特征值失败'));
- }
- });
- });
- }
- // 监听特征值变化
- notifyCharacteristicValueChange(deviceId, serviceId, characteristicId, state, callback) {
- // return new Promise((resolve, reject) => {
- wx.notifyBLECharacteristicValueChange({
- deviceId: deviceId,
- serviceId: serviceId,
- characteristicId: characteristicId,
- state: state, // true 表示开启通知,false 表示关闭通知
- success: (res) => {
- console.log('通知特征值变化成功:', res);
- // resolve(res);
- if (callback) {
- callback(res)
- }
- },
- fail: (err) => {
- console.error('通知特征值变化失败:', err);
- // reject(new Error('通知特征值变化失败'));
- }
- });
- // });
- }
- // 搜索蓝牙服务
- searchServices(deviceId) {
- return this.discoverServices(deviceId);
- }
- // 搜索蓝牙特征值
- searchCharacteristics(deviceId, serviceId) {
- return this.discoverCharacteristics(deviceId, serviceId);
- }
- }
- const ble = new bleManager();
- // 导出 bleManager 类
- module.exports = ble;
|