ble_manager.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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 hex_util = require('./../utils/hex_util');
  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 ? hex_util.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 ? hex_util.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 ? hex_util.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({ "deviceId": result.deviceId, "state": result.connected ? "online" : "offline" });
  191. // ///是否已配对
  192. // wx.isBluetoothDevicePaired({
  193. // deviceId: result.deviceId,
  194. // ///{"isPaired":false,"errno":0,"errMsg":"isBluetoothDevicePaired:ok"}
  195. // success: (res) => {
  196. // },
  197. // fail: (err) => {
  198. // }
  199. // })
  200. });
  201. }
  202. ///获取 所有搜索到的蓝牙设备
  203. getConnectedDevices() {
  204. var that = this;
  205. const hex_util = require('./../utils/hex_util');
  206. // wx.getConnectedBluetoothDevices({
  207. // // services: ['ab00'],
  208. // search: ['ab00', 'ab01', 'ab02', '0000AB00-0000-1000-8000-00805F9B34FB', '0000AB01-0000-1000-8000-00805F9B34FB', '0000AB02-0000-1000-8000-00805F9B34FB'],
  209. // success: (res) => {
  210. // // ble连接上,才会有这个返回
  211. // console.log('根据主服务 UUID 获取已连接的蓝牙设备:', res.devices);
  212. // if (res.devices.length > 0) {
  213. // for (var i = 0; i < res.devices.length; i++) {
  214. // var device = res.devices[i];
  215. // if (device.name != "") {
  216. // that.callBackConnect(device);
  217. // }
  218. // }
  219. // }
  220. // }
  221. // })
  222. wx.getBluetoothDevices({
  223. success: (res) => {
  224. console.log("搜索到的:" + res.length);
  225. if (that.callBackConnect != null) {
  226. for (var i = 0; i < res.devices.length; i++) {
  227. var temp = res.devices[i];
  228. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  229. temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
  230. if (temp.mac) {
  231. console.log("搜索到的" + JSON.stringify(temp));
  232. }
  233. // if (that.callBackConnect != null) {
  234. if (that.testData(temp)) {
  235. return
  236. }
  237. console.log("444:" + JSON.stringify(temp));
  238. // if ((temp.deviceId === "07:F6:F4:66:FB:FA")) {
  239. // that.callBackConnect(temp);
  240. // }
  241. that.callBackConnect(temp);
  242. }
  243. break;
  244. }
  245. } else {
  246. for (var i = 0; i < res.devices.length; i++) {
  247. if (that.compareList.length > 0) {
  248. var has = false;
  249. for (var j = 0; j < that.compareList.length; j++) {
  250. if (res.devices[i].name != "") {
  251. // if (res.devices[i].name == "MW-SR1(4G_WIFI)") {
  252. // console.log("gadsfqewrqewrqwerqrqr==000==" + JSON.stringify(res.devices[i]));
  253. // }
  254. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  255. has = true;
  256. break;
  257. }
  258. }
  259. }
  260. if (!has) {
  261. that.compareList.push(res.devices[i]);
  262. }
  263. } else {
  264. that.compareList.push(res.devices[i]);
  265. }
  266. }
  267. }
  268. },
  269. fail: (err) => {
  270. console.error('获取蓝牙设备列表失败', err);
  271. }
  272. });
  273. }
  274. testData(temp) {
  275. if ((temp.deviceId === "1A:B4:E0:40:22:8B"
  276. || temp.deviceId === "F3:55:1F:8D:26:A0"
  277. || temp.deviceId === "3F2F112F-ACB5-3EB3-30DA-93DE6A86228A")) {
  278. return true
  279. }
  280. return false
  281. }
  282. // 开始搜索蓝牙设备
  283. async startScan(connectWillDevice, boolean, callBackConnect) {
  284. var that = this;
  285. ///限制搜索没有打开蓝牙一直询问打开蓝牙
  286. const time_util = require('./../utils/time_util');
  287. if (!that.isAvailable) {
  288. if (callBackConnect == null) {
  289. return;
  290. }
  291. ///做搜索蓝牙适配器权限
  292. const permission_util = require('../utils/permission_util');
  293. // var location = await permission_util.getSetting()
  294. // if (!location) {
  295. // if (boolean != null) {
  296. // boolean(false);
  297. // console.log("没有定位权限")
  298. // }
  299. // return
  300. // }
  301. var available = await permission_util.openBluetoothAdapter();
  302. that.isAvailable = available;
  303. if (!available) {
  304. that.doStartScaning = false;
  305. that.requestBlueTime = time_util.getCurrentMills();
  306. if (boolean != null) {
  307. boolean(false);
  308. }
  309. return;
  310. }
  311. }
  312. const route_util = require('../utils/route_util');
  313. const route_constant = require('../utils/route_constant');
  314. const indexRoot = route_constant.indexRoot;
  315. const connectBleRoot = route_constant.connectBleRoot;
  316. var lastPageRoute = route_util.getLastPageRoute();
  317. // if (lastPageRoute != indexRoot && lastPageRoute != connectBleRoot) {
  318. // console.log("搜索蓝牙设备失败,请返回首页0");
  319. // return;
  320. // }
  321. ///蓝牙连接 做限制
  322. if (lastPageRoute == indexRoot) {
  323. if (that.doStartScaning == true) {
  324. console.log("搜索蓝牙设备失败,请返回首页1");
  325. return;
  326. }
  327. }
  328. that.doStartScaning = true;
  329. var currentMill = time_util.getCurrentMills();
  330. var waitMills = 0;
  331. var reduce = currentMill - that.requestBlueTime;
  332. const dMiliis = 6 * 1000;
  333. if (reduce > 0 && reduce < dMiliis) {
  334. waitMills = dMiliis - reduce;
  335. }
  336. if (waitMills > 0) {
  337. await time_util.delayMills(waitMills);
  338. }
  339. if (callBackConnect == null && lastPageRoute == connectBleRoot) {
  340. that.doStartScaning = false;
  341. return;
  342. }
  343. wx.stopBluetoothDevicesDiscovery({
  344. success: (res) => {
  345. that.search(connectWillDevice, boolean, callBackConnect);
  346. },
  347. fail: (err) => {
  348. that.doStartScaning = false;
  349. that.requestBlueTime = time_util.getCurrentMills();
  350. if (boolean != null) {
  351. boolean(false);
  352. }
  353. }
  354. });
  355. }
  356. search(connectWillDevice, boolean, callBackConnect) {
  357. var that = this;
  358. const time_util = require('./../utils/time_util');
  359. wx.startBluetoothDevicesDiscovery({
  360. allowDuplicatesKey: true,
  361. success: function (res) {
  362. console.log("开始搜索设备", res);
  363. that.getConnectedDevices();
  364. that.doStartScaning = false;
  365. that.requestBlueTime = time_util.getCurrentMills();
  366. if (boolean != null) {
  367. boolean(true);
  368. }
  369. that.setConnectWillDevice(connectWillDevice);
  370. that.setCallBackConnect(callBackConnect);
  371. that.compareList = [];
  372. },
  373. fail(err) {
  374. console.log("开始搜索设备失败", err);
  375. that.doStartScaning = false;
  376. that.requestBlueTime = time_util.getCurrentMills();
  377. if (err.errMsg.indexOf("location") >= 0) {
  378. wx.showToast({
  379. title: '搜索失败,请检查下手机设置的微信定位权限是否开启',
  380. })
  381. }
  382. if (boolean != null) {
  383. boolean(false);
  384. }
  385. },
  386. })
  387. }
  388. // 停止搜索
  389. stopSearch() {
  390. var that = this;
  391. that.setCallBackConnect(null);
  392. that.setConnectWillDevice(null);
  393. return new Promise((resolve, reject) => {
  394. wx.stopBluetoothDevicesDiscovery({
  395. success: (res) => {
  396. resolve(res);
  397. },
  398. fail: (err) => {
  399. reject('停止搜索失败');
  400. }
  401. });
  402. });
  403. }
  404. closeBle() {
  405. console.log('关闭蓝牙了')
  406. closeBluetoothAdapter();
  407. }
  408. // 断开与指定设备的连接
  409. disconnect(mDevice) {
  410. var that = this;
  411. const strings = require('../utils/strings');
  412. // 没有参数就默认断开现在连接的
  413. let device = mDevice;
  414. if (mDevice != null) {
  415. device = mDevice;
  416. }
  417. if (strings.isEmpty(device)) {
  418. return;
  419. }
  420. let deviceId = device.deviceId
  421. if (strings.isEmpty(deviceId)) {
  422. return;
  423. }
  424. console.log('开始断开连接', device);
  425. return new Promise((resolve, reject) => {
  426. wx.closeBLEConnection({
  427. deviceId: deviceId,
  428. success: (res) => {
  429. let publicDevice = that.publicDevice ?? {}
  430. if (deviceId == publicDevice.deviceId) {
  431. console.log('成功断开连接', res, deviceId);
  432. that.publicDevice = null;
  433. }
  434. resolve(res);
  435. },
  436. fail: (err) => {
  437. console.log('断开连接失败', err);
  438. resolve(err);
  439. }
  440. });
  441. });
  442. }
  443. // 连接到指定设备
  444. async connectToDevice(device) {
  445. var that = this;
  446. if (that.isConnecting) {
  447. // 防止多次进入连接
  448. return;
  449. }
  450. that.isConnecting = true
  451. return new Promise((resolve, reject) => {
  452. console.log("开始连接蓝牙:", device.deviceId)
  453. wx.createBLEConnection({
  454. deviceId: device.deviceId,
  455. success: (res) => {
  456. that.publicDevice = device
  457. console.log('连接成功:', res);
  458. that.isConnecting = false;
  459. resolve(true);
  460. },
  461. fail: (err) => {
  462. // {errno: 1509007, errCode: -1, errMsg: "createBLEConnection:fail:already connect"}
  463. if (err.errno == 1509007) {
  464. that.disconnect({ "deviceId": device.deviceId })
  465. } else {
  466. that.isConnecting = false;
  467. console.log("监听到设备状态变化3:", err);
  468. that.errorDisconnect({ "deviceId": device.deviceId, "state": "offline" })
  469. let publicDevice = that.publicDevice ?? {}
  470. if (device.deviceId == publicDevice.deviceId) {
  471. that.publicDevice = null;
  472. }
  473. }
  474. console.error('连接失败:', err);
  475. resolve(false);
  476. }
  477. });
  478. });
  479. }
  480. // 发送数据到指定设备
  481. async sendData(data, callback) {
  482. var that = this
  483. if (that.publicDevice == null) {
  484. console.log("没有连接设备");
  485. return;
  486. }
  487. return new Promise((resolve, reject) => {
  488. var buffer = null;
  489. // todo 判断是否是buffer
  490. // if (needChange) {
  491. // buffer = data;
  492. // } else {
  493. buffer = new ArrayBuffer(data.length);
  494. // 下面是赋值,不能删
  495. const dataView = new DataView(buffer);
  496. data.forEach((value, index) => {
  497. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  498. });
  499. // }
  500. // let logData = new Uint8Array(buffer);
  501. // console.log('开始发送数据:', buffer);
  502. wx.writeBLECharacteristicValue({
  503. deviceId: that.publicDevice.deviceId,
  504. serviceId: that.publicDevice.serviceId,
  505. characteristicId: that.publicDevice.characteristicId,
  506. value: buffer,
  507. success: (res) => {
  508. // console.log('发送数据成功:', res, callback);
  509. if (callback) {
  510. callback(true)
  511. }
  512. resolve(true);
  513. },
  514. fail: (err) => {
  515. if (callback) {
  516. callback(false)
  517. }
  518. console.log('监听到设备状态变化4:', err);
  519. that.errorDisconnect({ "deviceId": that.publicDevice.deviceId, "state": "offline" })
  520. resolve(false);
  521. }
  522. });
  523. });
  524. }
  525. ab2hex(buffer) {
  526. var hexArr = Array.prototype.map.call(
  527. new Uint8Array(buffer),
  528. function (bit) {
  529. return ('00' + bit.toString(16)).slice(-2)
  530. }
  531. )
  532. return hexArr.join(':');
  533. }
  534. fiterDevice(res) {
  535. var that = this;
  536. var devices = res.devices.filter(device => {
  537. const name = device.name || '';
  538. const localName = device.localName || '';
  539. let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName);
  540. if (isNot) {
  541. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  542. let mac = that.ab2hex(device.advertisData)
  543. // console.log(mac)
  544. device.mac = mac
  545. }
  546. return isNot
  547. });
  548. let newDevices = devices.map((device) => {
  549. let uuid = device.advertisServiceUUIDs[0] ?? ""
  550. return {
  551. deviceId: device.deviceId,
  552. name: device.name,
  553. localName: device.localName,
  554. uuid: uuid,
  555. mac: device.mac,
  556. connectable: device.connectable
  557. }
  558. });
  559. return newDevices
  560. }
  561. isNotEmpty(name) {
  562. let isNot = (name !== '' &&
  563. (name.startsWith("MW_") ||
  564. name.startsWith("MW-") ||
  565. // name.startsWith("猫王") ||
  566. // name.startsWith("妙播") ||
  567. // name.startsWith("AirSmart") ||
  568. name === "le")
  569. )
  570. // if (!isNot && name !== '') {
  571. // console.log('不是猫王设备名称:', name)
  572. // }
  573. return isNot;
  574. }
  575. // 发现服务
  576. discoverServices(deviceId) {
  577. var that = this;
  578. console.log('发现服务:', deviceId);
  579. return new Promise((resolve, reject) => {
  580. wx.getBLEDeviceServices({
  581. deviceId: deviceId,
  582. success: (res) => {
  583. // that.publicDevice .services = res.services;
  584. let service_id = "";
  585. for (let i = 0; i < res.services.length; i++) {
  586. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  587. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  588. // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  589. ) {
  590. service_id = res.services[i].uuid;
  591. break;
  592. }
  593. console.log('发现服务1:', service_id);
  594. service_id = res.services[i].uuid;
  595. }
  596. if (that.publicDevice) {
  597. that.publicDevice.serviceId = service_id;
  598. console.log('发现服务2:', that.publicDevice.service_id);
  599. }
  600. resolve(service_id);
  601. // resolve(res.services);
  602. },
  603. fail: (err) => {
  604. if (that.publicDevice) {
  605. that.publicDevice.serviceId = null;
  606. }
  607. console.error('发现服务失败:', err);
  608. reject([]);
  609. }
  610. });
  611. });
  612. }
  613. connect() { }
  614. // 发现特征值 read / write
  615. discoverCharacteristics(deviceId, serviceId) {
  616. var that = this;
  617. console.log('发现特征值:' + deviceId + " , " + serviceId);
  618. // if (deviceId !== that.publicDevice .deviceId) {
  619. // console.log('设备id不匹配')
  620. // return false
  621. // }
  622. return new Promise((resolve, reject) => {
  623. wx.getBLEDeviceCharacteristics({
  624. deviceId: deviceId,
  625. serviceId: serviceId,
  626. success: (res) => {
  627. // that.characteristics[serviceId] = res.characteristics;
  628. console.log('发现特征值2:', res);
  629. // that.publicDevice .characteristics = res.characteristics;
  630. resolve(res.characteristics);
  631. },
  632. fail: (err) => {
  633. if (that.publicDevice) {
  634. that.publicDevice.characteristics = null;
  635. }
  636. console.error('发现特征值失败:', err);
  637. reject("");
  638. }
  639. });
  640. });
  641. }
  642. // 读取特征值
  643. readCharacteristicValue(characteristicId) {
  644. var that = ths;
  645. console.log('开始读取特征值', characteristicId)
  646. return new Promise((resolve, reject) => {
  647. wx.readBLECharacteristicValue({
  648. deviceId: that.publicDevice.deviceId,
  649. serviceId: that.publicDevice.serviceId,
  650. characteristicId: characteristicId,
  651. success: (res) => {
  652. const name = that.parseBLEValue(res.value); // 解析读取到的值
  653. console.log('读取特征值成功:', name, res);
  654. resolve(res);
  655. },
  656. fail: (err) => {
  657. console.error('读取特征值失败:', err);
  658. reject("");
  659. }
  660. });
  661. });
  662. }
  663. // 解析读取到的设备名称
  664. parseBLEValue(buffer) {
  665. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  666. }
  667. // 监听特征值变化
  668. notifyCharacteristicValueChange(characteristicId, callback) {
  669. var that = this;
  670. console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
  671. wx.notifyBLECharacteristicValueChange({
  672. deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样
  673. serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  674. characteristicId: characteristicId, //notify uuid
  675. state: true,
  676. success: function (res) {
  677. console.log("开启notify 成功")
  678. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  679. wx.onBLECharacteristicValueChange(function (characteristic) {
  680. let buffer = characteristic.value
  681. let dataView = new DataView(buffer)
  682. let dataResult = []
  683. for (let i = 0; i < dataView.byteLength; i++) {
  684. // console.log("0x" + dataView.getUint8(i).toString(16))
  685. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  686. dataResult.push(dataView.getUint8(i))
  687. }
  688. const result = dataResult
  689. // console.log("拿到的数据:", result)
  690. if (callback) {
  691. callback(result)
  692. }
  693. })
  694. },
  695. fail: function (res) {
  696. console.log("订阅特征失败:", res)
  697. }
  698. })
  699. }
  700. setWrite(wirte, characteristicId) {
  701. var that = this;
  702. console.log('写入特征值:', characteristicId)
  703. // that.publicDevice .wirte = wirte
  704. that.publicDevice.characteristicId = characteristicId;
  705. }
  706. setStateChangeCallback(callback) {
  707. this.stateChangeCallback = callback;
  708. }
  709. errorDisconnect(result) {
  710. // this.disconnect();
  711. console.log("监听到设备状态变化1:", result.deviceId, result.state, this.stateChangeCallback);
  712. if (this.stateChangeCallback && result.deviceId) {
  713. this.stateChangeCallback(result);
  714. }
  715. }
  716. }
  717. // const ble = new bleManager();
  718. // 导出 bleManager 类
  719. module.exports = bleManager;