ble_manager.js 20 KB

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