ble_manager.js 21 KB

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