ble_manager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. // 引入必要的微信小程序 API
  2. // const wx = require('wx');
  3. class bleManager {
  4. constructor() {
  5. var that = this;
  6. that.isAvailable = false;
  7. that.hasPermission = false;
  8. that.scanDevices = [];
  9. that.device = null;
  10. }
  11. // 初始化蓝牙适配器
  12. async initBluetoothAdapter(callback) {
  13. var that = this
  14. return new Promise((resolve, reject) => {
  15. wx.openBluetoothAdapter({
  16. success: (res) => {
  17. that.isAvailable = true;
  18. if (callback) {
  19. callback(true);
  20. }
  21. resolve(true);
  22. },
  23. fail: (err) => {
  24. that.isAvailable = false;
  25. console.log('adapterState fail, now is', err)
  26. if (callback) {
  27. callback(false);
  28. }
  29. reject(false);
  30. }
  31. });
  32. wx.onBluetoothAdapterStateChange(function (res) {
  33. // console.log('adapterState changed, now is', res)
  34. // if (callback) {
  35. // callback(res.available ?? false);
  36. // }
  37. that.isAvailable = res.available ?? false
  38. })
  39. });
  40. }
  41. // 开始搜索蓝牙设备
  42. async startScan(callBack, succeed) {
  43. var that = this;
  44. var open = await that.getLocalSetting();
  45. if (!open) {
  46. succeed(false);
  47. return;
  48. }
  49. if (!that.isAvailable) {
  50. wx.showToast({
  51. title: '请打开蓝牙',
  52. icon: 'none',
  53. duration: 2000
  54. });
  55. succeed(false);
  56. return;
  57. }
  58. if (!that.hasPermission) {
  59. wx.showToast({
  60. title: '请打开蓝牙权限',
  61. icon: 'none',
  62. duration: 2000
  63. });
  64. succeed(false);
  65. return;
  66. }
  67. // services: ["ffc0", "ab00", "ffe5"],
  68. wx.startBluetoothDevicesDiscovery({
  69. allowDuplicatesKey: false,
  70. success: (res) => {
  71. if (res) {
  72. wx.onBluetoothDeviceFound((devicesRes) => {
  73. for (var i = 0; i < devicesRes.devices.length; i++) {
  74. if (devicesRes.devices[i].name === getApp().globalData.connectWillDevice.clientType) {
  75. callBack(devicesRes.devices[i]);
  76. break;
  77. }
  78. }
  79. });
  80. } else {
  81. succeed(false);
  82. }
  83. },
  84. fail: (err) => {
  85. if (err.errno == 1509008) {
  86. wx.showToast({
  87. title: '搜索蓝牙需要先开启定位权限',
  88. icon: 'none',
  89. duration: 2000
  90. });
  91. }
  92. succeed(false);
  93. }
  94. });
  95. }
  96. // 停止搜索
  97. stopScan() {
  98. return new Promise((resolve, reject) => {
  99. wx.stopBluetoothDevicesDiscovery({
  100. success: (res) => {
  101. console.log('停止搜索成功:', res);
  102. resolve(res);
  103. },
  104. fail: (err) => {
  105. console.error('停止搜索失败:', err);
  106. reject(new Error('停止搜索失败'));
  107. }
  108. });
  109. });
  110. }
  111. // 检查蓝牙权限
  112. async checkBluetoothPermission(callback) {
  113. // 获取蓝牙权限
  114. var that = this;
  115. const _app = getApp();
  116. wx.getSetting({
  117. success(res) {
  118. if (res.authSetting["scope.bluetooth"]) {
  119. _app.globalData.scopeBluetooth = true;
  120. that.hasPermission = true;
  121. if (callback) {
  122. callback(true);
  123. }
  124. } else if (res.authSetting["scope.bluetooth"] === undefined) {
  125. _app.globalData.scopeBluetooth = false;
  126. that.hasPermission = false;
  127. if (callback) {
  128. callback(false);
  129. }
  130. wx.authorize({
  131. scope: "scope.bluetooth",
  132. complete() {
  133. that.checkBluetoothPermission()
  134. }
  135. });
  136. } else {
  137. that.globalData.scopeBluetooth = false;
  138. that.hasPermission = false;
  139. if (callback) {
  140. callback(false);
  141. }
  142. wx.showModal({
  143. title: '请打开系统蓝牙进行配网',
  144. content: '如已打开蓝牙仍然弹框,请尝试重启小程序',
  145. success(res) {
  146. if (res.confirm) {
  147. console.log('用户点击确定')
  148. wx.openSetting({
  149. complete() {}
  150. })
  151. } else if (res.cancel) {
  152. console.log('用户点击取消')
  153. }
  154. }
  155. });
  156. };
  157. }
  158. })
  159. }
  160. closeBle() {
  161. console.log('关闭蓝牙了')
  162. wx.closeBluetoothAdapter();
  163. }
  164. // 获取已连接的蓝牙设备
  165. getConnectedDevices() {
  166. var that = this;
  167. if (!that.isAvailable && !that.hasPermission) {
  168. return [];
  169. }
  170. return new Promise((resolve, reject) => {
  171. wx.getConnectedBluetoothDevices({
  172. // services: ["FFC0", "ffc0", "FFC1", "FFC2", "ffc1", "ffc2", "AB00", "ab00", "AB01", "AB02", "FFF1", "fff1", "FFE2", "FFE5",],
  173. services: ["ab00", "ffe5", "1111", "FFC0", "FFC1", "FFF1", ],
  174. // services: [],
  175. // services: [
  176. // "0000ab00-0000-1000-8000-00805f9b34fb",
  177. // "0000ffc0-0000-1000-8000-00805f9b34fb",
  178. // "0000FFF0-0000-1000-8000-00805F9B34FB",
  179. // "0000FFF1-0000-1000-8000-00805F9B34FB",
  180. // "0000FFE5-0000-1000-8000-00805F9B34FB",
  181. // ],
  182. success: (res) => {
  183. let newDevices = that.fiterDevice(res)
  184. console.log('已连接的蓝牙设备:', newDevices);
  185. resolve(newDevices);
  186. },
  187. fail: (err) => {
  188. console.error('获取已连接的蓝牙设备失败:', err);
  189. reject([]);
  190. }
  191. });
  192. });
  193. }
  194. // 获取获取在蓝牙模块生效期间所有搜索到的蓝牙设备。包括已经和本机处于连接状态的设备。
  195. getAllConnectedDevices() {
  196. var that = this;
  197. if (!that.isAvailable && !that.hasPermission) {
  198. return [];
  199. }
  200. return new Promise((resolve, reject) => {
  201. wx.getBluetoothDevices({
  202. success: (res) => {
  203. // const connectedDevices = res.devices.map(device => ({
  204. // deviceId: device.deviceId,
  205. // name: device.name || device.localName
  206. // }));
  207. let newDevices = that.fiterDevice(res)
  208. resolve(newDevices);
  209. },
  210. fail: (err) => {
  211. console.error('已扫描过的蓝牙设备失败:', err);
  212. reject([]);
  213. }
  214. });
  215. });
  216. }
  217. // 断开与指定设备的连接
  218. disconnect() {
  219. var that = this;
  220. let device = that.device ?? {};
  221. let deviceId = device.deviceId ?? ""
  222. if (deviceId.length === 0) {
  223. return;
  224. }
  225. return new Promise((resolve, reject) => {
  226. wx.closeBLEConnection({
  227. deviceId: that.device.deviceId ?? "",
  228. success: (res) => {
  229. that.device = null;
  230. console.log('断开连接成功:', res);
  231. resolve(res);
  232. },
  233. fail: (err) => {
  234. console.error('断开连接失败:', err);
  235. reject(new Error('断开连接失败'));
  236. }
  237. });
  238. });
  239. }
  240. // 发送数据到指定设备
  241. async sendData(data) {
  242. var that = this
  243. return new Promise((resolve, reject) => {
  244. var buffer = null;
  245. // todo 判断是否是buffer
  246. // if (Buffer.isBuffer(data)) {
  247. // buffer = data;
  248. // } else {
  249. buffer = new ArrayBuffer(data.length);
  250. // 下面是赋值,不能删
  251. const dataView = new DataView(buffer);
  252. data.forEach((value, index) => {
  253. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  254. });
  255. // }
  256. console.log('开始发送数据:', data, buffer);
  257. wx.writeBLECharacteristicValue({
  258. deviceId: that.device.deviceId,
  259. serviceId: that.device.serviceId,
  260. characteristicId: that.device.characteristicId,
  261. value: buffer,
  262. success: (res) => {
  263. // console.log('数据发送成功:');
  264. resolve(res);
  265. },
  266. fail: (err) => {
  267. console.error('数据发送失败:', err);
  268. reject(new Error('数据发送失败'));
  269. }
  270. });
  271. });
  272. }
  273. ///获取定位权限
  274. async getLocalSetting() {
  275. var that = this;
  276. return new Promise((resolve, reject) => {
  277. wx.getSetting({
  278. success(res) {
  279. if (res.authSetting["scope.userLocation"]) {
  280. console.log("有定位权限")
  281. resolve(true);
  282. } else if (res.authSetting["scope.userLocation"] === undefined) {
  283. wx.authorize({
  284. scope: "scope.userLocation",
  285. success() {
  286. resolve(that.getLocalSetting());
  287. }
  288. });
  289. } else {
  290. wx.showModal({
  291. title: '请打开系统位置获取定位权限',
  292. success(res) {
  293. if (res.confirm) {
  294. wx.openSetting({
  295. complete() {}
  296. })
  297. } else if (res.cancel) {}
  298. }
  299. })
  300. console.log("没有有定位权限")
  301. reject(false);
  302. }
  303. },
  304. fail(err) {}
  305. });
  306. });
  307. }
  308. // 监听发现新设备的事件
  309. onBluetoothDeviceFound(callback) {
  310. var that = this;
  311. wx.onBluetoothDeviceFound((res) => {
  312. let newDevices = that.fiterDevice(res)
  313. // that.devices.push(...devices);
  314. if (newDevices.length > 0) {
  315. // console.log('发现设备1:', res);
  316. }
  317. if (callback) {
  318. callback(newDevices);
  319. }
  320. });
  321. }
  322. getMac() {
  323. }
  324. ab2hex(buffer) {
  325. var hexArr = Array.prototype.map.call(
  326. new Uint8Array(buffer),
  327. function (bit) {
  328. return ('00' + bit.toString(16)).slice(-2)
  329. }
  330. )
  331. return hexArr.join(':');
  332. }
  333. fiterDevice(res) {
  334. var that = this;
  335. var devices = res.devices.filter(device => {
  336. const name = device.name || '';
  337. const localName = device.localName || '';
  338. let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName);
  339. if (isNot) {
  340. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  341. let mac = that.ab2hex(device.advertisData)
  342. // console.log(mac)
  343. device.mac = mac
  344. }
  345. return isNot
  346. });
  347. let newDevices = devices.map((device) => {
  348. let uuid = device.advertisServiceUUIDs[0] ?? ""
  349. return {
  350. deviceId: device.deviceId,
  351. name: device.name,
  352. localName: device.localName,
  353. uuid: uuid,
  354. mac: device.mac,
  355. connectable: device.connectable
  356. }
  357. });
  358. return newDevices
  359. }
  360. isNotEmpty(name) {
  361. let isNot = (name !== '' &&
  362. (name.startsWith("MW_") ||
  363. name.startsWith("MW-") ||
  364. // name.startsWith("猫王") ||
  365. // name.startsWith("妙播") ||
  366. // name.startsWith("AirSmart") ||
  367. name === "le")
  368. )
  369. // if (!isNot && name !== '') {
  370. // console.log('不是猫王设备名称:', name)
  371. // }
  372. return isNot;
  373. }
  374. // 连接到指定设备
  375. async connectToDevice(device) {
  376. var that = this;
  377. return new Promise((resolve, reject) => {
  378. console.log("开始连接蓝牙:", device.deviceId)
  379. wx.createBLEConnection({
  380. deviceId: device.deviceId,
  381. success: (res) => {
  382. that.device = device
  383. console.log('连接成功:', res);
  384. resolve(true);
  385. },
  386. fail: (err) => {
  387. that.device = null
  388. console.error('连接失败:', err);
  389. resolve(false);
  390. }
  391. });
  392. });
  393. }
  394. // 发现服务
  395. discoverServices(deviceId) {
  396. var that = this;
  397. console.log('发现服务:', deviceId);
  398. return new Promise((resolve, reject) => {
  399. wx.getBLEDeviceServices({
  400. deviceId: deviceId,
  401. success: (res) => {
  402. // that.device.services = res.services;
  403. let service_id = "";
  404. for (let i = 0; i < res.services.length; i++) {
  405. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  406. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  407. // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  408. ) {
  409. service_id = res.services[i].uuid;
  410. break;
  411. }
  412. console.log('发现服务1:', service_id);
  413. service_id = res.services[i].uuid;
  414. }
  415. that.device.serviceId = service_id;
  416. console.log('发现服务2:', service_id);
  417. resolve(service_id);
  418. // resolve(res.services);
  419. },
  420. fail: (err) => {
  421. that.device.serviceId = null;
  422. console.error('发现服务失败:', err);
  423. reject([]);
  424. }
  425. });
  426. });
  427. }
  428. // 发现特征值 read / write
  429. discoverCharacteristics(deviceId, serviceId) {
  430. var that = this;
  431. console.log('发现特征值:' + deviceId + " , " + serviceId);
  432. // if (deviceId !== that.device.deviceId) {
  433. // console.log('设备id不匹配')
  434. // return false
  435. // }
  436. return new Promise((resolve, reject) => {
  437. wx.getBLEDeviceCharacteristics({
  438. deviceId: deviceId,
  439. serviceId: serviceId,
  440. success: (res) => {
  441. // that.characteristics[serviceId] = res.characteristics;
  442. console.log('发现特征值2:', res);
  443. // that.device.characteristics = res.characteristics;
  444. resolve(res.characteristics);
  445. },
  446. fail: (err) => {
  447. that.device.characteristics = null;
  448. console.error('发现特征值失败:', err);
  449. reject("");
  450. }
  451. });
  452. });
  453. }
  454. // 读取特征值
  455. readCharacteristicValue(characteristicId) {
  456. var that = ths;
  457. console.log('开始读取特征值', characteristicId)
  458. return new Promise((resolve, reject) => {
  459. wx.readBLECharacteristicValue({
  460. deviceId: that.device.deviceId,
  461. serviceId: that.device.serviceId,
  462. characteristicId: characteristicId,
  463. success: (res) => {
  464. const name = that.parseBLEValue(res.value); // 解析读取到的值
  465. console.log('读取特征值成功:', name, res);
  466. resolve(res);
  467. },
  468. fail: (err) => {
  469. console.error('读取特征值失败:', err);
  470. reject("");
  471. }
  472. });
  473. });
  474. }
  475. // 解析读取到的设备名称
  476. parseBLEValue(buffer) {
  477. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  478. }
  479. // 监听特征值变化
  480. notifyCharacteristicValueChange(characteristicId, callback) {
  481. var that = this;
  482. console.log('监听特征值变化:', characteristicId, that.device.deviceId, that.device.serviceId);
  483. wx.notifyBLECharacteristicValueChange({
  484. deviceId: that.device.deviceId, //设备mac IOS和安卓系统不一样
  485. serviceId: that.device.serviceId, //服务通道,这里主要是notify
  486. characteristicId: characteristicId, //notify uuid
  487. state: true,
  488. success: function (res) {
  489. console.log("开启notify 成功")
  490. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  491. wx.onBLECharacteristicValueChange(function (characteristic) {
  492. let buffer = characteristic.value
  493. let dataView = new DataView(buffer)
  494. let dataResult = []
  495. for (let i = 0; i < dataView.byteLength; i++) {
  496. // console.log("0x" + dataView.getUint8(i).toString(16))
  497. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  498. dataResult.push(dataView.getUint8(i))
  499. }
  500. const result = dataResult
  501. console.log("拿到的数据:", result)
  502. if (callback) {
  503. callback(result)
  504. }
  505. })
  506. },
  507. fail: function (res) {
  508. console.log("订阅特征失败:", res)
  509. }
  510. })
  511. }
  512. setWrite(wirte, characteristicId) {
  513. var that = this;
  514. console.log('写入特征值:', characteristicId)
  515. // that.device.wirte = wirte
  516. that.device.characteristicId = characteristicId;
  517. }
  518. }
  519. // const ble = new bleManager();
  520. // 导出 bleManager 类
  521. module.exports = bleManager;
  522. // wx.getSetting({
  523. // success(res) {
  524. // if (res.authSetting["scope.userFuzzyLocation"]) {
  525. // // 成功
  526. // // that.getBluetoothStatus();
  527. // console.log("有定位权限")
  528. // resolve(true);
  529. // } else if (res.authSetting["scope.userFuzzyLocation"] === undefined) {
  530. // wx.authorize({
  531. // scope: "scope.userFuzzyLocation",
  532. // success() {
  533. // console.log("再次获取定位权限")
  534. // resolve(that.getSetting());
  535. // }
  536. // });
  537. // } else {
  538. // wx.showModal({
  539. // title: '请打开系统位置获取定位权限',
  540. // success(res) {
  541. // if (res.confirm) {
  542. // console.log('用户点击确定')
  543. // wx.openSetting({
  544. // complete() {
  545. // // that.getSetting();
  546. // // resolve(that.getSetting());
  547. // }
  548. // })
  549. // } else if (res.cancel) {
  550. // console.log('用户点击取消');
  551. // }
  552. // }
  553. // })
  554. // console.log("没有有定位权限")
  555. // reject(false);
  556. // }
  557. // }
  558. // })