ble_manager.js 21 KB

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