manager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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 hex_util = require('./../../utils/hex_util');
  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 ? hex_util.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 ? hex_util.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 ? hex_util.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 permission_util = require('../utils/permission_util');
  191. var available = await permission_util.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 route_util = require('../utils/route_util');
  203. const route_constant = require('../utils/route_constant');
  204. const indexRoot = route_constant.indexRoot;
  205. const connectBleRoot = route_constant.connectBleRoot;
  206. var lastPageRoute = route_util.getLastPageRoute();
  207. if (lastPageRoute != indexRoot && lastPageRoute != connectBleRoot) {
  208. return;
  209. }
  210. ///蓝牙连接 做限制
  211. if (lastPageRoute == indexRoot) {
  212. if (that.doStartScaning == true) {
  213. return;
  214. }
  215. }
  216. const time_util = require('./../../utils/time_util');
  217. that.doStartScaning = true;
  218. var currentMill = time_util.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 time_util.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 = time_util.getCurrentMills();
  239. if (boolean != null) {
  240. boolean(false);
  241. }
  242. }
  243. });
  244. }
  245. ///搜索设备
  246. search(connectWillDevice, boolean, callBackConnect) {
  247. var that = this;
  248. const time_util = require('./../../utils/time_util');
  249. wx.startBluetoothDevicesDiscovery({
  250. allowDuplicatesKey: true,
  251. success: function (res) {
  252. // that.getConnectedDevices();
  253. that.doStartScaning = false;
  254. that.requestBlueTime = time_util.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 = time_util.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. console.log("gadsfasdfadfaf===mmm==" + JSON.stringify(res));
  295. resolve(true);
  296. },
  297. fail: function (res) {
  298. console.log("gadsfasdfadfaf===nnn==" + JSON.stringify(res));
  299. var errCode = res.errCode;
  300. var errMsg = res.errMsg;
  301. if (errCode == -1 && errMsg == "createBLEConnection:fail:already connect") {
  302. resolve(true);
  303. } else {
  304. resolve(false);
  305. }
  306. }
  307. });
  308. });
  309. }
  310. // 发现服务
  311. discoverServices(device) {
  312. var deviceId = device.deviceId;
  313. return new Promise((resolve, reject) => {
  314. wx.getBLEDeviceServices({
  315. deviceId: deviceId,
  316. success: (res) => {
  317. let service_id = "";
  318. for (let i = 0; i < res.services.length; i++) {
  319. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  320. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  321. ) {
  322. service_id = res.services[i].uuid;
  323. break;
  324. }
  325. service_id = res.services[i].uuid;
  326. }
  327. // if (that.publicDevice) {
  328. // that.publicDevice.serviceId = service_id;
  329. // }
  330. resolve(service_id);
  331. },
  332. fail: (err) => {
  333. reject("");
  334. }
  335. });
  336. });
  337. }
  338. ///初始化 接收数据 获取特征值
  339. getNotifyServices(device) {
  340. var deviceId = device.deviceId;
  341. return new Promise((resolve, reject) => {
  342. wx.getBLEDeviceServices({
  343. deviceId: deviceId,
  344. success: function (res) {
  345. console.log("gadsfasdfadfaf===2222==" + JSON.stringify(res));
  346. resolve(res.services);
  347. },
  348. fail: function (res) {
  349. console.log("gadsfasdfadfaf===333==" + JSON.stringify(res));
  350. resolve(null);
  351. }
  352. });
  353. });
  354. }
  355. // 发现服务
  356. discoverServices(device) {
  357. var deviceId = device.deviceId;
  358. return new Promise((resolve, reject) => {
  359. wx.getBLEDeviceServices({
  360. deviceId: deviceId,
  361. success: (res) => {
  362. let service_id = "";
  363. for (let i = 0; i < res.services.length; i++) {
  364. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  365. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  366. ) {
  367. service_id = res.services[i].uuid;
  368. break;
  369. }
  370. service_id = res.services[i].uuid;
  371. }
  372. resolve(service_id);
  373. },
  374. fail: (err) => {
  375. console.error('发现服务失败:', err);
  376. reject("");
  377. }
  378. });
  379. });
  380. }
  381. // 发现特征值 read / write
  382. discoverCharacteristics(device, serviceId) {
  383. var deviceId = device.deviceId;
  384. return new Promise((resolve, reject) => {
  385. wx.getBLEDeviceCharacteristics({
  386. deviceId: deviceId,
  387. serviceId: serviceId,
  388. success: (res) => {
  389. resolve(res.characteristics);
  390. },
  391. fail: (err) => {
  392. reject("");
  393. }
  394. });
  395. });
  396. }
  397. ///获取设备真正的属性特征值
  398. getCharacteristics(device, serviceId, failed, getMessageCall, successed) {
  399. var that = this;
  400. var deviceId = device.deviceId;
  401. wx.getBLEDeviceCharacteristics({
  402. deviceId: deviceId,
  403. serviceId: serviceId,
  404. success: function (res) {
  405. var characteristics = res.characteristics;
  406. if (characteristics.length <= 0) {
  407. failed();
  408. return;
  409. }
  410. for (let i = 0; i < characteristics.length; i++) {
  411. var charc = characteristics[i];
  412. var properties = charc.properties;
  413. var charaterId = charc.uuid;
  414. ///可以开始读取数据
  415. if (properties.notify) {
  416. var notifyCharaterId = charaterId;
  417. getMessageCall(notifyCharaterId);
  418. }
  419. ///可以开始写入数据
  420. if (properties.write || properties.writeWithoutResponse) {
  421. that.writeServiceId = serviceId;
  422. that.writeCharaterId = charaterId;
  423. setTimeout(() => {
  424. successed();
  425. }, 100);
  426. }
  427. }
  428. }
  429. });
  430. }
  431. // 监听发送的数据
  432. monitorCharacteristicValueChange(device, notifyServiceId, notifyCharaterId) {
  433. return new Promise((resolve, reject) => {
  434. var deviceId = device.deviceId;
  435. wx.notifyBLECharacteristicValueChange({
  436. state: true,
  437. deviceId: deviceId,
  438. serviceId: notifyServiceId,
  439. characteristicId: notifyCharaterId,
  440. success: function (res) {
  441. resolve(true);
  442. },
  443. fail: function (res) {
  444. resolve(false);
  445. }
  446. });
  447. });
  448. }
  449. ///收取到的数据转换为文字
  450. onBLECharacteristicValueChange(callback) {
  451. wx.onBLECharacteristicValueChange(function (r) {
  452. console.log("gadsfasdfadfaf===666==" + JSON.stringify(r));
  453. var receiveText = hex_util.buf2string(r);
  454. console.log("gadsfasdfadfaf===777==" + receiveText);
  455. let buffer = characteristic.value
  456. let dataView = new DataView(buffer)
  457. let dataResult = []
  458. for (let i = 0; i < dataView.byteLength; i++) {
  459. dataResult.push(dataView.getUint8(i))
  460. }
  461. callback(dataResult);
  462. });
  463. }
  464. // 断开设备的连接
  465. disconnect(device) {
  466. return new Promise((resolve, reject) => {
  467. var deviceId = device.deviceId;
  468. wx.closeBLEConnection({
  469. deviceId: deviceId,
  470. success: (res) => {
  471. resolve(true);
  472. },
  473. fail: (err) => {
  474. resolve(false);
  475. }
  476. });
  477. });
  478. }
  479. ///发送数据
  480. sendData(device, data) {
  481. return new Promise((resolve, reject) => {
  482. var that = this;
  483. var deviceId = device.deviceId;
  484. var buffer = new ArrayBuffer(data.length);
  485. // 下面是赋值,不能删
  486. const dataView = new DataView(buffer);
  487. for (var i = 0; i < data.length; i++) {
  488. dataView.setUint8(i, data[i]);
  489. }
  490. // data.forEach((value, index) => {
  491. // dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  492. // });
  493. console.log("gadsfasdfadfaf===bbb==" + deviceId);
  494. console.log("gadsfasdfadfaf===ccc==" + that.writeServiceId);
  495. console.log("gadsfasdfadfaf===ddd==" + that.writeCharaterId);
  496. console.log("gadsfasdfadfaf===eee==" + JSON.stringify(buffer));
  497. // serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  498. // characteristicId: characteristicId, //notify uuid
  499. wx.writeBLECharacteristicValue({
  500. deviceId: deviceId,
  501. serviceId: that.writeServiceId,
  502. characteristicId: that.writeCharaterId,
  503. value: buffer,
  504. success: function (res) {
  505. resolve(true);
  506. },
  507. fail(err) {
  508. resolve(false);
  509. }
  510. });
  511. });
  512. }
  513. }
  514. module.exports = Manager;
  515. ///获取设备真正的属性特征值
  516. // getCharacteristics(device, services, index, notify, write, read, succeed, fail) {
  517. // var that = this;
  518. // var deviceId = device.deviceId;
  519. // var serviceId = services[index].uuid;
  520. // wx.getBLEDeviceCharacteristics({
  521. // deviceId: deviceId,
  522. // serviceId: serviceId,
  523. // success: function (res) {
  524. // var notifyCharaterId = "";
  525. // var notifyServiceId = "";
  526. // console.log("gadsfasdfadfaf===xxxx==" + JSON.stringify(res.characteristics));
  527. // for (var i = 0; i < res.characteristics.length; i++) {
  528. // var properties = res.characteristics[i].properties;
  529. // var charaterId = res.characteristics[i].uuid;
  530. // if (!notify) {
  531. // if (properties.notify) {
  532. // notifyCharaterId = charaterId;
  533. // notifyServiceId = services[index].uuid;
  534. // console.log("gadsfasdfadfaf===xxxx==" + properties.write);
  535. // console.log("gadsfasdfadfaf===yyy==" + properties.writeWithoutResponse);
  536. // console.log("gadsfasdfadfaf===zzz==" + JSON.stringify(res.characteristics[i]));
  537. // notify = true;
  538. // }
  539. // }
  540. // if (!write) {
  541. // if (properties.write) {
  542. // that.writeCharaterId = charaterId;
  543. // that.writeServiceId = services[index].uuid;
  544. // write = true;
  545. // }
  546. // }
  547. // if (!read) {
  548. // if (properties.read) {
  549. // that.readCharaterId = charaterId;
  550. // that.readServiceId = services[index].uuid;
  551. // read = true;
  552. // }
  553. // }
  554. // }
  555. // if (!notify) {
  556. // index++
  557. // if (index == services.length) {
  558. // fail();
  559. // } else {
  560. // console.log("gadsfasdfadfaf===yyy==");
  561. // that.getCharacteristics(device, services, index, notify, write, read, succeed, fail);
  562. // }
  563. // } else {
  564. // succeed(notifyServiceId, notifyCharaterId);
  565. // }
  566. // }
  567. // })
  568. // }
  569. ///获取 所有搜索过的蓝牙设备
  570. // getConnectedDevices() {
  571. // var that = this;
  572. // const hex_util = require('./../../utils/hex_util');
  573. // wx.getBluetoothDevices({
  574. // success: (res) => {
  575. // if (that.callBackConnect != null) {
  576. // for (var i = 0; i < res.devices.length; i++) {
  577. // var temp = res.devices[i];
  578. // if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  579. // temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
  580. // if (that.callBackConnect != null) {
  581. // that.callBackConnect(temp);
  582. // }
  583. // break;
  584. // }
  585. // }
  586. // } else {
  587. // for (var i = 0; i < res.devices.length; i++) {
  588. // if (that.compareList.length > 0) {
  589. // var has = false;
  590. // for (var j = 0; j < that.compareList.length; j++) {
  591. // if (res.devices[i].name != "") {
  592. // if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  593. // has = true;
  594. // break;
  595. // }
  596. // }
  597. // }
  598. // if (!has) {
  599. // that.compareList.push(res.devices[i]);
  600. // }
  601. // } else {
  602. // that.compareList.push(res.devices[i]);
  603. // }
  604. // }
  605. // }
  606. // },
  607. // fail: (err) => {
  608. // console.error('获取蓝牙设备列表失败', err);
  609. // }
  610. // });
  611. // }