ble_manager.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. if (that.publicDevice == null) {
  458. console.log("没有连接设备");
  459. return;
  460. }
  461. return new Promise((resolve, reject) => {
  462. var buffer = null;
  463. // todo 判断是否是buffer
  464. // if (needChange) {
  465. // buffer = data;
  466. // } else {
  467. buffer = new ArrayBuffer(data.length);
  468. // 下面是赋值,不能删
  469. const dataView = new DataView(buffer);
  470. data.forEach((value, index) => {
  471. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  472. });
  473. // }
  474. let logData = new Uint8Array(buffer);
  475. console.log('开始发送数据:', logData);
  476. wx.writeBLECharacteristicValue({
  477. deviceId: that.publicDevice.deviceId,
  478. serviceId: that.publicDevice.serviceId,
  479. characteristicId: that.publicDevice.characteristicId,
  480. value: buffer,
  481. success: (res) => {
  482. if (callback) {
  483. callback(true)
  484. }
  485. resolve(true);
  486. },
  487. fail: (err) => {
  488. if (callback) {
  489. callback(false)
  490. }
  491. console.log('数据发送失败:', err);
  492. resolve(false);
  493. }
  494. });
  495. });
  496. }
  497. ab2hex(buffer) {
  498. var hexArr = Array.prototype.map.call(
  499. new Uint8Array(buffer),
  500. function (bit) {
  501. return ('00' + bit.toString(16)).slice(-2)
  502. }
  503. )
  504. return hexArr.join(':');
  505. }
  506. fiterDevice(res) {
  507. var that = this;
  508. var devices = res.devices.filter(device => {
  509. const name = device.name || '';
  510. const localName = device.localName || '';
  511. let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName);
  512. if (isNot) {
  513. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  514. let mac = that.ab2hex(device.advertisData)
  515. // console.log(mac)
  516. device.mac = mac
  517. }
  518. return isNot
  519. });
  520. let newDevices = devices.map((device) => {
  521. let uuid = device.advertisServiceUUIDs[0] ?? ""
  522. return {
  523. deviceId: device.deviceId,
  524. name: device.name,
  525. localName: device.localName,
  526. uuid: uuid,
  527. mac: device.mac,
  528. connectable: device.connectable
  529. }
  530. });
  531. return newDevices
  532. }
  533. isNotEmpty(name) {
  534. let isNot = (name !== '' &&
  535. (name.startsWith("MW_") ||
  536. name.startsWith("MW-") ||
  537. // name.startsWith("猫王") ||
  538. // name.startsWith("妙播") ||
  539. // name.startsWith("AirSmart") ||
  540. name === "le")
  541. )
  542. // if (!isNot && name !== '') {
  543. // console.log('不是猫王设备名称:', name)
  544. // }
  545. return isNot;
  546. }
  547. // 发现服务
  548. discoverServices(deviceId) {
  549. var that = this;
  550. console.log('发现服务:', deviceId);
  551. return new Promise((resolve, reject) => {
  552. wx.getBLEDeviceServices({
  553. deviceId: deviceId,
  554. success: (res) => {
  555. // that.publicDevice .services = res.services;
  556. let service_id = "";
  557. for (let i = 0; i < res.services.length; i++) {
  558. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  559. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  560. // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  561. ) {
  562. service_id = res.services[i].uuid;
  563. break;
  564. }
  565. console.log('发现服务1:', service_id);
  566. service_id = res.services[i].uuid;
  567. }
  568. that.publicDevice.serviceId = service_id;
  569. console.log('发现服务2:', service_id);
  570. resolve(service_id);
  571. // resolve(res.services);
  572. },
  573. fail: (err) => {
  574. that.publicDevice.serviceId = null;
  575. console.error('发现服务失败:', err);
  576. reject([]);
  577. }
  578. });
  579. });
  580. }
  581. connect() { }
  582. // 发现特征值 read / write
  583. discoverCharacteristics(deviceId, serviceId) {
  584. var that = this;
  585. console.log('发现特征值:' + deviceId + " , " + serviceId);
  586. // if (deviceId !== that.publicDevice .deviceId) {
  587. // console.log('设备id不匹配')
  588. // return false
  589. // }
  590. return new Promise((resolve, reject) => {
  591. wx.getBLEDeviceCharacteristics({
  592. deviceId: deviceId,
  593. serviceId: serviceId,
  594. success: (res) => {
  595. // that.characteristics[serviceId] = res.characteristics;
  596. console.log('发现特征值2:', res);
  597. // that.publicDevice .characteristics = res.characteristics;
  598. resolve(res.characteristics);
  599. },
  600. fail: (err) => {
  601. that.publicDevice.characteristics = null;
  602. console.error('发现特征值失败:', err);
  603. reject("");
  604. }
  605. });
  606. });
  607. }
  608. // 读取特征值
  609. readCharacteristicValue(characteristicId) {
  610. var that = ths;
  611. console.log('开始读取特征值', characteristicId)
  612. return new Promise((resolve, reject) => {
  613. wx.readBLECharacteristicValue({
  614. deviceId: that.publicDevice.deviceId,
  615. serviceId: that.publicDevice.serviceId,
  616. characteristicId: characteristicId,
  617. success: (res) => {
  618. const name = that.parseBLEValue(res.value); // 解析读取到的值
  619. console.log('读取特征值成功:', name, res);
  620. resolve(res);
  621. },
  622. fail: (err) => {
  623. console.error('读取特征值失败:', err);
  624. reject("");
  625. }
  626. });
  627. });
  628. }
  629. // 解析读取到的设备名称
  630. parseBLEValue(buffer) {
  631. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  632. }
  633. // 监听特征值变化
  634. notifyCharacteristicValueChange(characteristicId, callback) {
  635. var that = this;
  636. console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
  637. wx.notifyBLECharacteristicValueChange({
  638. deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样
  639. serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  640. characteristicId: characteristicId, //notify uuid
  641. state: true,
  642. success: function (res) {
  643. console.log("开启notify 成功")
  644. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  645. wx.onBLECharacteristicValueChange(function (characteristic) {
  646. let buffer = characteristic.value
  647. let dataView = new DataView(buffer)
  648. let dataResult = []
  649. for (let i = 0; i < dataView.byteLength; i++) {
  650. // console.log("0x" + dataView.getUint8(i).toString(16))
  651. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  652. dataResult.push(dataView.getUint8(i))
  653. }
  654. const result = dataResult
  655. // console.log("拿到的数据:", result)
  656. if (callback) {
  657. callback(result)
  658. }
  659. })
  660. },
  661. fail: function (res) {
  662. console.log("订阅特征失败:", res)
  663. }
  664. })
  665. }
  666. setWrite(wirte, characteristicId) {
  667. var that = this;
  668. console.log('写入特征值:', characteristicId)
  669. // that.publicDevice .wirte = wirte
  670. that.publicDevice.characteristicId = characteristicId;
  671. }
  672. }
  673. // const ble = new bleManager();
  674. // 导出 bleManager 类
  675. module.exports = bleManager;