ble_manager.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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.callBackConnect != null) {
  100. // C8:96:D9:51:37:98
  101. // 1A:B4:E0:40:22:8B
  102. // if (that.callBackConnect != null) {
  103. // || temp.deviceId != "1A:B4:E0:40:22:8B"
  104. // A3:7B:97:45:CC:22
  105. // DA:D5:FB:DC:91:30
  106. if ((temp.deviceId === "1A:B4:E0:40:22:8B")) {
  107. return
  108. }
  109. console.log("2222:", temp.mac, ":", temp.mac2, ":", temp.deviceId, temp, temp.connectable);
  110. // if ((temp.deviceId === "07:F6:F4:66:FB:FA")) {
  111. // that.callBackConnect(temp);
  112. // }
  113. that.callBackConnect(temp);
  114. break;
  115. }
  116. }
  117. } else {
  118. for (var i = 0; i < res.devices.length; i++) {
  119. if (res.devices[i].name != "") {
  120. if (that.compareList.length > 0) {
  121. var has = false;
  122. for (var j = 0; j < that.compareList.length; j++) {
  123. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  124. has = true;
  125. break;
  126. }
  127. }
  128. if (!has) {
  129. that.compareList.push(res.devices[i]);
  130. }
  131. } else {
  132. that.compareList.push(res.devices[i]);
  133. }
  134. }
  135. }
  136. }
  137. }
  138. ///第三种情况
  139. else if (res[0]) {
  140. if (that.callBackConnect != null) {
  141. if (that.connectWillDevice != null && res[0].name == that.connectWillDevice.clientType) {
  142. res[0].mac = res[0].advertisData ? hex_util.buf2hex(res[0].advertisData) : '';
  143. // if (that.callBackConnect != null) {
  144. console.log("3333", res.mac);
  145. if (that.callBackConnect != null) {
  146. that.callBackConnect(res[0]);
  147. }
  148. }
  149. } else {
  150. if (res[0].name != "") {
  151. if (that.compareList.length > 0) {
  152. var has = false;
  153. for (var i = 0; i < that.compareList.length; i++) {
  154. if (res[0].deviceId == that.compareList[i].deviceId) {
  155. has = true;
  156. break;
  157. }
  158. }
  159. if (!has) {
  160. that.compareList.push(res[0]);
  161. }
  162. } else {
  163. that.compareList.push(res[0]);
  164. }
  165. }
  166. }
  167. }
  168. });
  169. }
  170. onBLEConnectionStateChange() {
  171. ///监听已连接或没有连接 连接和断开的时候会回调
  172. // {"deviceId":"E4:9F:80:09:40:EC","connected":false}
  173. let that = this;
  174. wx.onBLEConnectionStateChange((result) => {
  175. if (result.connected) {
  176. for (var i = 0; i < that.dissmissDevice.length; i++) {
  177. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  178. that.dissmissDevice.splice(i, 1);
  179. break;
  180. }
  181. }
  182. } else {
  183. var has = false;
  184. for (var i = 0; i < that.dissmissDevice.length; i++) {
  185. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  186. has = true;
  187. break;
  188. }
  189. }
  190. if (!has) {
  191. that.dissmissDevice.push(result);
  192. }
  193. }
  194. // that.disconnect(result)
  195. //断开连接是失败的, 只能监听到下线。
  196. console.log("监听到设备状态变化0:", result);
  197. that.errorDisconnect(result.connected);
  198. // ///是否已配对
  199. // wx.isBluetoothDevicePaired({
  200. // deviceId: result.deviceId,
  201. // ///{"isPaired":false,"errno":0,"errMsg":"isBluetoothDevicePaired:ok"}
  202. // success: (res) => {
  203. // },
  204. // fail: (err) => {
  205. // }
  206. // })
  207. });
  208. }
  209. ///获取 所有搜索到的蓝牙设备
  210. getConnectedDevices() {
  211. var that = this;
  212. const hex_util = require('./../utils/hex_util');
  213. wx.getConnectedBluetoothDevices({
  214. // services: ['ab00'],
  215. search: ['ab00', 'ab01', 'ab02', '0000AB00-0000-1000-8000-00805F9B34FB', '0000AB01-0000-1000-8000-00805F9B34FB', '0000AB02-0000-1000-8000-00805F9B34FB'],
  216. success: (res) => {
  217. // ble连接上,才会有这个返回
  218. console.log('根据主服务 UUID 获取已连接的蓝牙设备:', res.devices);
  219. if (res.devices.length > 0) {
  220. for (var i = 0; i < res.devices.length; i++) {
  221. var device = res.devices[i];
  222. if (device.name != "") {
  223. that.callBackConnect(device);
  224. }
  225. }
  226. }
  227. }
  228. })
  229. wx.getBluetoothDevices({
  230. success: (res) => {
  231. console.log("搜索到的:" + res.length);
  232. if (that.callBackConnect != null) {
  233. for (var i = 0; i < res.devices.length; i++) {
  234. var temp = res.devices[i];
  235. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  236. temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
  237. if (temp.mac) {
  238. console.log("搜索到的" + JSON.stringify(temp));
  239. }
  240. // if (that.callBackConnect != null) {
  241. if (that.callBackConnect != null) {
  242. if ((temp.deviceId === "1A:B4:E0:40:22:8B")) {
  243. return
  244. }
  245. console.log("444:" + JSON.stringify(temp));
  246. // if ((temp.deviceId === "07:F6:F4:66:FB:FA")) {
  247. // that.callBackConnect(temp);
  248. // }
  249. that.callBackConnect(temp);
  250. }
  251. break;
  252. }
  253. }
  254. } else {
  255. for (var i = 0; i < res.devices.length; i++) {
  256. if (that.compareList.length > 0) {
  257. var has = false;
  258. for (var j = 0; j < that.compareList.length; j++) {
  259. if (res.devices[i].name != "") {
  260. // if (res.devices[i].name == "MW-SR1(4G_WIFI)") {
  261. // console.log("gadsfqewrqewrqwerqrqr==000==" + JSON.stringify(res.devices[i]));
  262. // }
  263. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  264. has = true;
  265. break;
  266. }
  267. }
  268. }
  269. if (!has) {
  270. that.compareList.push(res.devices[i]);
  271. }
  272. } else {
  273. that.compareList.push(res.devices[i]);
  274. }
  275. }
  276. }
  277. },
  278. fail: (err) => {
  279. console.error('获取蓝牙设备列表失败', err);
  280. }
  281. });
  282. }
  283. // 开始搜索蓝牙设备
  284. async startScan(connectWillDevice, boolean, callBackConnect) {
  285. var that = this;
  286. ///限制搜索没有打开蓝牙一直询问打开蓝牙
  287. const time_util = require('./../utils/time_util');
  288. if (!that.isAvailable) {
  289. if (callBackConnect == null) {
  290. return;
  291. }
  292. ///做搜索蓝牙适配器权限
  293. const permission_util = require('../utils/permission_util');
  294. var available = await permission_util.openBluetoothAdapter();
  295. that.isAvailable = available;
  296. if (!available) {
  297. that.doStartScaning = false;
  298. that.requestBlueTime = time_util.getCurrentMills();
  299. if (boolean != null) {
  300. boolean(false);
  301. }
  302. return;
  303. }
  304. }
  305. const route_util = require('../utils/route_util');
  306. const route_constant = require('../utils/route_constant');
  307. const indexRoot = route_constant.indexRoot;
  308. const connectBleRoot = route_constant.connectBleRoot;
  309. var lastPageRoute = route_util.getLastPageRoute();
  310. if (lastPageRoute != indexRoot && lastPageRoute != connectBleRoot) {
  311. console.log("搜索蓝牙设备失败,请返回首页0");
  312. return;
  313. }
  314. ///蓝牙连接 做限制
  315. if (lastPageRoute == indexRoot) {
  316. if (that.doStartScaning == true) {
  317. console.log("搜索蓝牙设备失败,请返回首页1");
  318. return;
  319. }
  320. }
  321. that.doStartScaning = true;
  322. var currentMill = time_util.getCurrentMills();
  323. var waitMills = 0;
  324. var reduce = currentMill - that.requestBlueTime;
  325. const dMiliis = 6 * 1000;
  326. if (reduce > 0 && reduce < dMiliis) {
  327. waitMills = dMiliis - reduce;
  328. }
  329. if (waitMills > 0) {
  330. await time_util.delayMills(waitMills);
  331. }
  332. if (callBackConnect == null && lastPageRoute == connectBleRoot) {
  333. that.doStartScaning = false;
  334. return;
  335. }
  336. wx.stopBluetoothDevicesDiscovery({
  337. success: (res) => {
  338. that.search(connectWillDevice, boolean, callBackConnect);
  339. },
  340. fail: (err) => {
  341. that.doStartScaning = false;
  342. that.requestBlueTime = time_util.getCurrentMills();
  343. if (boolean != null) {
  344. boolean(false);
  345. }
  346. }
  347. });
  348. }
  349. search(connectWillDevice, boolean, callBackConnect) {
  350. var that = this;
  351. const time_util = require('./../utils/time_util');
  352. wx.startBluetoothDevicesDiscovery({
  353. allowDuplicatesKey: true,
  354. success: function (res) {
  355. console.log("开始搜索设备", res);
  356. that.getConnectedDevices();
  357. that.doStartScaning = false;
  358. that.requestBlueTime = time_util.getCurrentMills();
  359. if (boolean != null) {
  360. boolean(true);
  361. }
  362. that.setConnectWillDevice(connectWillDevice);
  363. that.setCallBackConnect(callBackConnect);
  364. that.compareList = [];
  365. },
  366. fail(err) {
  367. console.log("开始搜索设备失败", res);
  368. that.doStartScaning = false;
  369. that.requestBlueTime = time_util.getCurrentMills();
  370. if (boolean != null) {
  371. boolean(false);
  372. }
  373. },
  374. })
  375. }
  376. // 停止搜索
  377. stopSearch() {
  378. var that = this;
  379. that.setCallBackConnect(null);
  380. that.setConnectWillDevice(null);
  381. return new Promise((resolve, reject) => {
  382. wx.stopBluetoothDevicesDiscovery({
  383. success: (res) => {
  384. resolve(res);
  385. },
  386. fail: (err) => {
  387. reject('停止搜索失败');
  388. }
  389. });
  390. });
  391. }
  392. closeBle() {
  393. console.log('关闭蓝牙了')
  394. closeBluetoothAdapter();
  395. }
  396. // 断开与指定设备的连接
  397. disconnect(mDevice) {
  398. var that = this;
  399. const strings = require('../utils/strings');
  400. let device = that.publicDevice;
  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. console.log('成功断开连接', res);
  417. let publicDevice = that.publicDevice ?? {}
  418. if (deviceId == publicDevice.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(false)
  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(false)
  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. that.publicDevice.characteristics = null;
  620. console.error('发现特征值失败:', err);
  621. reject("");
  622. }
  623. });
  624. });
  625. }
  626. // 读取特征值
  627. readCharacteristicValue(characteristicId) {
  628. var that = ths;
  629. console.log('开始读取特征值', characteristicId)
  630. return new Promise((resolve, reject) => {
  631. wx.readBLECharacteristicValue({
  632. deviceId: that.publicDevice.deviceId,
  633. serviceId: that.publicDevice.serviceId,
  634. characteristicId: characteristicId,
  635. success: (res) => {
  636. const name = that.parseBLEValue(res.value); // 解析读取到的值
  637. console.log('读取特征值成功:', name, res);
  638. resolve(res);
  639. },
  640. fail: (err) => {
  641. console.error('读取特征值失败:', err);
  642. reject("");
  643. }
  644. });
  645. });
  646. }
  647. // 解析读取到的设备名称
  648. parseBLEValue(buffer) {
  649. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  650. }
  651. // 监听特征值变化
  652. notifyCharacteristicValueChange(characteristicId, callback) {
  653. var that = this;
  654. console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
  655. wx.notifyBLECharacteristicValueChange({
  656. deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样
  657. serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  658. characteristicId: characteristicId, //notify uuid
  659. state: true,
  660. success: function (res) {
  661. console.log("开启notify 成功")
  662. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  663. wx.onBLECharacteristicValueChange(function (characteristic) {
  664. let buffer = characteristic.value
  665. let dataView = new DataView(buffer)
  666. let dataResult = []
  667. for (let i = 0; i < dataView.byteLength; i++) {
  668. // console.log("0x" + dataView.getUint8(i).toString(16))
  669. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  670. dataResult.push(dataView.getUint8(i))
  671. }
  672. const result = dataResult
  673. // console.log("拿到的数据:", result)
  674. if (callback) {
  675. callback(result)
  676. }
  677. })
  678. },
  679. fail: function (res) {
  680. console.log("订阅特征失败:", res)
  681. }
  682. })
  683. }
  684. setWrite(wirte, characteristicId) {
  685. var that = this;
  686. console.log('写入特征值:', characteristicId)
  687. // that.publicDevice .wirte = wirte
  688. that.publicDevice.characteristicId = characteristicId;
  689. }
  690. setStateChangeCallback(callback) {
  691. this.stateChangeCallback = callback;
  692. }
  693. errorDisconnect(result) {
  694. // this.disconnect();
  695. console.log("监听到设备状态变化:", result, this.stateChangeCallback);
  696. if (this.stateChangeCallback) {
  697. let device = this.publicDevice ?? {};
  698. this.stateChangeCallback({ "deviceId": device.deviceId ?? "", "state": "offline" });
  699. }
  700. }
  701. }
  702. // const ble = new bleManager();
  703. // 导出 bleManager 类
  704. module.exports = bleManager;