ble_manager.js 23 KB

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