ble_manager.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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 === "07:F6:F4:66:FB:FA")) {
  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. that.errorDisconnect({ "deviceId": device.deviceId, "state": "offline" })
  468. let publicDevice = that.publicDevice ?? {}
  469. if (device.deviceId == publicDevice.deviceId) {
  470. that.publicDevice = null;
  471. }
  472. }
  473. console.error('连接失败:', err);
  474. resolve(false);
  475. }
  476. });
  477. });
  478. }
  479. // 发送数据到指定设备
  480. async sendData(data, callback) {
  481. var that = this
  482. if (that.publicDevice == null) {
  483. console.log("没有连接设备");
  484. return;
  485. }
  486. return new Promise((resolve, reject) => {
  487. var buffer = null;
  488. // todo 判断是否是buffer
  489. // if (needChange) {
  490. // buffer = data;
  491. // } else {
  492. buffer = new ArrayBuffer(data.length);
  493. // 下面是赋值,不能删
  494. const dataView = new DataView(buffer);
  495. data.forEach((value, index) => {
  496. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  497. });
  498. // }
  499. // let logData = new Uint8Array(buffer);
  500. // console.log('开始发送数据:', buffer);
  501. wx.writeBLECharacteristicValue({
  502. deviceId: that.publicDevice.deviceId,
  503. serviceId: that.publicDevice.serviceId,
  504. characteristicId: that.publicDevice.characteristicId,
  505. value: buffer,
  506. success: (res) => {
  507. // console.log('发送数据成功:', res, callback);
  508. if (callback) {
  509. callback(true)
  510. }
  511. resolve(true);
  512. },
  513. fail: (err) => {
  514. if (callback) {
  515. callback(false)
  516. }
  517. console.log('数据发送失败:', err);
  518. that.errorDisconnect({ "deviceId": that.publicDevice.deviceId, "state": "offline" })
  519. resolve(false);
  520. }
  521. });
  522. });
  523. }
  524. ab2hex(buffer) {
  525. var hexArr = Array.prototype.map.call(
  526. new Uint8Array(buffer),
  527. function (bit) {
  528. return ('00' + bit.toString(16)).slice(-2)
  529. }
  530. )
  531. return hexArr.join(':');
  532. }
  533. fiterDevice(res) {
  534. var that = this;
  535. var devices = res.devices.filter(device => {
  536. const name = device.name || '';
  537. const localName = device.localName || '';
  538. let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName);
  539. if (isNot) {
  540. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  541. let mac = that.ab2hex(device.advertisData)
  542. // console.log(mac)
  543. device.mac = mac
  544. }
  545. return isNot
  546. });
  547. let newDevices = devices.map((device) => {
  548. let uuid = device.advertisServiceUUIDs[0] ?? ""
  549. return {
  550. deviceId: device.deviceId,
  551. name: device.name,
  552. localName: device.localName,
  553. uuid: uuid,
  554. mac: device.mac,
  555. connectable: device.connectable
  556. }
  557. });
  558. return newDevices
  559. }
  560. isNotEmpty(name) {
  561. let isNot = (name !== '' &&
  562. (name.startsWith("MW_") ||
  563. name.startsWith("MW-") ||
  564. // name.startsWith("猫王") ||
  565. // name.startsWith("妙播") ||
  566. // name.startsWith("AirSmart") ||
  567. name === "le")
  568. )
  569. // if (!isNot && name !== '') {
  570. // console.log('不是猫王设备名称:', name)
  571. // }
  572. return isNot;
  573. }
  574. // 发现服务
  575. discoverServices(deviceId) {
  576. var that = this;
  577. console.log('发现服务:', deviceId);
  578. return new Promise((resolve, reject) => {
  579. wx.getBLEDeviceServices({
  580. deviceId: deviceId,
  581. success: (res) => {
  582. // that.publicDevice .services = res.services;
  583. let service_id = "";
  584. for (let i = 0; i < res.services.length; i++) {
  585. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  586. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  587. // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  588. ) {
  589. service_id = res.services[i].uuid;
  590. break;
  591. }
  592. console.log('发现服务1:', service_id);
  593. service_id = res.services[i].uuid;
  594. }
  595. if (that.publicDevice) {
  596. that.publicDevice.serviceId = service_id;
  597. console.log('发现服务2:', that.publicDevice.service_id);
  598. }
  599. resolve(service_id);
  600. // resolve(res.services);
  601. },
  602. fail: (err) => {
  603. if (that.publicDevice) {
  604. that.publicDevice.serviceId = null;
  605. }
  606. console.error('发现服务失败:', err);
  607. reject([]);
  608. }
  609. });
  610. });
  611. }
  612. connect() { }
  613. // 发现特征值 read / write
  614. discoverCharacteristics(deviceId, serviceId) {
  615. var that = this;
  616. console.log('发现特征值:' + deviceId + " , " + serviceId);
  617. // if (deviceId !== that.publicDevice .deviceId) {
  618. // console.log('设备id不匹配')
  619. // return false
  620. // }
  621. return new Promise((resolve, reject) => {
  622. wx.getBLEDeviceCharacteristics({
  623. deviceId: deviceId,
  624. serviceId: serviceId,
  625. success: (res) => {
  626. // that.characteristics[serviceId] = res.characteristics;
  627. console.log('发现特征值2:', res);
  628. // that.publicDevice .characteristics = res.characteristics;
  629. resolve(res.characteristics);
  630. },
  631. fail: (err) => {
  632. if (that.publicDevice) {
  633. that.publicDevice.characteristics = null;
  634. }
  635. console.error('发现特征值失败:', err);
  636. reject("");
  637. }
  638. });
  639. });
  640. }
  641. // 读取特征值
  642. readCharacteristicValue(characteristicId) {
  643. var that = ths;
  644. console.log('开始读取特征值', characteristicId)
  645. return new Promise((resolve, reject) => {
  646. wx.readBLECharacteristicValue({
  647. deviceId: that.publicDevice.deviceId,
  648. serviceId: that.publicDevice.serviceId,
  649. characteristicId: characteristicId,
  650. success: (res) => {
  651. const name = that.parseBLEValue(res.value); // 解析读取到的值
  652. console.log('读取特征值成功:', name, res);
  653. resolve(res);
  654. },
  655. fail: (err) => {
  656. console.error('读取特征值失败:', err);
  657. reject("");
  658. }
  659. });
  660. });
  661. }
  662. // 解析读取到的设备名称
  663. parseBLEValue(buffer) {
  664. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  665. }
  666. // 监听特征值变化
  667. notifyCharacteristicValueChange(characteristicId, callback) {
  668. var that = this;
  669. console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
  670. wx.notifyBLECharacteristicValueChange({
  671. deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样
  672. serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  673. characteristicId: characteristicId, //notify uuid
  674. state: true,
  675. success: function (res) {
  676. console.log("开启notify 成功")
  677. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  678. wx.onBLECharacteristicValueChange(function (characteristic) {
  679. let buffer = characteristic.value
  680. let dataView = new DataView(buffer)
  681. let dataResult = []
  682. for (let i = 0; i < dataView.byteLength; i++) {
  683. // console.log("0x" + dataView.getUint8(i).toString(16))
  684. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  685. dataResult.push(dataView.getUint8(i))
  686. }
  687. const result = dataResult
  688. // console.log("拿到的数据:", result)
  689. if (callback) {
  690. callback(result)
  691. }
  692. })
  693. },
  694. fail: function (res) {
  695. console.log("订阅特征失败:", res)
  696. }
  697. })
  698. }
  699. setWrite(wirte, characteristicId) {
  700. var that = this;
  701. console.log('写入特征值:', characteristicId)
  702. // that.publicDevice .wirte = wirte
  703. that.publicDevice.characteristicId = characteristicId;
  704. }
  705. setStateChangeCallback(callback) {
  706. this.stateChangeCallback = callback;
  707. }
  708. errorDisconnect(result) {
  709. // this.disconnect();
  710. console.log("监听到设备状态变化1:", result.deviceId, result.connected, this.stateChangeCallback);
  711. if (this.stateChangeCallback && result.deviceId) {
  712. this.stateChangeCallback(result);
  713. }
  714. }
  715. }
  716. // const ble = new bleManager();
  717. // 导出 bleManager 类
  718. module.exports = bleManager;