ble_manager.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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.publicDevice = null;
  10. that.compareList = [];
  11. that.connectWillDevice = null;
  12. that.callBackConnect = null;
  13. that.requestBlueTime = 0;
  14. ///正在执行扫描中
  15. that.doStartScaning = false;
  16. }
  17. ///获取比较的数据
  18. getCompareList() {
  19. return this.compareList;
  20. }
  21. setConnectWillDevice(connectWillDevice) {
  22. this.connectWillDevice = connectWillDevice;
  23. }
  24. getCallBackConnect() {
  25. return this.callBackConnect;
  26. }
  27. setCallBackConnect(callBackConnect) {
  28. this.callBackConnect = callBackConnect;
  29. }
  30. /// 监控蓝牙打开状态
  31. initBluetoothAdapter() {
  32. var that = this;
  33. wx.openBluetoothAdapter({
  34. success: (res) => {
  35. that.isAvailable = true;
  36. },
  37. fail: (err) => {
  38. that.isAvailable = false;
  39. }
  40. });
  41. wx.onBluetoothAdapterStateChange(function (res) {
  42. that.isAvailable = res.available;
  43. })
  44. }
  45. ///监听搜索设备列表
  46. getBluetoothDevices() {
  47. var that = this;
  48. wx.onBluetoothDeviceFound(function (res) {
  49. ///第一种情况
  50. if (res.deviceId) {
  51. if (that.callBackConnect != null) {
  52. if (that.connectWillDevice != null && res.name == that.connectWillDevice.clientType) {
  53. res.advertisData = res.advertisData ? that.buf2hex(res.advertisData) : '';
  54. that.callBackConnect(res);
  55. }
  56. } else {
  57. if (res.name != "") {
  58. if (that.compareList.length > 0) {
  59. var has = false;
  60. for (var i = 0; i < that.compareList.length; i++) {
  61. if (res.deviceId == that.compareList[i].deviceId) {
  62. has = true;
  63. break;
  64. }
  65. }
  66. if (!has) {
  67. that.compareList.push(res);
  68. }
  69. } else {
  70. that.compareList.push(res);
  71. }
  72. }
  73. }
  74. }
  75. ///第二种情况
  76. else if (res.devices) {
  77. if (that.callBackConnect != null) {
  78. for (var i = 0; i < res.devices.length; i++) {
  79. var temp = res.devices[i];
  80. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  81. temp.advertisData = temp.advertisData ? that.buf2hex(temp.advertisData) : '';
  82. that.callBackConnect(temp);
  83. break;
  84. }
  85. }
  86. } else {
  87. for (var i = 0; i < res.devices.length; i++) {
  88. if (that.compareList.length > 0) {
  89. var has = false;
  90. for (var j = 0; j < that.compareList.length; j++) {
  91. if (res.devices[i].name != "") {
  92. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  93. has = true;
  94. break;
  95. }
  96. }
  97. }
  98. if (!has) {
  99. that.compareList.push(res.devices[i]);
  100. }
  101. } else {
  102. that.compareList.push(res.devices[i]);
  103. }
  104. }
  105. }
  106. }
  107. ///第三种情况
  108. else if (res[0]) {
  109. if (that.callBackConnect != null) {
  110. if (that.connectWillDevice != null && res[0].name == that.connectWillDevice.clientType) {
  111. res[0].advertisData = res[0].advertisData ? that.buf2hex(res[0].advertisData) : '';
  112. that.callBackConnect(res[0]);
  113. }
  114. } else {
  115. if (res[0].name != "") {
  116. if (that.compareList.length > 0) {
  117. var has = false;
  118. for (var i = 0; i < that.compareList.length; i++) {
  119. if (res[0].deviceId == that.compareList[i].deviceId) {
  120. has = true;
  121. break;
  122. }
  123. }
  124. if (!has) {
  125. that.compareList.push(res[0]);
  126. }
  127. } else {
  128. that.compareList.push(res[0]);
  129. }
  130. }
  131. }
  132. }
  133. });
  134. }
  135. ///获取已连接的设备
  136. getConnectedDevices() {
  137. wx.getBluetoothDevices({
  138. success: (res) => {
  139. if (res.devices && res.devices.length > 0) {
  140. for (var i = 0; i < res.devices.length; i++) {
  141. var temp = res.devices[i];
  142. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  143. temp.advertisData = temp.advertisData ? that.buf2hex(temp.advertisData) : '';
  144. that.callBackConnect(temp);
  145. break;
  146. }
  147. }
  148. }
  149. },
  150. fail: (err) => {
  151. console.error('获取蓝牙设备列表失败', err);
  152. }
  153. });
  154. }
  155. ///获取数据
  156. buf2hex(buffer) {
  157. return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  158. }
  159. ///获取毫秒
  160. getCurrentMills() {
  161. var currentDate = new Date();
  162. var currentTimeMillis = currentDate.getTime();
  163. // return Math.floor(currentTimeMillis / 1000);
  164. return currentTimeMillis;
  165. }
  166. // 等待多少秒
  167. delay(ms) {
  168. return new Promise(resolve => setTimeout(resolve, ms));
  169. }
  170. // 开始搜索蓝牙设备
  171. async startScan(connectWillDevice, boolean, callBackConnect) {
  172. var that = this;
  173. const route_util = require('../utils/route_util');
  174. const route_constant = require('../utils/route_constant');
  175. const indexRoot = route_constant.indexRoot;
  176. const connectBleRoot = route_constant.connectBleRoot;
  177. var lastPageRoute = route_util.getLastPageRoute();
  178. if (lastPageRoute != indexRoot && lastPageRoute != connectBleRoot) {
  179. return;
  180. }
  181. if (!that.isAvailable) {
  182. if (lastPageRoute == connectBleRoot) {
  183. wx.showToast({
  184. title: '蓝牙未打开',
  185. icon: "none",
  186. duration: 2000
  187. })
  188. }
  189. return;
  190. }
  191. ///蓝牙连接 做限制
  192. if (lastPageRoute == indexRoot) {
  193. if (that.doStartScaning == true) {
  194. return;
  195. }
  196. }
  197. that.doStartScaning = true;
  198. var currentMill = that.getCurrentMills();
  199. var waitMills = 0;
  200. var reduce = currentMill - that.requestBlueTime;
  201. const delayMiliis = 5 * 1000;
  202. if (reduce > 0 && reduce < delayMiliis) {
  203. waitMills = delayMiliis - reduce;
  204. }
  205. // if (waitMills > 0) {
  206. // await that.delay(waitMills);
  207. // }
  208. if (callBackConnect == null && lastPageRoute == connectBleRoot) {
  209. that.doStartScaning = false;
  210. return;
  211. }
  212. wx.stopBluetoothDevicesDiscovery({
  213. success: (res) => {
  214. wx.startBluetoothDevicesDiscovery({
  215. allowDuplicatesKey: true,
  216. success: function (res) {
  217. that.getConnectedDevices();
  218. that.doStartScaning = false;
  219. that.requestBlueTime = that.getCurrentMills();
  220. if (boolean != null) {
  221. boolean(true);
  222. }
  223. that.setConnectWillDevice(connectWillDevice);
  224. that.setCallBackConnect(callBackConnect);
  225. that.compareList = [];
  226. },
  227. fail(err) {
  228. that.doStartScaning = false;
  229. that.requestBlueTime = that.getCurrentMills();
  230. if (boolean != null) {
  231. boolean(false);
  232. }
  233. },
  234. })
  235. },
  236. fail: (err) => {
  237. wx.showModal({
  238. title: '提示',
  239. content: '请检查手机蓝牙是否打开',
  240. showCancel: false,
  241. success: function (res) {}
  242. });
  243. that.doStartScaning = false;
  244. if (boolean != null) {
  245. boolean(false);
  246. }
  247. }
  248. });
  249. // wx.startBluetoothDevicesDiscovery({
  250. // allowDuplicatesKey: true,
  251. // success: function (res) {
  252. // that.doStartScaning = false;
  253. // that.requestBlueTime = that.getCurrentMills();
  254. // if (boolean != null) {
  255. // boolean(true);
  256. // }
  257. // that.setConnectWillDevice(connectWillDevice);
  258. // that.setCallBackConnect(callBackConnect);
  259. // that.compareList = [];
  260. // },
  261. // fail(err) {
  262. // that.doStartScaning = false;
  263. // that.requestBlueTime = that.getCurrentMills();
  264. // if (boolean != null) {
  265. // boolean(false);
  266. // }
  267. // },
  268. // })
  269. // wx.closeBluetoothAdapter({
  270. // complete: function (res) {
  271. // wx.openBluetoothAdapter({
  272. // success: function (res) {
  273. // wx.getBluetoothAdapterState({
  274. // success: function (res) {
  275. // that.doStartScaning = false;
  276. // console.log("gadsfasdfqwerqwerqwerqr==xxx==" + JSON.stringify(res));
  277. // },
  278. // fail(err) {
  279. // that.doStartScaning = false;
  280. // console.log("gadsfasdfqwerqwerqwerqr==yyyy==" + JSON.stringify(res));
  281. // if (boolean != null) {
  282. // boolean(false);
  283. // }
  284. // },
  285. // })
  286. // wx.startBluetoothDevicesDiscovery({
  287. // allowDuplicatesKey: false,
  288. // success: function (res) {
  289. // console.log("gadsfasdfqwerqwerqwerqr==mmmm==" + JSON.stringify(res));
  290. // that.doStartScaning = false;
  291. // that.requestBlueTime = that.getCurrentMills();
  292. // if (boolean != null) {
  293. // boolean(true);
  294. // }
  295. // that.setConnectWillDevice(connectWillDevice);
  296. // that.setCallBackConnect(callBackConnect);
  297. // that.compareList = [];
  298. // },
  299. // fail(err) {
  300. // console.log("gadsfasdfqwerqwerqwerqr==nnnn==" + JSON.stringify(err));
  301. // that.doStartScaning = false;
  302. // that.requestBlueTime = that.getCurrentMills();
  303. // if (boolean != null) {
  304. // boolean(false);
  305. // }
  306. // },
  307. // })
  308. // },
  309. // fail: function (res) {
  310. // wx.showModal({
  311. // title: '提示',
  312. // content: '请检查手机蓝牙是否打开',
  313. // showCancel: false,
  314. // success: function (res) {}
  315. // });
  316. // that.doStartScaning = false;
  317. // if (boolean != null) {
  318. // boolean(false);
  319. // }
  320. // }
  321. // })
  322. // }
  323. // })
  324. }
  325. // 停止搜索
  326. stopSearch() {
  327. var that = this;
  328. that.setCallBackConnect(null);
  329. that.setConnectWillDevice(null);
  330. return new Promise((resolve, reject) => {
  331. wx.stopBluetoothDevicesDiscovery({
  332. success: (res) => {
  333. resolve(res);
  334. },
  335. fail: (err) => {
  336. reject(new Error('停止搜索失败'));
  337. }
  338. });
  339. });
  340. }
  341. closeBle() {
  342. console.log('关闭蓝牙了')
  343. closeBluetoothAdapter();
  344. }
  345. // 断开与指定设备的连接
  346. disconnect() {
  347. var that = this;
  348. let device = that.publicDevice ?? {};
  349. let deviceId = device.deviceId ?? ""
  350. if (deviceId.length === 0) {
  351. return;
  352. }
  353. return new Promise((resolve, reject) => {
  354. wx.closeBLEConnection({
  355. deviceId: that.publicDevice.deviceId ?? "",
  356. success: (res) => {
  357. that.publicDevice = null;
  358. console.log('断开连接成功:', res);
  359. resolve(res);
  360. },
  361. fail: (err) => {
  362. console.error('断开连接失败:', err);
  363. reject(new Error('断开连接失败'));
  364. }
  365. });
  366. });
  367. }
  368. // 发送数据到指定设备
  369. async sendData(data) {
  370. var that = this
  371. return new Promise((resolve, reject) => {
  372. var buffer = null;
  373. // todo 判断是否是buffer
  374. // if (Buffer.isBuffer(data)) {
  375. // buffer = data;
  376. // } else {
  377. buffer = new ArrayBuffer(data.length);
  378. // 下面是赋值,不能删
  379. const dataView = new DataView(buffer);
  380. data.forEach((value, index) => {
  381. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  382. });
  383. // }
  384. console.log('开始发送数据:', data, buffer);
  385. wx.writeBLECharacteristicValue({
  386. deviceId: that.publicDevice.deviceId,
  387. serviceId: that.publicDevice.serviceId,
  388. characteristicId: that.publicDevice.characteristicId,
  389. value: buffer,
  390. success: (res) => {
  391. // console.log('数据发送成功:');
  392. resolve(res);
  393. },
  394. fail: (err) => {
  395. console.error('数据发送失败:', err);
  396. reject(new Error('数据发送失败'));
  397. }
  398. });
  399. });
  400. }
  401. ab2hex(buffer) {
  402. var hexArr = Array.prototype.map.call(
  403. new Uint8Array(buffer),
  404. function (bit) {
  405. return ('00' + bit.toString(16)).slice(-2)
  406. }
  407. )
  408. return hexArr.join(':');
  409. }
  410. fiterDevice(res) {
  411. var that = this;
  412. var devices = res.devices.filter(device => {
  413. const name = device.name || '';
  414. const localName = device.localName || '';
  415. let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName);
  416. if (isNot) {
  417. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  418. let mac = that.ab2hex(device.advertisData)
  419. // console.log(mac)
  420. device.mac = mac
  421. }
  422. return isNot
  423. });
  424. let newDevices = devices.map((device) => {
  425. let uuid = device.advertisServiceUUIDs[0] ?? ""
  426. return {
  427. deviceId: device.deviceId,
  428. name: device.name,
  429. localName: device.localName,
  430. uuid: uuid,
  431. mac: device.mac,
  432. connectable: device.connectable
  433. }
  434. });
  435. return newDevices
  436. }
  437. isNotEmpty(name) {
  438. let isNot = (name !== '' &&
  439. (name.startsWith("MW_") ||
  440. name.startsWith("MW-") ||
  441. // name.startsWith("猫王") ||
  442. // name.startsWith("妙播") ||
  443. // name.startsWith("AirSmart") ||
  444. name === "le")
  445. )
  446. // if (!isNot && name !== '') {
  447. // console.log('不是猫王设备名称:', name)
  448. // }
  449. return isNot;
  450. }
  451. // 连接到指定设备
  452. async connectToDevice(device) {
  453. var that = this;
  454. return new Promise((resolve, reject) => {
  455. console.log("开始连接蓝牙:", device.deviceId)
  456. wx.createBLEConnection({
  457. deviceId: device.deviceId,
  458. success: (res) => {
  459. that.publicDevice = device
  460. console.log('连接成功:', res);
  461. resolve(true);
  462. },
  463. fail: (err) => {
  464. that.publicDevice = null
  465. console.error('连接失败:', err);
  466. resolve(false);
  467. }
  468. });
  469. });
  470. }
  471. // 发现服务
  472. discoverServices(deviceId) {
  473. var that = this;
  474. console.log('发现服务:', deviceId);
  475. return new Promise((resolve, reject) => {
  476. wx.getBLEDeviceServices({
  477. deviceId: deviceId,
  478. success: (res) => {
  479. // that.publicDevice .services = res.services;
  480. let service_id = "";
  481. for (let i = 0; i < res.services.length; i++) {
  482. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  483. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  484. // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  485. ) {
  486. service_id = res.services[i].uuid;
  487. break;
  488. }
  489. console.log('发现服务1:', service_id);
  490. service_id = res.services[i].uuid;
  491. }
  492. that.publicDevice.serviceId = service_id;
  493. console.log('发现服务2:', service_id);
  494. resolve(service_id);
  495. // resolve(res.services);
  496. },
  497. fail: (err) => {
  498. that.publicDevice.serviceId = null;
  499. console.error('发现服务失败:', err);
  500. reject([]);
  501. }
  502. });
  503. });
  504. }
  505. // 发现特征值 read / write
  506. discoverCharacteristics(deviceId, serviceId) {
  507. var that = this;
  508. console.log('发现特征值:' + deviceId + " , " + serviceId);
  509. // if (deviceId !== that.publicDevice .deviceId) {
  510. // console.log('设备id不匹配')
  511. // return false
  512. // }
  513. return new Promise((resolve, reject) => {
  514. wx.getBLEDeviceCharacteristics({
  515. deviceId: deviceId,
  516. serviceId: serviceId,
  517. success: (res) => {
  518. // that.characteristics[serviceId] = res.characteristics;
  519. console.log('发现特征值2:', res);
  520. // that.publicDevice .characteristics = res.characteristics;
  521. resolve(res.characteristics);
  522. },
  523. fail: (err) => {
  524. that.publicDevice.characteristics = null;
  525. console.error('发现特征值失败:', err);
  526. reject("");
  527. }
  528. });
  529. });
  530. }
  531. // 读取特征值
  532. readCharacteristicValue(characteristicId) {
  533. var that = ths;
  534. console.log('开始读取特征值', characteristicId)
  535. return new Promise((resolve, reject) => {
  536. wx.readBLECharacteristicValue({
  537. deviceId: that.publicDevice.deviceId,
  538. serviceId: that.publicDevice.serviceId,
  539. characteristicId: characteristicId,
  540. success: (res) => {
  541. const name = that.parseBLEValue(res.value); // 解析读取到的值
  542. console.log('读取特征值成功:', name, res);
  543. resolve(res);
  544. },
  545. fail: (err) => {
  546. console.error('读取特征值失败:', err);
  547. reject("");
  548. }
  549. });
  550. });
  551. }
  552. // 解析读取到的设备名称
  553. parseBLEValue(buffer) {
  554. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  555. }
  556. // 监听特征值变化
  557. notifyCharacteristicValueChange(characteristicId, callback) {
  558. var that = this;
  559. console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
  560. wx.notifyBLECharacteristicValueChange({
  561. deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样
  562. serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  563. characteristicId: characteristicId, //notify uuid
  564. state: true,
  565. success: function (res) {
  566. console.log("开启notify 成功")
  567. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  568. wx.onBLECharacteristicValueChange(function (characteristic) {
  569. let buffer = characteristic.value
  570. let dataView = new DataView(buffer)
  571. let dataResult = []
  572. for (let i = 0; i < dataView.byteLength; i++) {
  573. // console.log("0x" + dataView.getUint8(i).toString(16))
  574. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  575. dataResult.push(dataView.getUint8(i))
  576. }
  577. const result = dataResult
  578. console.log("拿到的数据:", result)
  579. if (callback) {
  580. callback(result)
  581. }
  582. })
  583. },
  584. fail: function (res) {
  585. console.log("订阅特征失败:", res)
  586. }
  587. })
  588. }
  589. setWrite(wirte, characteristicId) {
  590. var that = this;
  591. console.log('写入特征值:', characteristicId)
  592. // that.publicDevice .wirte = wirte
  593. that.publicDevice.characteristicId = characteristicId;
  594. }
  595. }
  596. // const ble = new bleManager();
  597. // 导出 bleManager 类
  598. module.exports = bleManager;
  599. // wx.getSetting({
  600. // success(res) {
  601. // if (res.authSetting["scope.userFuzzyLocation"]) {
  602. // // 成功
  603. // // that.getBluetoothStatus();
  604. // console.log("有定位权限")
  605. // resolve(true);
  606. // } else if (res.authSetting["scope.userFuzzyLocation"] === undefined) {
  607. // wx.authorize({
  608. // scope: "scope.userFuzzyLocation",
  609. // success() {
  610. // console.log("再次获取定位权限")
  611. // resolve(that.getSetting());
  612. // }
  613. // });
  614. // } else {
  615. // wx.showModal({
  616. // title: '请打开系统位置获取定位权限',
  617. // success(res) {
  618. // if (res.confirm) {
  619. // console.log('用户点击确定')
  620. // wx.openSetting({
  621. // complete() {
  622. // // that.getSetting();
  623. // // resolve(that.getSetting());
  624. // }
  625. // })
  626. // } else if (res.cancel) {
  627. // console.log('用户点击取消');
  628. // }
  629. // }
  630. // })
  631. // console.log("没有有定位权限")
  632. // reject(false);
  633. // }
  634. // }
  635. // })
  636. // // 获取已连接的蓝牙设备
  637. // getConnectedDevices() {
  638. // var that = this;
  639. // if (!that.isAvailable && !that.hasPermission) {
  640. // return [];
  641. // }
  642. // return new Promise((resolve, reject) => {
  643. // wx.getConnectedBluetoothDevices({
  644. // // services: ["FFC0", "ffc0", "FFC1", "FFC2", "ffc1", "ffc2", "AB00", "ab00", "AB01", "AB02", "FFF1", "fff1", "FFE2", "FFE5",],
  645. // // services: ["ab00", "ffe5", "1111", "FFC0", "FFC1", "FFF1", ],
  646. // // services: [],
  647. // // services: [
  648. // // "0000ab00-0000-1000-8000-00805f9b34fb",
  649. // // "0000ffc0-0000-1000-8000-00805f9b34fb",
  650. // // "0000FFF0-0000-1000-8000-00805F9B34FB",
  651. // // "0000FFF1-0000-1000-8000-00805F9B34FB",
  652. // // "0000FFE5-0000-1000-8000-00805F9B34FB",
  653. // // ],
  654. // success: (res) => {
  655. // console.log('已连接的蓝牙设备==11==:', newDevices);
  656. // let newDevices = that.fiterDevice(res)
  657. // console.log('已连接的蓝牙设备==22==:', newDevices);
  658. // resolve(newDevices);
  659. // },
  660. // fail: (err) => {
  661. // console.error('获取已连接的蓝牙设备失败:', err);
  662. // reject([]);
  663. // }
  664. // });
  665. // });
  666. // }