manager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. class Manager {
  2. constructor() {
  3. var that = this;
  4. ///正在连接中的设备
  5. that.connectWillDevice = null;
  6. ///正在连接的设备,成功后返回的数据
  7. that.callBackConnect = null;
  8. ///搜索过快会失败,给的一定的缓冲时间
  9. that.requestBlueTime = 0;
  10. ///蓝牙是否已打开,是否可用
  11. that.isAvailable = false;
  12. ///蓝牙正在搜索中,则不允许继续搜索
  13. that.doStartScaning = false;
  14. ///蓝牙设备搜索的所有在线设备,用来和现有设备比较
  15. that.compareList = [];
  16. ///离线的所有设备,也可以用来比较
  17. that.dissmissDevice = [];
  18. ///当前蓝牙ble连接设备的相关属性
  19. that.writeCharaterId = "";
  20. that.writeServiceId = "";
  21. that.readCharaterId = "";
  22. that.readServiceId = "";
  23. }
  24. ///获取比较的数据
  25. getCompareList() {
  26. var that = this;
  27. return that.compareList;
  28. }
  29. setCompareList(compareList) {
  30. var that = this;
  31. that.compareList = compareList;
  32. }
  33. getDissmissDevice() {
  34. var that = this;
  35. return that.dissmissDevice;
  36. }
  37. setConnectWillDevice(connectWillDevice) {
  38. var that = this;
  39. that.connectWillDevice = connectWillDevice;
  40. }
  41. getCallBackConnect() {
  42. var that = this;
  43. return that.callBackConnect;
  44. }
  45. setCallBackConnect(callBackConnect) {
  46. this.callBackConnect = callBackConnect;
  47. }
  48. /// 监控蓝牙打开状态
  49. initBlueAdapter() {
  50. var that = this;
  51. wx.onBluetoothAdapterStateChange(function (res) {
  52. that.isAvailable = res.available;
  53. if (!that.isAvailable) {
  54. that.compareList = [];
  55. that.dissmissDevice = [];
  56. getCurrentPages()[0].closeBlueResetOffline(false, true);
  57. }
  58. })
  59. }
  60. ///监听搜索设备列表
  61. listenBlueDevices() {
  62. var that = this;
  63. const hexUtil = require('../hexUtil');
  64. wx.onBluetoothDeviceFound(function (res) {
  65. ///第一种情况
  66. if (res.deviceId) {
  67. if (that.callBackConnect != null) {
  68. if (that.connectWillDevice != null && res.name == that.connectWillDevice.clientType) {
  69. res.mac = res.advertisData ? hexUtil.buf2hex(res.advertisData) : '';
  70. if (that.callBackConnect != null) {
  71. that.callBackConnect(res);
  72. }
  73. }
  74. } else {
  75. if (res.name != "") {
  76. if (that.compareList.length > 0) {
  77. var has = false;
  78. for (var i = 0; i < that.compareList.length; i++) {
  79. if (res.deviceId == that.compareList[i].deviceId) {
  80. has = true;
  81. break;
  82. }
  83. }
  84. if (!has) {
  85. that.compareList.push(res);
  86. }
  87. } else {
  88. that.compareList.push(res);
  89. }
  90. }
  91. }
  92. }
  93. ///第二种情况
  94. else if (res.devices) {
  95. if (that.callBackConnect != null) {
  96. for (var i = 0; i < res.devices.length; i++) {
  97. var temp = res.devices[i];
  98. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  99. temp.mac = temp.advertisData ? hexUtil.buf2hex(temp.advertisData) : '';
  100. temp.mac2 = that.ab2hex(temp.advertisData ?? "")
  101. if (that.callBackConnect != null) {
  102. that.callBackConnect(temp);
  103. }
  104. break;
  105. }
  106. }
  107. } else {
  108. for (var i = 0; i < res.devices.length; i++) {
  109. if (that.compareList.length > 0) {
  110. var has = false;
  111. for (var j = 0; j < that.compareList.length; j++) {
  112. if (res.devices[i].name != "") {
  113. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  114. has = true;
  115. break;
  116. }
  117. }
  118. }
  119. if (!has) {
  120. that.compareList.push(res.devices[i]);
  121. }
  122. } else {
  123. that.compareList.push(res.devices[i]);
  124. }
  125. }
  126. }
  127. }
  128. ///第三种情况
  129. else if (res[0]) {
  130. if (that.callBackConnect != null) {
  131. if (that.connectWillDevice != null && res[0].name == that.connectWillDevice.clientType) {
  132. res[0].mac = res[0].advertisData ? hexUtil.buf2hex(res[0].advertisData) : '';
  133. if (that.callBackConnect != null) {
  134. that.callBackConnect(res[0]);
  135. }
  136. }
  137. } else {
  138. if (res[0].name != "") {
  139. if (that.compareList.length > 0) {
  140. var has = false;
  141. for (var i = 0; i < that.compareList.length; i++) {
  142. if (res[0].deviceId == that.compareList[i].deviceId) {
  143. has = true;
  144. break;
  145. }
  146. }
  147. if (!has) {
  148. that.compareList.push(res[0]);
  149. }
  150. } else {
  151. that.compareList.push(res[0]);
  152. }
  153. }
  154. }
  155. }
  156. });
  157. ///监听 离线和连接成功设备导入
  158. // {"deviceId":"E4:9F:80:09:40:EC","connected":false}
  159. wx.onBLEConnectionStateChange((result) => {
  160. if (result.connected) {
  161. for (var i = 0; i < that.dissmissDevice.length; i++) {
  162. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  163. that.dissmissDevice.splice(i, 1);
  164. break;
  165. }
  166. }
  167. } else {
  168. var has = false;
  169. for (var i = 0; i < that.dissmissDevice.length; i++) {
  170. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  171. has = true;
  172. break;
  173. }
  174. }
  175. if (!has) {
  176. that.dissmissDevice.push(result);
  177. }
  178. }
  179. });
  180. }
  181. // 开始搜索蓝牙设备
  182. async startScan(connectWillDevice, boolean, callBackConnect) {
  183. var that = this;
  184. ///限制搜索没有打开蓝牙一直询问打开蓝牙
  185. if (!that.isAvailable) {
  186. if (callBackConnect == null) {
  187. return;
  188. }
  189. ///做搜索蓝牙适配器权限
  190. const permissionUtil = require('../../utils/permissionUtil');
  191. var available = await permissionUtil.openBluetoothAdapter();
  192. that.isAvailable = available;
  193. if (!available) {
  194. that.doStartScaning = false;
  195. that.requestBlueTime = that.getCurrentMills();
  196. if (boolean != null) {
  197. boolean(false);
  198. }
  199. return;
  200. }
  201. }
  202. const routeUtil = require('../../utils/routeUtil');
  203. const routeRoot = require('../../utils/routeRoot');
  204. const index = routeRoot.index;
  205. const connectBleRoot = routeRoot.connectBleRoot;
  206. var lastPageRoute = routeUtil.getLastPageRoute();
  207. if (lastPageRoute != index && lastPageRoute != connectBleRoot) {
  208. return;
  209. }
  210. ///蓝牙连接 做限制
  211. if (lastPageRoute == index) {
  212. if (that.doStartScaning == true) {
  213. return;
  214. }
  215. }
  216. const timeUtil = require('../../utils/timeUtil');
  217. that.doStartScaning = true;
  218. var currentMill = timeUtil.getCurrentMills();
  219. var waitMills = 0;
  220. var reduce = currentMill - that.requestBlueTime;
  221. const dMills = 6 * 1000;
  222. if (reduce > 0 && reduce < dMills) {
  223. waitMills = dMills - reduce;
  224. }
  225. if (waitMills > 0) {
  226. await timeUtil.delayMills(waitMills);
  227. }
  228. if (callBackConnect == null && lastPageRoute == connectBleRoot) {
  229. that.doStartScaning = false;
  230. return;
  231. }
  232. wx.stopBluetoothDevicesDiscovery({
  233. success: (res) => {
  234. that.search(connectWillDevice, boolean, callBackConnect);
  235. },
  236. fail: (err) => {
  237. that.doStartScaning = false;
  238. that.requestBlueTime = timeUtil.getCurrentMills();
  239. if (boolean != null) {
  240. boolean(false);
  241. }
  242. }
  243. });
  244. }
  245. ///搜索设备
  246. search(connectWillDevice, boolean, callBackConnect) {
  247. var that = this;
  248. const timeUtil = require('../../utils/timeUtil');
  249. wx.startBluetoothDevicesDiscovery({
  250. allowDuplicatesKey: true,
  251. success: function (res) {
  252. // that.getConnectedDevices();
  253. that.doStartScaning = false;
  254. that.requestBlueTime = timeUtil.getCurrentMills();
  255. if (boolean != null) {
  256. boolean(true);
  257. }
  258. that.setConnectWillDevice(connectWillDevice);
  259. that.setCallBackConnect(callBackConnect);
  260. that.compareList = [];
  261. },
  262. fail(err) {
  263. that.doStartScaning = false;
  264. that.requestBlueTime = timeUtil.getCurrentMills();
  265. if (boolean != null) {
  266. boolean(false);
  267. }
  268. },
  269. });
  270. }
  271. // 停止搜索
  272. stopScan() {
  273. var that = this;
  274. that.setCallBackConnect(null);
  275. that.setConnectWillDevice(null);
  276. return new Promise((resolve, reject) => {
  277. wx.stopBluetoothDevicesDiscovery({
  278. success: (res) => {
  279. resolve(res);
  280. },
  281. fail: (err) => {
  282. reject('停止搜索失败');
  283. }
  284. });
  285. });
  286. }
  287. ///开始连接设备
  288. startConnect(device) {
  289. var deviceId = device.deviceId;
  290. return new Promise((resolve, reject) => {
  291. wx.createBLEConnection({
  292. deviceId: deviceId,
  293. success: function (res) {
  294. resolve(true);
  295. },
  296. fail: function (res) {
  297. var errCode = res.errCode;
  298. var errMsg = res.errMsg;
  299. if (errCode == -1 && errMsg == "createBLEConnection:fail:already connect") {
  300. resolve(true);
  301. } else {
  302. resolve(false);
  303. }
  304. }
  305. });
  306. });
  307. }
  308. // 发现服务
  309. discoverServices(device) {
  310. var deviceId = device.deviceId;
  311. return new Promise((resolve, reject) => {
  312. wx.getBLEDeviceServices({
  313. deviceId: deviceId,
  314. success: (res) => {
  315. let service_id = "";
  316. for (let i = 0; i < res.services.length; i++) {
  317. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  318. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  319. ) {
  320. service_id = res.services[i].uuid;
  321. break;
  322. }
  323. service_id = res.services[i].uuid;
  324. }
  325. // if (that.publicDevice) {
  326. // that.publicDevice.serviceId = service_id;
  327. // }
  328. resolve(service_id);
  329. },
  330. fail: (err) => {
  331. reject("");
  332. }
  333. });
  334. });
  335. }
  336. ///初始化 接收数据 获取特征值
  337. getNotifyServices(device) {
  338. var deviceId = device.deviceId;
  339. return new Promise((resolve, reject) => {
  340. wx.getBLEDeviceServices({
  341. deviceId: deviceId,
  342. success: function (res) {
  343. resolve(res.services);
  344. },
  345. fail: function (res) {
  346. resolve("");
  347. }
  348. });
  349. });
  350. }
  351. // 发现服务
  352. discoverServices(device) {
  353. var deviceId = device.deviceId;
  354. return new Promise((resolve, reject) => {
  355. wx.getBLEDeviceServices({
  356. deviceId: deviceId,
  357. success: (res) => {
  358. let service_id = "";
  359. for (let i = 0; i < res.services.length; i++) {
  360. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  361. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  362. ) {
  363. service_id = res.services[i].uuid;
  364. break;
  365. }
  366. service_id = res.services[i].uuid;
  367. }
  368. resolve(service_id);
  369. },
  370. fail: (err) => {
  371. console.error('发现服务失败:', err);
  372. reject("");
  373. }
  374. });
  375. });
  376. }
  377. setWriteServiceId(serviceId) {
  378. var that = this;
  379. that.writeServiceId = serviceId;
  380. }
  381. ///获取设备真正的属性特征值
  382. getCharacteristics(device, failed, readSucceed) {
  383. var that = this;
  384. var deviceId = device.deviceId;
  385. wx.getBLEDeviceCharacteristics({
  386. deviceId: deviceId,
  387. serviceId: that.writeServiceId,
  388. success: function (res) {
  389. that._forProcessDeal(res, failed, readSucceed);
  390. },
  391. fail: (err) => {
  392. failed();
  393. }
  394. });
  395. }
  396. async _forProcessDeal(res, failed, readSucceed) {
  397. var that = this;
  398. const timeUtil = require('../../utils/timeUtil');
  399. var characteristics = res.characteristics;
  400. if (characteristics.length <= 0) {
  401. failed();
  402. return;
  403. }
  404. var isWrited = false;
  405. for (let i = 0; i < characteristics.length; i++) {
  406. var charc = characteristics[i];
  407. ///可以开始写入数据
  408. if (charc.properties.write || charc.properties.writeWithoutResponse) {
  409. isWrited = true;
  410. that.writeCharaterId = charc.uuid;
  411. break;
  412. }
  413. }
  414. if (!isWrited) {
  415. failed();
  416. return;
  417. }
  418. var isReaded = false;
  419. for (let i = 0; i < characteristics.length; i++) {
  420. var charc = characteristics[i];
  421. ///可以开始读取数据
  422. if (charc.properties.notify) {
  423. isReaded = true;
  424. readSucceed(charc.uuid);
  425. break;
  426. }
  427. }
  428. if (!isReaded) {
  429. failed();
  430. return;
  431. }
  432. // for (let i = 0; i < characteristics.length; i++) {
  433. // var charc = characteristics[i];
  434. // ///可以开始读取数据
  435. // if (charc.properties.notify) {
  436. // writeSucceed(charc.uuid);
  437. // }
  438. // ///可以开始写入数据
  439. // if (charc.properties.write || charc.properties.writeWithoutResponse) {
  440. // that.writeCharaterId = charc.uuid;
  441. // readSucceed();
  442. // }
  443. // }
  444. }
  445. // 监听特征值变化
  446. monitorCharacteristicValueChange(device, serviceId, notifyCharaterId) {
  447. return new Promise((resolve, reject) => {
  448. var deviceId = device.deviceId;
  449. wx.notifyBLECharacteristicValueChange({
  450. state: true,
  451. deviceId: deviceId,
  452. serviceId: serviceId,
  453. characteristicId: notifyCharaterId,
  454. success: function (res) {
  455. resolve(true);
  456. },
  457. ///{"errno":1500104,"errMsg":"notifyBLECharacteristicValueChange:fail:no descriptor"}
  458. fail: function (res) {
  459. resolve(false);
  460. }
  461. });
  462. });
  463. }
  464. ///收取到的数据转换为文字
  465. onBLECharacteristicValueChange(device, callback) {
  466. wx.onBLECharacteristicValueChange(function (characteristic) {
  467. //characteristic: {"value":{},"deviceId":"22:10:14:95:F0:1E","serviceId":"0000FFE5-0000-1000-8000-00805F9B34FB","characteristicId":"0000FFE5-0001-1000-8000-00805F9B34FB"}
  468. const hexUtil = require('../hexUtil');
  469. var buffer = characteristic.value
  470. var dataView = new DataView(buffer)
  471. var dataResult = []
  472. for (let i = 0; i < dataView.byteLength; i++) {
  473. dataResult.push(dataView.getUint8(i))
  474. }
  475. var value = hexUtil.buf2string(dataResult);
  476. ///109,113,116,116
  477. ///114,101,99,118,95,102,105,110,105,115,104
  478. callback(value);
  479. });
  480. }
  481. // 断开设备的连接
  482. disconnect(device) {
  483. return new Promise((resolve, reject) => {
  484. var deviceId = device.deviceId;
  485. wx.closeBLEConnection({
  486. deviceId: deviceId,
  487. success: (res) => {
  488. resolve(true);
  489. },
  490. fail: (err) => {
  491. resolve(false);
  492. }
  493. });
  494. });
  495. }
  496. ///发送数据
  497. sendData(device, data) {
  498. var that = this;
  499. return new Promise((resolve, reject) => {
  500. var buffer = new ArrayBuffer(data.length);
  501. // 下面是赋值,不能删
  502. const dataView = new DataView(buffer);
  503. // 将每个16进制数值写入到 buffer 中
  504. data.forEach((value, index) => {
  505. dataView.setUint8(index, value);
  506. });
  507. var deviceId = device.deviceId;
  508. wx.writeBLECharacteristicValue({
  509. deviceId: deviceId,
  510. serviceId: that.writeServiceId,
  511. characteristicId: that.writeCharaterId,
  512. value: buffer,
  513. success: function (res) {
  514. resolve(true);
  515. },
  516. fail(err) {
  517. resolve(false);
  518. }
  519. });
  520. });
  521. }
  522. }
  523. module.exports = Manager;
  524. ///获取设备真正的属性特征值
  525. // getCharacteristics(device, services, index, notify, write, read, succeed, fail) {
  526. // var that = this;
  527. // var deviceId = device.deviceId;
  528. // var serviceId = services[index].uuid;
  529. // wx.getBLEDeviceCharacteristics({
  530. // deviceId: deviceId,
  531. // serviceId: serviceId,
  532. // success: function (res) {
  533. // var notifyCharaterId = "";
  534. // var notifyServiceId = "";
  535. // for (var i = 0; i < res.characteristics.length; i++) {
  536. // var properties = res.characteristics[i].properties;
  537. // var charaterId = res.characteristics[i].uuid;
  538. // if (!notify) {
  539. // if (properties.notify) {
  540. // notifyCharaterId = charaterId;
  541. // notifyServiceId = services[index].uuid;
  542. // notify = true;
  543. // }
  544. // }
  545. // if (!write) {
  546. // if (properties.write) {
  547. // that.writeCharaterId = charaterId;
  548. // that.writeServiceId = services[index].uuid;
  549. // write = true;
  550. // }
  551. // }
  552. // if (!read) {
  553. // if (properties.read) {
  554. // that.readCharaterId = charaterId;
  555. // that.readServiceId = services[index].uuid;
  556. // read = true;
  557. // }
  558. // }
  559. // }
  560. // if (!notify) {
  561. // index++
  562. // if (index == services.length) {
  563. // fail();
  564. // } else {
  565. // that.getCharacteristics(device, services, index, notify, write, read, succeed, fail);
  566. // }
  567. // } else {
  568. // succeed(notifyServiceId, notifyCharaterId);
  569. // }
  570. // }
  571. // })
  572. // }
  573. ///获取 所有搜索过的蓝牙设备
  574. // getConnectedDevices() {
  575. // var that = this;
  576. // const hexUtil = require('../hexUtil');
  577. // wx.getBluetoothDevices({
  578. // success: (res) => {
  579. // if (that.callBackConnect != null) {
  580. // for (var i = 0; i < res.devices.length; i++) {
  581. // var temp = res.devices[i];
  582. // if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  583. // temp.mac = temp.advertisData ? hexUtil.buf2hex(temp.advertisData) : '';
  584. // if (that.callBackConnect != null) {
  585. // that.callBackConnect(temp);
  586. // }
  587. // break;
  588. // }
  589. // }
  590. // } else {
  591. // for (var i = 0; i < res.devices.length; i++) {
  592. // if (that.compareList.length > 0) {
  593. // var has = false;
  594. // for (var j = 0; j < that.compareList.length; j++) {
  595. // if (res.devices[i].name != "") {
  596. // if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  597. // has = true;
  598. // break;
  599. // }
  600. // }
  601. // }
  602. // if (!has) {
  603. // that.compareList.push(res.devices[i]);
  604. // }
  605. // } else {
  606. // that.compareList.push(res.devices[i]);
  607. // }
  608. // }
  609. // }
  610. // },
  611. // fail: (err) => {
  612. // console.error('获取蓝牙设备列表失败', err);
  613. // }
  614. // });
  615. // }