ble_manager.js 19 KB

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