ble_manager.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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. that.stateChangeCallback = null;
  17. that.isConnecting = false;
  18. }
  19. ///获取比较的数据
  20. getCompareList() {
  21. return this.compareList;
  22. }
  23. setCompareList(compareList) {
  24. this.compareList = compareList;
  25. }
  26. getDissmissDevice() {
  27. return this.dissmissDevice;
  28. }
  29. setConnectWillDevice(connectWillDevice) {
  30. this.connectWillDevice = connectWillDevice;
  31. }
  32. getCallBackConnect() {
  33. return this.callBackConnect;
  34. }
  35. setCallBackConnect(callBackConnect) {
  36. this.callBackConnect = callBackConnect;
  37. }
  38. /// 监控蓝牙打开状态
  39. initBluetoothAdapter() {
  40. var that = this;
  41. wx.onBluetoothAdapterStateChange(function (res) {
  42. that.isAvailable = res.available;
  43. if (!that.isAvailable) {
  44. that.compareList = [];
  45. that.dissmissDevice = [];
  46. getCurrentPages()[0].closeBlueResetOffline(false, true);
  47. }
  48. });
  49. }
  50. ///监听搜索设备列表
  51. getBluetoothDevices() {
  52. var that = this;
  53. const hex_util = require('./../utils/hex_util');
  54. wx.onBluetoothDeviceFound(function (res) {
  55. ///第一种情况
  56. if (res.deviceId) {
  57. if (that.callBackConnect != null) {
  58. if (that.connectWillDevice != null && res.name == that.connectWillDevice.clientType) {
  59. res.mac = res.advertisData ? hex_util.buf2hex(res.advertisData) : '';
  60. // if (that.callBackConnect != null) {
  61. console.log("1111", res.mac);
  62. if (that.callBackConnect != null) {
  63. that.callBackConnect(res);
  64. }
  65. }
  66. } else {
  67. if (res.name != "") {
  68. if (that.compareList.length > 0) {
  69. var has = false;
  70. for (var i = 0; i < that.compareList.length; i++) {
  71. if (res.deviceId == that.compareList[i].deviceId) {
  72. has = true;
  73. break;
  74. }
  75. }
  76. if (!has) {
  77. that.compareList.push(res);
  78. }
  79. } else {
  80. that.compareList.push(res);
  81. }
  82. }
  83. }
  84. }
  85. ///第二种情况
  86. else if (res.devices) {
  87. if (that.callBackConnect != null) {
  88. for (var i = 0; i < res.devices.length; i++) {
  89. var temp = res.devices[i];
  90. // if (temp.name == "MW-SR1(4G_WIFI)") {
  91. // }
  92. // if (temp.name != null) {
  93. // console.log("2222", temp.name);
  94. // }
  95. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  96. temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
  97. temp.mac2 = that.ab2hex(temp.advertisData ?? "")
  98. // if (that.callBackConnect != null) {
  99. console.log("2222:", temp.mac, ":", temp.mac2, ":", temp.deviceId, temp);
  100. if (that.callBackConnect != null) {
  101. // if (that.callBackConnect != null && (temp.deviceId != "6E:66:C2:CA:74:F8" || temp.deviceId != "1A:B4:E0:40:22:8B")) {
  102. that.callBackConnect(temp);
  103. }
  104. break;
  105. }
  106. }
  107. } else {
  108. for (var i = 0; i < res.devices.length; i++) {
  109. if (res.devices[i].name != "") {
  110. if (that.compareList.length > 0) {
  111. var has = false;
  112. for (var j = 0; j < that.compareList.length; j++) {
  113. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  114. has = true;
  115. break;
  116. }
  117. }
  118. if (!has) {
  119. that.compareList.push(res.devices[i]);
  120. }
  121. } else {
  122. that.compareList.push(res.devices[i]);
  123. }
  124. }
  125. }
  126. }
  127. }
  128. ///第三种情况
  129. else if (res[0]) {
  130. if (that.callBackConnect != null) {
  131. if (that.connectWillDevice != null && res[0].name == that.connectWillDevice.clientType) {
  132. res[0].mac = res[0].advertisData ? hex_util.buf2hex(res[0].advertisData) : '';
  133. // if (that.callBackConnect != null) {
  134. console.log("3333", res.mac);
  135. if (that.callBackConnect != null) {
  136. that.callBackConnect(res[0]);
  137. }
  138. }
  139. } else {
  140. if (res[0].name != "") {
  141. if (that.compareList.length > 0) {
  142. var has = false;
  143. for (var i = 0; i < that.compareList.length; i++) {
  144. if (res[0].deviceId == that.compareList[i].deviceId) {
  145. has = true;
  146. break;
  147. }
  148. }
  149. if (!has) {
  150. that.compareList.push(res[0]);
  151. }
  152. } else {
  153. that.compareList.push(res[0]);
  154. }
  155. }
  156. }
  157. }
  158. });
  159. }
  160. onBLEConnectionStateChange() {
  161. ///监听已连接或没有连接 连接和断开的时候会回调
  162. // {"deviceId":"E4:9F:80:09:40:EC","connected":false}
  163. let that = this;
  164. wx.onBLEConnectionStateChange((result) => {
  165. if (result.connected) {
  166. for (var i = 0; i < that.dissmissDevice.length; i++) {
  167. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  168. that.dissmissDevice.splice(i, 1);
  169. break;
  170. }
  171. }
  172. } else {
  173. var has = false;
  174. for (var i = 0; i < that.dissmissDevice.length; i++) {
  175. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  176. has = true;
  177. break;
  178. }
  179. }
  180. if (!has) {
  181. that.dissmissDevice.push(result);
  182. }
  183. }
  184. // that.disconnect(result)
  185. //断开连接是失败的, 只能监听到下线。
  186. that.errorDisconnect(result);
  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. if (that.isConnecting) {
  397. return;
  398. }
  399. return new Promise((resolve, reject) => {
  400. console.log("开始连接蓝牙:", device.deviceId)
  401. wx.createBLEConnection({
  402. deviceId: device.deviceId,
  403. success: (res) => {
  404. that.publicDevice = device
  405. console.log('连接成功:', res);
  406. that.isConnecting = false;
  407. resolve(true);
  408. },
  409. fail: (err) => {
  410. that.isConnecting = false;
  411. that.publicDevice = null
  412. console.error('连接失败:', err);
  413. resolve(false);
  414. }
  415. });
  416. });
  417. }
  418. // 发送数据到指定设备
  419. async sendData(data, callback) {
  420. var that = this
  421. if (that.publicDevice == null) {
  422. console.log("没有连接设备");
  423. return;
  424. }
  425. return new Promise((resolve, reject) => {
  426. var buffer = null;
  427. // todo 判断是否是buffer
  428. // if (needChange) {
  429. // buffer = data;
  430. // } else {
  431. buffer = new ArrayBuffer(data.length);
  432. // 下面是赋值,不能删
  433. const dataView = new DataView(buffer);
  434. data.forEach((value, index) => {
  435. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  436. });
  437. // }
  438. let logData = new Uint8Array(buffer);
  439. console.log('开始发送数据:', logData);
  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. that.errorDisconnect()
  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. setStateChangeCallback(callback) {
  638. this.stateChangeCallback = callback;
  639. }
  640. errorDisconnect() {
  641. // this.disconnect();
  642. if (this.stateChangeCallback) {
  643. this.stateChangeCallback({ "deviceId": this.publicDevice.deviceId, "state": "offline" });
  644. }
  645. }
  646. }
  647. // const ble = new bleManager();
  648. // 导出 bleManager 类
  649. module.exports = bleManager;