ble_manager.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. // 引入必要的微信小程序 API
  2. // const wx = require('wx');
  3. class bleManager {
  4. constructor() {
  5. var that = this;
  6. that.hasPermission = false;
  7. that.publicDevice = null;
  8. that.connectWillDevice = null;
  9. that.callBackConnect = null;
  10. that.requestBlueTime = 0;
  11. ///正在执行扫描中
  12. that.isAvailable = false;
  13. that.doStartScaning = false;
  14. that.compareList = [];
  15. that.dissmissDevice = [];
  16. that.stateChangeCallback = null;
  17. that.isConnecting = false;
  18. }
  19. ///获取比较的数据
  20. getCompareList() {
  21. return this.compareList;
  22. }
  23. setCompareList(compareList) {
  24. this.compareList = compareList;
  25. }
  26. getDissmissDevice() {
  27. return this.dissmissDevice;
  28. }
  29. setConnectWillDevice(connectWillDevice) {
  30. this.connectWillDevice = connectWillDevice;
  31. }
  32. getCallBackConnect() {
  33. return this.callBackConnect;
  34. }
  35. setCallBackConnect(callBackConnect) {
  36. this.callBackConnect = callBackConnect;
  37. }
  38. /// 监控蓝牙打开状态
  39. initBluetoothAdapter() {
  40. var that = this;
  41. wx.onBluetoothAdapterStateChange(function (res) {
  42. that.isAvailable = res.available;
  43. if (!that.isAvailable) {
  44. that.compareList = [];
  45. that.dissmissDevice = [];
  46. getCurrentPages()[0].closeBlueResetOffline(false, true);
  47. }
  48. });
  49. }
  50. ///监听搜索设备列表 监听设备列表
  51. getBluetoothDevices() {
  52. var that = this;
  53. const hexUtil = require('../utils/hexUtil');
  54. wx.onBluetoothDeviceFound(function (res) {
  55. // console.log("蓝牙设备列表", res.length);
  56. ///第一种情况
  57. if (res.deviceId) {
  58. if (that.callBackConnect != null) {
  59. if (that.connectWillDevice != null && res.name == that.connectWillDevice.clientType) {
  60. res.mac = res.advertisData ? hexUtil.buf2hex(res.advertisData) : '';
  61. // if (that.callBackConnect != null) {
  62. console.log("1111", res.mac);
  63. if (that.callBackConnect != null) {
  64. that.callBackConnect(res);
  65. }
  66. }
  67. } else {
  68. if (res.name != "") {
  69. if (that.compareList.length > 0) {
  70. var has = false;
  71. for (var i = 0; i < that.compareList.length; i++) {
  72. if (res.deviceId == that.compareList[i].deviceId) {
  73. has = true;
  74. break;
  75. }
  76. }
  77. if (!has) {
  78. that.compareList.push(res);
  79. }
  80. } else {
  81. that.compareList.push(res);
  82. }
  83. }
  84. }
  85. }
  86. ///第二种情况
  87. else if (res.devices) {
  88. if (that.callBackConnect != null) {
  89. for (var i = 0; i < res.devices.length; i++) {
  90. var temp = res.devices[i];
  91. // if (temp.name == "MW-SR1(4G_WIFI)") {
  92. // }
  93. // if (temp.name != null) {
  94. // console.log("2222", temp.name);
  95. // }
  96. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  97. temp.mac = temp.advertisData ? hexUtil.buf2hex(temp.advertisData) : '';
  98. temp.mac2 = that.ab2hex(temp.advertisData ?? "")
  99. // if (that.testData(temp)) {
  100. // return
  101. // }
  102. console.log("2222:", temp.mac, ":", temp.mac2, ":", temp.deviceId, temp, temp.connectable);
  103. // if ((temp.deviceId.indexOf("1f:de") ) > -1) {
  104. // that.callBackConnect(temp);
  105. // }
  106. that.callBackConnect(temp);
  107. break;
  108. }
  109. }
  110. } else {
  111. for (var i = 0; i < res.devices.length; i++) {
  112. if (res.devices[i].name != "") {
  113. if (that.compareList.length > 0) {
  114. var has = false;
  115. for (var j = 0; j < that.compareList.length; j++) {
  116. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  117. has = true;
  118. break;
  119. }
  120. }
  121. if (!has) {
  122. that.compareList.push(res.devices[i]);
  123. }
  124. } else {
  125. that.compareList.push(res.devices[i]);
  126. }
  127. }
  128. }
  129. }
  130. }
  131. ///第三种情况
  132. else if (res[0]) {
  133. if (that.callBackConnect != null) {
  134. if (that.connectWillDevice != null && res[0].name == that.connectWillDevice.clientType) {
  135. res[0].mac = res[0].advertisData ? hexUtil.buf2hex(res[0].advertisData) : '';
  136. // if (that.callBackConnect != null) {
  137. console.log("3333", res.mac);
  138. if (that.callBackConnect != null) {
  139. that.callBackConnect(res[0]);
  140. }
  141. }
  142. } else {
  143. if (res[0].name != "") {
  144. if (that.compareList.length > 0) {
  145. var has = false;
  146. for (var i = 0; i < that.compareList.length; i++) {
  147. if (res[0].deviceId == that.compareList[i].deviceId) {
  148. has = true;
  149. break;
  150. }
  151. }
  152. if (!has) {
  153. that.compareList.push(res[0]);
  154. }
  155. } else {
  156. that.compareList.push(res[0]);
  157. }
  158. }
  159. }
  160. }
  161. });
  162. }
  163. onBLEConnectionStateChange() {
  164. ///监听已连接或没有连接 连接和断开的时候会回调
  165. // {"deviceId":"E4:9F:80:09:40:EC","connected":false}
  166. let that = this;
  167. wx.onBLEConnectionStateChange((result) => {
  168. if (result.connected) {
  169. for (var i = 0; i < that.dissmissDevice.length; i++) {
  170. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  171. that.dissmissDevice.splice(i, 1);
  172. break;
  173. }
  174. }
  175. } else {
  176. var has = false;
  177. for (var i = 0; i < that.dissmissDevice.length; i++) {
  178. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  179. has = true;
  180. break;
  181. }
  182. }
  183. if (!has) {
  184. that.dissmissDevice.push(result);
  185. }
  186. }
  187. // that.disconnect(result)
  188. //断开连接是失败的。
  189. console.log("监听到设备状态变化0:", result.deviceId, JSON.stringify(result));
  190. that.errorDisconnect({
  191. "deviceId": result.deviceId,
  192. "state": result.connected ? "online" : "offline"
  193. });
  194. // ///是否已配对
  195. // wx.isBluetoothDevicePaired({
  196. // deviceId: result.deviceId,
  197. // ///{"isPaired":false,"errno":0,"errMsg":"isBluetoothDevicePaired:ok"}
  198. // success: (res) => {
  199. // },
  200. // fail: (err) => {
  201. // }
  202. // })
  203. });
  204. }
  205. ///获取 所有搜索到的蓝牙设备
  206. getConnectedDevices() {
  207. var that = this;
  208. const hexUtil = require('../utils/hexUtil');
  209. // wx.getConnectedBluetoothDevices({
  210. // // services: ['ab00'],
  211. // search: ['ab00', 'ab01', 'ab02', '0000AB00-0000-1000-8000-00805F9B34FB', '0000AB01-0000-1000-8000-00805F9B34FB', '0000AB02-0000-1000-8000-00805F9B34FB'],
  212. // success: (res) => {
  213. // // ble连接上,才会有这个返回
  214. // console.log('根据主服务 UUID 获取已连接的蓝牙设备:', res.devices);
  215. // if (res.devices.length > 0) {
  216. // for (var i = 0; i < res.devices.length; i++) {
  217. // var device = res.devices[i];
  218. // if (device.name != "") {
  219. // that.callBackConnect(device);
  220. // }
  221. // }
  222. // }
  223. // }
  224. // })
  225. wx.getBluetoothDevices({
  226. success: (res) => {
  227. console.log("搜索到的:" + res.length);
  228. if (that.callBackConnect != null) {
  229. for (var i = 0; i < res.devices.length; i++) {
  230. var temp = res.devices[i];
  231. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  232. temp.mac = temp.advertisData ? hexUtil.buf2hex(temp.advertisData) : '';
  233. if (temp.mac) {
  234. console.log("搜索到的" + JSON.stringify(temp));
  235. }
  236. // if (that.callBackConnect != null) {
  237. if (that.testData(temp)) {
  238. return
  239. }
  240. console.log("444:" + JSON.stringify(temp));
  241. // if ((temp.deviceId === "07:F6:F4:66:FB:FA")) {
  242. // that.callBackConnect(temp);
  243. // }
  244. that.callBackConnect(temp);
  245. }
  246. break;
  247. }
  248. } else {
  249. for (var i = 0; i < res.devices.length; i++) {
  250. if (that.compareList.length > 0) {
  251. var has = false;
  252. for (var j = 0; j < that.compareList.length; j++) {
  253. if (res.devices[i].name != "") {
  254. // if (res.devices[i].name == "MW-SR1(4G_WIFI)") {
  255. // console.log("gadsfqewrqewrqwerqrqr==000==" + JSON.stringify(res.devices[i]));
  256. // }
  257. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  258. has = true;
  259. break;
  260. }
  261. }
  262. }
  263. if (!has) {
  264. that.compareList.push(res.devices[i]);
  265. }
  266. } else {
  267. that.compareList.push(res.devices[i]);
  268. }
  269. }
  270. }
  271. },
  272. fail: (err) => {
  273. console.error('获取蓝牙设备列表失败', err);
  274. }
  275. });
  276. }
  277. testData(temp) {
  278. if ((temp.deviceId === "1A:B4:E0:40:22:8B" ||
  279. temp.deviceId === "F3:55:1F:8D:26:A0" ||
  280. temp.deviceId === "3F2F112F-ACB5-3EB3-30DA-93DE6A86228A")) {
  281. return true
  282. }
  283. return false
  284. }
  285. // 开始搜索蓝牙设备
  286. async startScan(connectWillDevice, boolean, callBackConnect) {
  287. var that = this;
  288. ///限制搜索没有打开蓝牙一直询问打开蓝牙
  289. const time_util = require('../utils/timeUtil');
  290. if (!that.isAvailable) {
  291. if (callBackConnect == null) {
  292. return;
  293. }
  294. ///做搜索蓝牙适配器权限
  295. const permissionUtil = require('../utils/permissionUtil');
  296. // var location = await permission_util.getSetting()
  297. // if (!location) {
  298. // if (boolean != null) {
  299. // boolean(false);
  300. // console.log("没有定位权限")
  301. // }
  302. // return
  303. // }
  304. var available = await permissionUtil.openBluetoothAdapter();
  305. that.isAvailable = available;
  306. if (!available) {
  307. that.doStartScaning = false;
  308. that.requestBlueTime = time_util.getCurrentMills();
  309. if (boolean != null) {
  310. boolean(false);
  311. }
  312. return;
  313. }
  314. }
  315. const routeUtil = require('../utils/routeUtil');
  316. const routeRoot = require('../utils/routeRoot');
  317. const index = routeRoot.index;
  318. const connectBleRoot = routeRoot.connectBle;
  319. var lastPageRoute = routeUtil.getLastPageRoute();
  320. if (lastPageRoute != index && lastPageRoute != connectBleRoot) {
  321. console.log("搜索蓝牙设备失败,请返回首页0");
  322. return;
  323. }
  324. ///蓝牙连接 做限制
  325. if (lastPageRoute == index) {
  326. if (that.doStartScaning == true) {
  327. console.log("搜索蓝牙设备失败,请返回首页1");
  328. return;
  329. }
  330. }
  331. that.doStartScaning = true;
  332. var currentMill = time_util.getCurrentMills();
  333. var waitMills = 0;
  334. var reduce = currentMill - that.requestBlueTime;
  335. const dMiliis = 6 * 1000;
  336. if (reduce > 0 && reduce < dMiliis) {
  337. waitMills = dMiliis - reduce;
  338. }
  339. if (waitMills > 0) {
  340. await time_util.delayMills(waitMills);
  341. }
  342. if (callBackConnect == null && lastPageRoute == connectBleRoot) {
  343. that.doStartScaning = false;
  344. return;
  345. }
  346. wx.stopBluetoothDevicesDiscovery({
  347. success: (res) => {
  348. that.search(connectWillDevice, boolean, callBackConnect);
  349. },
  350. fail: (err) => {
  351. that.doStartScaning = false;
  352. that.requestBlueTime = time_util.getCurrentMills();
  353. if (boolean != null) {
  354. boolean(false);
  355. }
  356. }
  357. });
  358. }
  359. search(connectWillDevice, boolean, callBackConnect) {
  360. var that = this;
  361. const timeUtil = require('../utils/timeUtil');
  362. wx.startBluetoothDevicesDiscovery({
  363. allowDuplicatesKey: true,
  364. success: function (res) {
  365. console.log("开始搜索设备", res);
  366. that.getConnectedDevices();
  367. that.doStartScaning = false;
  368. that.requestBlueTime = timeUtil.getCurrentMills();
  369. if (boolean != null) {
  370. boolean(true);
  371. }
  372. that.setConnectWillDevice(connectWillDevice);
  373. that.setCallBackConnect(callBackConnect);
  374. that.compareList = [];
  375. },
  376. fail(err) {
  377. console.log("开始搜索设备失败", err);
  378. that.doStartScaning = false;
  379. that.requestBlueTime = timeUtil.getCurrentMills();
  380. if (err.errMsg.indexOf("location") >= 0) {
  381. wx.showToast({
  382. title: '搜索失败,请检查下手机设置的微信定位权限是否开启',
  383. })
  384. }
  385. if (boolean != null) {
  386. boolean(false);
  387. }
  388. },
  389. })
  390. }
  391. // 停止搜索
  392. stopSearch() {
  393. var that = this;
  394. that.setCallBackConnect(null);
  395. that.setConnectWillDevice(null);
  396. return new Promise((resolve, reject) => {
  397. wx.stopBluetoothDevicesDiscovery({
  398. success: (res) => {
  399. resolve(res);
  400. },
  401. fail: (err) => {
  402. reject('停止搜索失败');
  403. }
  404. });
  405. });
  406. }
  407. closeBle() {
  408. console.log('关闭蓝牙了')
  409. closeBluetoothAdapter();
  410. }
  411. // 断开与指定设备的连接
  412. disconnect(mDevice) {
  413. var that = this;
  414. const strings = require('../utils/strings');
  415. // 没有参数就默认断开现在连接的
  416. let device = mDevice;
  417. if (mDevice != null) {
  418. device = mDevice;
  419. }
  420. if (strings.isEmpty(device)) {
  421. return;
  422. }
  423. let deviceId = device.deviceId
  424. if (strings.isEmpty(deviceId)) {
  425. return;
  426. }
  427. console.log('开始断开连接', device);
  428. return new Promise((resolve, reject) => {
  429. wx.closeBLEConnection({
  430. deviceId: deviceId,
  431. success: (res) => {
  432. let publicDevice = that.publicDevice ?? {}
  433. if (deviceId == publicDevice.deviceId) {
  434. console.log('成功断开连接', res, deviceId);
  435. that.publicDevice = null;
  436. }
  437. resolve(res);
  438. },
  439. fail: (err) => {
  440. console.log('断开连接失败', err);
  441. resolve(err);
  442. }
  443. });
  444. });
  445. }
  446. // 连接到指定设备
  447. async connectToDevice(device) {
  448. var that = this;
  449. if (that.isConnecting) {
  450. // 防止多次进入连接
  451. return;
  452. }
  453. that.isConnecting = true
  454. return new Promise((resolve, reject) => {
  455. console.log("开始连接蓝牙:", device.deviceId)
  456. wx.createBLEConnection({
  457. deviceId: device.deviceId,
  458. success: (res) => {
  459. that.publicDevice = device
  460. console.log('连接成功:', res);
  461. that.isConnecting = false;
  462. wx.setBLEMTU({
  463. deviceId: device.deviceId,
  464. mtu: 128,
  465. success: (mtuRes) => {
  466. console.log("设置mtu成功")
  467. },
  468. fail: (mtuErr) => {
  469. console.log("设置mtu失败:", mtuErr)
  470. }
  471. })
  472. resolve(true);
  473. },
  474. fail: (err) => {
  475. // {errno: 1509007, errCode: -1, errMsg: "createBLEConnection:fail:already connect"}
  476. if (err.errno == 1509007) {
  477. that.disconnect({
  478. "deviceId": device.deviceId
  479. })
  480. } else {
  481. that.isConnecting = false;
  482. console.log("监听到设备状态变化3:", err);
  483. that.errorDisconnect({
  484. "deviceId": device.deviceId,
  485. "state": "offline"
  486. })
  487. let publicDevice = that.publicDevice ?? {}
  488. if (device.deviceId == publicDevice.deviceId) {
  489. that.publicDevice = null;
  490. }
  491. }
  492. console.error('连接失败:', err);
  493. resolve(false);
  494. }
  495. });
  496. });
  497. }
  498. // 发送数据到指定设备
  499. async sendData(data, callback) {
  500. var that = this
  501. if (that.publicDevice == null) {
  502. console.log("没有连接设备");
  503. return;
  504. }
  505. return new Promise((resolve, reject) => {
  506. var buffer = null;
  507. // todo 判断是否是buffer
  508. // if (needChange) {
  509. // buffer = data;
  510. // } else {
  511. buffer = new ArrayBuffer(data.length);
  512. // 下面是赋值,不能删
  513. const dataView = new DataView(buffer);
  514. data.forEach((value, index) => {
  515. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  516. });
  517. // }
  518. // let logData = new Uint8Array(buffer);
  519. // console.log('开始发送数据:', buffer);
  520. wx.writeBLECharacteristicValue({
  521. deviceId: that.publicDevice.deviceId,
  522. serviceId: that.publicDevice.serviceId,
  523. characteristicId: that.publicDevice.characteristicId,
  524. value: buffer,
  525. success: (res) => {
  526. console.log('发送数据成功:', dataView);
  527. if (callback) {
  528. callback(true)
  529. }
  530. resolve(true);
  531. },
  532. fail: (err) => {
  533. if (callback) {
  534. callback(false)
  535. }
  536. console.log('监听到设备状态变化4:', err);
  537. that.errorDisconnect({
  538. "deviceId": that.publicDevice.deviceId,
  539. "state": "offline"
  540. })
  541. resolve(false);
  542. }
  543. });
  544. });
  545. }
  546. ab2hex(buffer) {
  547. var hexArr = Array.prototype.map.call(
  548. new Uint8Array(buffer),
  549. function (bit) {
  550. return ('00' + bit.toString(16)).slice(-2)
  551. }
  552. )
  553. return hexArr.join(':');
  554. }
  555. fiterDevice(res) {
  556. var that = this;
  557. var devices = res.devices.filter(device => {
  558. const name = device.name || '';
  559. const localName = device.localName || '';
  560. let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName);
  561. if (isNot) {
  562. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  563. let mac = that.ab2hex(device.advertisData)
  564. // console.log(mac)
  565. device.mac = mac
  566. }
  567. return isNot
  568. });
  569. let newDevices = devices.map((device) => {
  570. let uuid = device.advertisServiceUUIDs[0] ?? ""
  571. return {
  572. deviceId: device.deviceId,
  573. name: device.name,
  574. localName: device.localName,
  575. uuid: uuid,
  576. mac: device.mac,
  577. connectable: device.connectable
  578. }
  579. });
  580. return newDevices
  581. }
  582. isNotEmpty(name) {
  583. let isNot = (name !== '' &&
  584. (name.startsWith("MW_") ||
  585. name.startsWith("MW-") ||
  586. // name.startsWith("猫王") ||
  587. // name.startsWith("妙播") ||
  588. // name.startsWith("AirSmart") ||
  589. name === "le")
  590. )
  591. // if (!isNot && name !== '') {
  592. // console.log('不是猫王设备名称:', name)
  593. // }
  594. return isNot;
  595. }
  596. // 发现服务
  597. discoverServices(deviceId) {
  598. var that = this;
  599. console.log('发现服务:', deviceId);
  600. return new Promise((resolve, reject) => {
  601. wx.getBLEDeviceServices({
  602. deviceId: deviceId,
  603. success: (res) => {
  604. // that.publicDevice .services = res.services;
  605. let service_id = "";
  606. for (let i = 0; i < res.services.length; i++) {
  607. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  608. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  609. // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  610. ) {
  611. service_id = res.services[i].uuid;
  612. break;
  613. }
  614. console.log('发现服务1:', service_id);
  615. service_id = res.services[i].uuid;
  616. }
  617. if (that.publicDevice) {
  618. that.publicDevice.serviceId = service_id;
  619. console.log('发现服务2:', that.publicDevice.service_id);
  620. }
  621. resolve(service_id);
  622. // resolve(res.services);
  623. },
  624. fail: (err) => {
  625. if (that.publicDevice) {
  626. that.publicDevice.serviceId = null;
  627. }
  628. console.error('发现服务失败:', err);
  629. reject([]);
  630. }
  631. });
  632. });
  633. }
  634. connect() {}
  635. // 发现特征值 read / write
  636. discoverCharacteristics(deviceId, serviceId) {
  637. var that = this;
  638. console.log('发现特征值:' + deviceId + " , " + serviceId);
  639. // if (deviceId !== that.publicDevice .deviceId) {
  640. // console.log('设备id不匹配')
  641. // return false
  642. // }
  643. return new Promise((resolve, reject) => {
  644. wx.getBLEDeviceCharacteristics({
  645. deviceId: deviceId,
  646. serviceId: serviceId,
  647. success: (res) => {
  648. // that.characteristics[serviceId] = res.characteristics;
  649. console.log('发现特征值2:', res);
  650. // that.publicDevice .characteristics = res.characteristics;
  651. resolve(res.characteristics);
  652. },
  653. fail: (err) => {
  654. if (that.publicDevice) {
  655. that.publicDevice.characteristics = null;
  656. }
  657. console.error('发现特征值失败:', err);
  658. reject("");
  659. }
  660. });
  661. });
  662. }
  663. // 读取特征值
  664. readCharacteristicValue(characteristicId) {
  665. var that = ths;
  666. console.log('开始读取特征值', characteristicId)
  667. return new Promise((resolve, reject) => {
  668. wx.readBLECharacteristicValue({
  669. deviceId: that.publicDevice.deviceId,
  670. serviceId: that.publicDevice.serviceId,
  671. characteristicId: characteristicId,
  672. success: (res) => {
  673. const name = that.parseBLEValue(res.value); // 解析读取到的值
  674. console.log('读取特征值成功:', name, res);
  675. resolve(res);
  676. },
  677. fail: (err) => {
  678. console.error('读取特征值失败:', err);
  679. reject("");
  680. }
  681. });
  682. });
  683. }
  684. // 解析读取到的设备名称
  685. parseBLEValue(buffer) {
  686. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  687. }
  688. // 监听特征值变化
  689. notifyCharacteristicValueChange(characteristicId, callback) {
  690. var that = this;
  691. console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
  692. wx.notifyBLECharacteristicValueChange({
  693. deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样
  694. serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  695. characteristicId: characteristicId, //notify uuid
  696. state: true,
  697. success: function (res) {
  698. console.log("开启notify 成功")
  699. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  700. wx.onBLECharacteristicValueChange(function (characteristic) {
  701. let buffer = characteristic.value
  702. let dataView = new DataView(buffer)
  703. let dataResult = []
  704. for (let i = 0; i < dataView.byteLength; i++) {
  705. // console.log("0x" + dataView.getUint8(i).toString(16))
  706. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  707. dataResult.push(dataView.getUint8(i))
  708. }
  709. const result = dataResult
  710. // console.log("拿到的数据:", result)
  711. if (callback) {
  712. callback(result)
  713. }
  714. })
  715. },
  716. fail: function (res) {
  717. console.log("订阅特征失败:", res)
  718. }
  719. })
  720. }
  721. setWrite(wirte, characteristicId) {
  722. var that = this;
  723. console.log('写入特征值:', characteristicId)
  724. // that.publicDevice .wirte = wirte
  725. that.publicDevice.characteristicId = characteristicId;
  726. }
  727. setStateChangeCallback(callback) {
  728. this.stateChangeCallback = callback;
  729. }
  730. errorDisconnect(result) {
  731. // this.disconnect();
  732. console.log("监听到设备状态变化1:", result.deviceId, result.state, this.stateChangeCallback);
  733. if (this.stateChangeCallback && result.deviceId) {
  734. this.stateChangeCallback(result);
  735. }
  736. }
  737. }
  738. // const ble = new bleManager();
  739. // 导出 bleManager 类
  740. module.exports = bleManager;