ble_manager.js 18 KB

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