ble_manager.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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) {
  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) {
  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) {
  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. console.log('断开连接', device);
  380. return new Promise((resolve, reject) => {
  381. wx.getConnectedBluetoothDevices({
  382. success: (res) => {
  383. if (res.devices.length > 0) {
  384. wx.closeBLEConnection({
  385. deviceId: deviceId,
  386. success: (res) => {
  387. that.publicDevice = null;
  388. resolve(res);
  389. },
  390. fail: (err) => {
  391. resolve(err);
  392. }
  393. });
  394. } else {
  395. resolve("暂无连接设备");
  396. }
  397. },
  398. fail: (err) => {
  399. resolve(err);
  400. }
  401. });
  402. });
  403. }
  404. // 连接到指定设备
  405. async connectToDevice(device) {
  406. var that = this;
  407. return new Promise((resolve, reject) => {
  408. console.log("开始连接蓝牙:", device.deviceId)
  409. wx.createBLEConnection({
  410. deviceId: device.deviceId,
  411. success: (res) => {
  412. that.publicDevice = device
  413. console.log('连接成功:', res);
  414. resolve(true);
  415. },
  416. fail: (err) => {
  417. that.publicDevice = null
  418. console.error('连接失败:', err);
  419. resolve(false);
  420. }
  421. });
  422. });
  423. }
  424. // 发送数据到指定设备
  425. async sendData(data, callback) {
  426. var that = this
  427. return new Promise((resolve, reject) => {
  428. var buffer = null;
  429. // todo 判断是否是buffer
  430. // if (needChange) {
  431. // buffer = data;
  432. // } else {
  433. buffer = new ArrayBuffer(data.length);
  434. // 下面是赋值,不能删
  435. const dataView = new DataView(buffer);
  436. data.forEach((value, index) => {
  437. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  438. });
  439. // }
  440. // console.log('开始发送数据:', data);
  441. wx.writeBLECharacteristicValue({
  442. deviceId: that.publicDevice.deviceId,
  443. serviceId: that.publicDevice.serviceId,
  444. characteristicId: that.publicDevice.characteristicId,
  445. value: buffer,
  446. success: (res) => {
  447. if (callback) {
  448. callback(true)
  449. }
  450. resolve(true);
  451. },
  452. fail: (err) => {
  453. if (callback) {
  454. callback(false)
  455. }
  456. console.log('数据发送失败:', err);
  457. resolve(false);
  458. }
  459. });
  460. });
  461. }
  462. ab2hex(buffer) {
  463. var hexArr = Array.prototype.map.call(
  464. new Uint8Array(buffer),
  465. function (bit) {
  466. return ('00' + bit.toString(16)).slice(-2)
  467. }
  468. )
  469. return hexArr.join(':');
  470. }
  471. fiterDevice(res) {
  472. var that = this;
  473. var devices = res.devices.filter(device => {
  474. const name = device.name || '';
  475. const localName = device.localName || '';
  476. let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName);
  477. if (isNot) {
  478. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  479. let mac = that.ab2hex(device.advertisData)
  480. // console.log(mac)
  481. device.mac = mac
  482. }
  483. return isNot
  484. });
  485. let newDevices = devices.map((device) => {
  486. let uuid = device.advertisServiceUUIDs[0] ?? ""
  487. return {
  488. deviceId: device.deviceId,
  489. name: device.name,
  490. localName: device.localName,
  491. uuid: uuid,
  492. mac: device.mac,
  493. connectable: device.connectable
  494. }
  495. });
  496. return newDevices
  497. }
  498. isNotEmpty(name) {
  499. let isNot = (name !== '' &&
  500. (name.startsWith("MW_") ||
  501. name.startsWith("MW-") ||
  502. // name.startsWith("猫王") ||
  503. // name.startsWith("妙播") ||
  504. // name.startsWith("AirSmart") ||
  505. name === "le")
  506. )
  507. // if (!isNot && name !== '') {
  508. // console.log('不是猫王设备名称:', name)
  509. // }
  510. return isNot;
  511. }
  512. // 发现服务
  513. discoverServices(deviceId) {
  514. var that = this;
  515. console.log('发现服务:', deviceId);
  516. return new Promise((resolve, reject) => {
  517. wx.getBLEDeviceServices({
  518. deviceId: deviceId,
  519. success: (res) => {
  520. // that.publicDevice .services = res.services;
  521. let service_id = "";
  522. for (let i = 0; i < res.services.length; i++) {
  523. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  524. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  525. // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  526. ) {
  527. service_id = res.services[i].uuid;
  528. break;
  529. }
  530. console.log('发现服务1:', service_id);
  531. service_id = res.services[i].uuid;
  532. }
  533. that.publicDevice.serviceId = service_id;
  534. console.log('发现服务2:', service_id);
  535. resolve(service_id);
  536. // resolve(res.services);
  537. },
  538. fail: (err) => {
  539. that.publicDevice.serviceId = null;
  540. console.error('发现服务失败:', err);
  541. reject([]);
  542. }
  543. });
  544. });
  545. }
  546. connect() { }
  547. // 发现特征值 read / write
  548. discoverCharacteristics(deviceId, serviceId) {
  549. var that = this;
  550. console.log('发现特征值:' + deviceId + " , " + serviceId);
  551. // if (deviceId !== that.publicDevice .deviceId) {
  552. // console.log('设备id不匹配')
  553. // return false
  554. // }
  555. return new Promise((resolve, reject) => {
  556. wx.getBLEDeviceCharacteristics({
  557. deviceId: deviceId,
  558. serviceId: serviceId,
  559. success: (res) => {
  560. // that.characteristics[serviceId] = res.characteristics;
  561. console.log('发现特征值2:', res);
  562. // that.publicDevice .characteristics = res.characteristics;
  563. resolve(res.characteristics);
  564. },
  565. fail: (err) => {
  566. that.publicDevice.characteristics = null;
  567. console.error('发现特征值失败:', err);
  568. reject("");
  569. }
  570. });
  571. });
  572. }
  573. // 读取特征值
  574. readCharacteristicValue(characteristicId) {
  575. var that = ths;
  576. console.log('开始读取特征值', characteristicId)
  577. return new Promise((resolve, reject) => {
  578. wx.readBLECharacteristicValue({
  579. deviceId: that.publicDevice.deviceId,
  580. serviceId: that.publicDevice.serviceId,
  581. characteristicId: characteristicId,
  582. success: (res) => {
  583. const name = that.parseBLEValue(res.value); // 解析读取到的值
  584. console.log('读取特征值成功:', name, res);
  585. resolve(res);
  586. },
  587. fail: (err) => {
  588. console.error('读取特征值失败:', err);
  589. reject("");
  590. }
  591. });
  592. });
  593. }
  594. // 解析读取到的设备名称
  595. parseBLEValue(buffer) {
  596. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  597. }
  598. // 监听特征值变化
  599. notifyCharacteristicValueChange(characteristicId, callback) {
  600. var that = this;
  601. console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
  602. wx.notifyBLECharacteristicValueChange({
  603. deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样
  604. serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  605. characteristicId: characteristicId, //notify uuid
  606. state: true,
  607. success: function (res) {
  608. console.log("开启notify 成功")
  609. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  610. wx.onBLECharacteristicValueChange(function (characteristic) {
  611. let buffer = characteristic.value
  612. let dataView = new DataView(buffer)
  613. let dataResult = []
  614. for (let i = 0; i < dataView.byteLength; i++) {
  615. // console.log("0x" + dataView.getUint8(i).toString(16))
  616. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  617. dataResult.push(dataView.getUint8(i))
  618. }
  619. const result = dataResult
  620. // console.log("拿到的数据:", result)
  621. if (callback) {
  622. callback(result)
  623. }
  624. })
  625. },
  626. fail: function (res) {
  627. console.log("订阅特征失败:", res)
  628. }
  629. })
  630. }
  631. setWrite(wirte, characteristicId) {
  632. var that = this;
  633. console.log('写入特征值:', characteristicId)
  634. // that.publicDevice .wirte = wirte
  635. that.publicDevice.characteristicId = characteristicId;
  636. }
  637. }
  638. // const ble = new bleManager();
  639. // 导出 bleManager 类
  640. module.exports = bleManager;