ble_manager.js 18 KB

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