ble_manager.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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 available = await permission_util.openBluetoothAdapter();
  294. that.isAvailable = available;
  295. if (!available) {
  296. that.doStartScaning = false;
  297. that.requestBlueTime = time_util.getCurrentMills();
  298. if (boolean != null) {
  299. boolean(false);
  300. }
  301. return;
  302. }
  303. }
  304. const route_util = require('../utils/route_util');
  305. const route_constant = require('../utils/route_constant');
  306. const indexRoot = route_constant.indexRoot;
  307. const connectBleRoot = route_constant.connectBleRoot;
  308. var lastPageRoute = route_util.getLastPageRoute();
  309. if (lastPageRoute != indexRoot && lastPageRoute != connectBleRoot) {
  310. console.log("搜索蓝牙设备失败,请返回首页0");
  311. return;
  312. }
  313. ///蓝牙连接 做限制
  314. if (lastPageRoute == indexRoot) {
  315. if (that.doStartScaning == true) {
  316. console.log("搜索蓝牙设备失败,请返回首页1");
  317. return;
  318. }
  319. }
  320. that.doStartScaning = true;
  321. var currentMill = time_util.getCurrentMills();
  322. var waitMills = 0;
  323. var reduce = currentMill - that.requestBlueTime;
  324. const dMiliis = 6 * 1000;
  325. if (reduce > 0 && reduce < dMiliis) {
  326. waitMills = dMiliis - reduce;
  327. }
  328. if (waitMills > 0) {
  329. await time_util.delayMills(waitMills);
  330. }
  331. if (callBackConnect == null && lastPageRoute == connectBleRoot) {
  332. that.doStartScaning = false;
  333. return;
  334. }
  335. wx.stopBluetoothDevicesDiscovery({
  336. success: (res) => {
  337. that.search(connectWillDevice, boolean, callBackConnect);
  338. },
  339. fail: (err) => {
  340. that.doStartScaning = false;
  341. that.requestBlueTime = time_util.getCurrentMills();
  342. if (boolean != null) {
  343. boolean(false);
  344. }
  345. }
  346. });
  347. }
  348. search(connectWillDevice, boolean, callBackConnect) {
  349. var that = this;
  350. const time_util = require('./../utils/time_util');
  351. wx.startBluetoothDevicesDiscovery({
  352. allowDuplicatesKey: true,
  353. success: function (res) {
  354. console.log("开始搜索设备", res);
  355. that.getConnectedDevices();
  356. that.doStartScaning = false;
  357. that.requestBlueTime = time_util.getCurrentMills();
  358. if (boolean != null) {
  359. boolean(true);
  360. }
  361. that.setConnectWillDevice(connectWillDevice);
  362. that.setCallBackConnect(callBackConnect);
  363. that.compareList = [];
  364. },
  365. fail(err) {
  366. console.log("开始搜索设备失败", res);
  367. that.doStartScaning = false;
  368. that.requestBlueTime = time_util.getCurrentMills();
  369. if (boolean != null) {
  370. boolean(false);
  371. }
  372. },
  373. })
  374. }
  375. // 停止搜索
  376. stopSearch() {
  377. var that = this;
  378. that.setCallBackConnect(null);
  379. that.setConnectWillDevice(null);
  380. return new Promise((resolve, reject) => {
  381. wx.stopBluetoothDevicesDiscovery({
  382. success: (res) => {
  383. resolve(res);
  384. },
  385. fail: (err) => {
  386. reject('停止搜索失败');
  387. }
  388. });
  389. });
  390. }
  391. closeBle() {
  392. console.log('关闭蓝牙了')
  393. closeBluetoothAdapter();
  394. }
  395. // 断开与指定设备的连接
  396. disconnect(mDevice) {
  397. var that = this;
  398. const strings = require('../utils/strings');
  399. // 没有参数就默认断开现在连接的
  400. let device = mDevice;
  401. if (mDevice != null) {
  402. device = mDevice;
  403. }
  404. if (strings.isEmpty(device)) {
  405. return;
  406. }
  407. let deviceId = device.deviceId
  408. if (strings.isEmpty(deviceId)) {
  409. return;
  410. }
  411. console.log('开始断开连接', device);
  412. return new Promise((resolve, reject) => {
  413. wx.closeBLEConnection({
  414. deviceId: deviceId,
  415. success: (res) => {
  416. let publicDevice = that.publicDevice ?? {}
  417. if (deviceId == publicDevice.deviceId) {
  418. console.log('成功断开连接', res, deviceId);
  419. that.publicDevice = null;
  420. }
  421. resolve(res);
  422. },
  423. fail: (err) => {
  424. console.log('断开连接失败', err);
  425. resolve(err);
  426. }
  427. });
  428. });
  429. }
  430. // 连接到指定设备
  431. async connectToDevice(device) {
  432. var that = this;
  433. if (that.isConnecting) {
  434. // 防止多次进入连接
  435. return;
  436. }
  437. that.isConnecting = true
  438. return new Promise((resolve, reject) => {
  439. console.log("开始连接蓝牙:", device.deviceId)
  440. wx.createBLEConnection({
  441. deviceId: device.deviceId,
  442. success: (res) => {
  443. that.publicDevice = device
  444. console.log('连接成功:', res);
  445. that.isConnecting = false;
  446. resolve(true);
  447. },
  448. fail: (err) => {
  449. // {errno: 1509007, errCode: -1, errMsg: "createBLEConnection:fail:already connect"}
  450. if (err.errno == 1509007) {
  451. that.disconnect({ "deviceId": device.deviceId })
  452. } else {
  453. that.isConnecting = false;
  454. that.errorDisconnect({ "deviceId": device.deviceId, "state": "offline" })
  455. let publicDevice = that.publicDevice ?? {}
  456. if (device.deviceId == publicDevice.deviceId) {
  457. that.publicDevice = null;
  458. }
  459. }
  460. console.error('连接失败:', err);
  461. resolve(false);
  462. }
  463. });
  464. });
  465. }
  466. // 发送数据到指定设备
  467. async sendData(data, callback) {
  468. var that = this
  469. if (that.publicDevice == null) {
  470. console.log("没有连接设备");
  471. return;
  472. }
  473. return new Promise((resolve, reject) => {
  474. var buffer = null;
  475. // todo 判断是否是buffer
  476. // if (needChange) {
  477. // buffer = data;
  478. // } else {
  479. buffer = new ArrayBuffer(data.length);
  480. // 下面是赋值,不能删
  481. const dataView = new DataView(buffer);
  482. data.forEach((value, index) => {
  483. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  484. });
  485. // }
  486. // let logData = new Uint8Array(buffer);
  487. // console.log('开始发送数据:', buffer);
  488. wx.writeBLECharacteristicValue({
  489. deviceId: that.publicDevice.deviceId,
  490. serviceId: that.publicDevice.serviceId,
  491. characteristicId: that.publicDevice.characteristicId,
  492. value: buffer,
  493. success: (res) => {
  494. // console.log('发送数据成功:', res, callback);
  495. if (callback) {
  496. callback(true)
  497. }
  498. resolve(true);
  499. },
  500. fail: (err) => {
  501. if (callback) {
  502. callback(false)
  503. }
  504. console.log('数据发送失败:', err);
  505. that.errorDisconnect({ "deviceId": that.publicDevice.deviceId, "state": "offline" })
  506. resolve(false);
  507. }
  508. });
  509. });
  510. }
  511. ab2hex(buffer) {
  512. var hexArr = Array.prototype.map.call(
  513. new Uint8Array(buffer),
  514. function (bit) {
  515. return ('00' + bit.toString(16)).slice(-2)
  516. }
  517. )
  518. return hexArr.join(':');
  519. }
  520. fiterDevice(res) {
  521. var that = this;
  522. var devices = res.devices.filter(device => {
  523. const name = device.name || '';
  524. const localName = device.localName || '';
  525. let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName);
  526. if (isNot) {
  527. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  528. let mac = that.ab2hex(device.advertisData)
  529. // console.log(mac)
  530. device.mac = mac
  531. }
  532. return isNot
  533. });
  534. let newDevices = devices.map((device) => {
  535. let uuid = device.advertisServiceUUIDs[0] ?? ""
  536. return {
  537. deviceId: device.deviceId,
  538. name: device.name,
  539. localName: device.localName,
  540. uuid: uuid,
  541. mac: device.mac,
  542. connectable: device.connectable
  543. }
  544. });
  545. return newDevices
  546. }
  547. isNotEmpty(name) {
  548. let isNot = (name !== '' &&
  549. (name.startsWith("MW_") ||
  550. name.startsWith("MW-") ||
  551. // name.startsWith("猫王") ||
  552. // name.startsWith("妙播") ||
  553. // name.startsWith("AirSmart") ||
  554. name === "le")
  555. )
  556. // if (!isNot && name !== '') {
  557. // console.log('不是猫王设备名称:', name)
  558. // }
  559. return isNot;
  560. }
  561. // 发现服务
  562. discoverServices(deviceId) {
  563. var that = this;
  564. console.log('发现服务:', deviceId);
  565. return new Promise((resolve, reject) => {
  566. wx.getBLEDeviceServices({
  567. deviceId: deviceId,
  568. success: (res) => {
  569. // that.publicDevice .services = res.services;
  570. let service_id = "";
  571. for (let i = 0; i < res.services.length; i++) {
  572. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  573. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  574. // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  575. ) {
  576. service_id = res.services[i].uuid;
  577. break;
  578. }
  579. console.log('发现服务1:', service_id);
  580. service_id = res.services[i].uuid;
  581. }
  582. if (that.publicDevice) {
  583. that.publicDevice.serviceId = service_id;
  584. console.log('发现服务2:', that.publicDevice.service_id);
  585. }
  586. resolve(service_id);
  587. // resolve(res.services);
  588. },
  589. fail: (err) => {
  590. if (that.publicDevice) {
  591. that.publicDevice.serviceId = null;
  592. }
  593. console.error('发现服务失败:', err);
  594. reject([]);
  595. }
  596. });
  597. });
  598. }
  599. connect() { }
  600. // 发现特征值 read / write
  601. discoverCharacteristics(deviceId, serviceId) {
  602. var that = this;
  603. console.log('发现特征值:' + deviceId + " , " + serviceId);
  604. // if (deviceId !== that.publicDevice .deviceId) {
  605. // console.log('设备id不匹配')
  606. // return false
  607. // }
  608. return new Promise((resolve, reject) => {
  609. wx.getBLEDeviceCharacteristics({
  610. deviceId: deviceId,
  611. serviceId: serviceId,
  612. success: (res) => {
  613. // that.characteristics[serviceId] = res.characteristics;
  614. console.log('发现特征值2:', res);
  615. // that.publicDevice .characteristics = res.characteristics;
  616. resolve(res.characteristics);
  617. },
  618. fail: (err) => {
  619. if (that.publicDevice) {
  620. that.publicDevice.characteristics = null;
  621. }
  622. console.error('发现特征值失败:', err);
  623. reject("");
  624. }
  625. });
  626. });
  627. }
  628. // 读取特征值
  629. readCharacteristicValue(characteristicId) {
  630. var that = ths;
  631. console.log('开始读取特征值', characteristicId)
  632. return new Promise((resolve, reject) => {
  633. wx.readBLECharacteristicValue({
  634. deviceId: that.publicDevice.deviceId,
  635. serviceId: that.publicDevice.serviceId,
  636. characteristicId: characteristicId,
  637. success: (res) => {
  638. const name = that.parseBLEValue(res.value); // 解析读取到的值
  639. console.log('读取特征值成功:', name, res);
  640. resolve(res);
  641. },
  642. fail: (err) => {
  643. console.error('读取特征值失败:', err);
  644. reject("");
  645. }
  646. });
  647. });
  648. }
  649. // 解析读取到的设备名称
  650. parseBLEValue(buffer) {
  651. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  652. }
  653. // 监听特征值变化
  654. notifyCharacteristicValueChange(characteristicId, callback) {
  655. var that = this;
  656. console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
  657. wx.notifyBLECharacteristicValueChange({
  658. deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样
  659. serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  660. characteristicId: characteristicId, //notify uuid
  661. state: true,
  662. success: function (res) {
  663. console.log("开启notify 成功")
  664. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  665. wx.onBLECharacteristicValueChange(function (characteristic) {
  666. let buffer = characteristic.value
  667. let dataView = new DataView(buffer)
  668. let dataResult = []
  669. for (let i = 0; i < dataView.byteLength; i++) {
  670. // console.log("0x" + dataView.getUint8(i).toString(16))
  671. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  672. dataResult.push(dataView.getUint8(i))
  673. }
  674. const result = dataResult
  675. // console.log("拿到的数据:", result)
  676. if (callback) {
  677. callback(result)
  678. }
  679. })
  680. },
  681. fail: function (res) {
  682. console.log("订阅特征失败:", res)
  683. }
  684. })
  685. }
  686. setWrite(wirte, characteristicId) {
  687. var that = this;
  688. console.log('写入特征值:', characteristicId)
  689. // that.publicDevice .wirte = wirte
  690. that.publicDevice.characteristicId = characteristicId;
  691. }
  692. setStateChangeCallback(callback) {
  693. this.stateChangeCallback = callback;
  694. }
  695. errorDisconnect(result) {
  696. // this.disconnect();
  697. console.log("监听到设备状态变化1:", result.deviceId, result.connected, this.stateChangeCallback);
  698. if (this.stateChangeCallback && result.deviceId) {
  699. this.stateChangeCallback(result);
  700. }
  701. }
  702. }
  703. // const ble = new bleManager();
  704. // 导出 bleManager 类
  705. module.exports = bleManager;