ble_manager.js 20 KB

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