ble_manager.js 20 KB

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