ble_manager.js 20 KB

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