manager.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. setWriteServiceId(serviceId) {
  382. var that = this;
  383. that.writeServiceId = serviceId;
  384. }
  385. ///获取设备真正的属性特征值
  386. getCharacteristics(device, failed, getMessageCall, successed) {
  387. var that = this;
  388. var deviceId = device.deviceId;
  389. wx.getBLEDeviceCharacteristics({
  390. deviceId: deviceId,
  391. serviceId: that.writeServiceId,
  392. success: function (res) {
  393. that._forProcessDeal(res, failed, getMessageCall, successed);
  394. },
  395. fail: (err) => {
  396. failed();
  397. }
  398. });
  399. }
  400. async _forProcessDeal(res, failed, getMessageCall, successed) {
  401. var that = this;
  402. const time_util = require('./../../utils/time_util');
  403. var characteristics = res.characteristics;
  404. console.log("gadsfasdfadfaf===啊啊啊啊==" + JSON.stringify(characteristics));
  405. if (characteristics.length <= 0) {
  406. failed();
  407. return;
  408. }
  409. for (let i = 0; i < characteristics.length; i++) {
  410. var charc = characteristics[i];
  411. ///可以开始读取数据
  412. if (charc.properties.notify) {
  413. getMessageCall(charc.uuid);
  414. await time_util.delayMills(300);
  415. }
  416. ///可以开始写入数据
  417. if (charc.properties.write || charc.properties.writeWithoutResponse) {
  418. that.writeCharaterId = charc.uuid;
  419. successed();
  420. }
  421. }
  422. }
  423. // 监听特征值变化
  424. monitorCharacteristicValueChange(device, serviceId, notifyCharaterId) {
  425. console.log("gadsfasdfadfaf===wwww==" + device.deviceId + "===" + serviceId +
  426. "===" + notifyCharaterId);
  427. return new Promise((resolve, reject) => {
  428. var deviceId = device.deviceId;
  429. wx.notifyBLECharacteristicValueChange({
  430. state: true,
  431. deviceId: deviceId,
  432. serviceId: serviceId,
  433. characteristicId: notifyCharaterId,
  434. success: function (res) {
  435. console.log("啊是的发生的发生等份===cccc==" + JSON.stringify(res));
  436. resolve(true);
  437. },
  438. fail: function (res) {
  439. console.log("啊是的发生的发生等份===dddd==" + JSON.stringify(res));
  440. resolve(false);
  441. }
  442. });
  443. });
  444. }
  445. ///收取到的数据转换为文字
  446. onBLECharacteristicValueChange(callback) {
  447. wx.onBLECharacteristicValueChange(function (characteristic) {
  448. console.log("gadsfasdfadfaf===666==" + JSON.stringify(r));
  449. var receiveText = hex_util.buf2string(characteristic);
  450. console.log("gadsfasdfadfaf===777==" + receiveText);
  451. let buffer = characteristic.value
  452. let dataView = new DataView(buffer)
  453. let dataResult = []
  454. for (let i = 0; i < dataView.byteLength; i++) {
  455. dataResult.push(dataView.getUint8(i))
  456. }
  457. callback(dataResult);
  458. });
  459. }
  460. // 断开设备的连接
  461. disconnect(device) {
  462. return new Promise((resolve, reject) => {
  463. var deviceId = device.deviceId;
  464. wx.closeBLEConnection({
  465. deviceId: deviceId,
  466. success: (res) => {
  467. resolve(true);
  468. },
  469. fail: (err) => {
  470. resolve(false);
  471. }
  472. });
  473. });
  474. }
  475. ///发送数据
  476. sendData(device, data) {
  477. return new Promise((resolve, reject) => {
  478. var that = this;
  479. var length = data.length;
  480. console.log("gadsfasdfadfaf===hhh==" + length + "===" + data);
  481. var buffer = new ArrayBuffer(length);
  482. // 下面是赋值,不能删
  483. const dataView = new DataView(buffer);
  484. for (var i = 0; i < length; i++) {
  485. console.log("gadsfasdfadfaf===iii==" + i + "===" + data[i]);
  486. dataView.setUint8(i, data[i]);
  487. }
  488. // data.forEach((value, index) => {
  489. // dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  490. // });
  491. console.log("gadsfasdfadfaf===ccc==" + that.writeServiceId);
  492. console.log("gadsfasdfadfaf===ddd==" + that.writeCharaterId);
  493. console.log("gadsfasdfadfaf===eee==" + buffer);
  494. // serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  495. // characteristicId: characteristicId, //notify uuid
  496. var deviceId = device.deviceId;
  497. console.log("gadsfasdfadfaf===bbb==" + deviceId);
  498. wx.writeBLECharacteristicValue({
  499. deviceId: deviceId,
  500. serviceId: that.writeServiceId,
  501. characteristicId: that.writeCharaterId,
  502. value: buffer,
  503. success: function (res) {
  504. resolve(true);
  505. },
  506. fail(err) {
  507. resolve(false);
  508. }
  509. });
  510. });
  511. }
  512. }
  513. module.exports = Manager;
  514. ///获取设备真正的属性特征值
  515. // getCharacteristics(device, services, index, notify, write, read, succeed, fail) {
  516. // var that = this;
  517. // var deviceId = device.deviceId;
  518. // var serviceId = services[index].uuid;
  519. // wx.getBLEDeviceCharacteristics({
  520. // deviceId: deviceId,
  521. // serviceId: serviceId,
  522. // success: function (res) {
  523. // var notifyCharaterId = "";
  524. // var notifyServiceId = "";
  525. // console.log("gadsfasdfadfaf===xxxx==" + JSON.stringify(res.characteristics));
  526. // for (var i = 0; i < res.characteristics.length; i++) {
  527. // var properties = res.characteristics[i].properties;
  528. // var charaterId = res.characteristics[i].uuid;
  529. // if (!notify) {
  530. // if (properties.notify) {
  531. // notifyCharaterId = charaterId;
  532. // notifyServiceId = services[index].uuid;
  533. // console.log("gadsfasdfadfaf===xxxx==" + properties.write);
  534. // console.log("gadsfasdfadfaf===yyy==" + properties.writeWithoutResponse);
  535. // console.log("gadsfasdfadfaf===zzz==" + JSON.stringify(res.characteristics[i]));
  536. // notify = true;
  537. // }
  538. // }
  539. // if (!write) {
  540. // if (properties.write) {
  541. // that.writeCharaterId = charaterId;
  542. // that.writeServiceId = services[index].uuid;
  543. // write = true;
  544. // }
  545. // }
  546. // if (!read) {
  547. // if (properties.read) {
  548. // that.readCharaterId = charaterId;
  549. // that.readServiceId = services[index].uuid;
  550. // read = true;
  551. // }
  552. // }
  553. // }
  554. // if (!notify) {
  555. // index++
  556. // if (index == services.length) {
  557. // fail();
  558. // } else {
  559. // console.log("gadsfasdfadfaf===yyy==");
  560. // that.getCharacteristics(device, services, index, notify, write, read, succeed, fail);
  561. // }
  562. // } else {
  563. // succeed(notifyServiceId, notifyCharaterId);
  564. // }
  565. // }
  566. // })
  567. // }
  568. ///获取 所有搜索过的蓝牙设备
  569. // getConnectedDevices() {
  570. // var that = this;
  571. // const hex_util = require('./../../utils/hex_util');
  572. // wx.getBluetoothDevices({
  573. // success: (res) => {
  574. // if (that.callBackConnect != null) {
  575. // for (var i = 0; i < res.devices.length; i++) {
  576. // var temp = res.devices[i];
  577. // if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  578. // temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
  579. // if (that.callBackConnect != null) {
  580. // that.callBackConnect(temp);
  581. // }
  582. // break;
  583. // }
  584. // }
  585. // } else {
  586. // for (var i = 0; i < res.devices.length; i++) {
  587. // if (that.compareList.length > 0) {
  588. // var has = false;
  589. // for (var j = 0; j < that.compareList.length; j++) {
  590. // if (res.devices[i].name != "") {
  591. // if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  592. // has = true;
  593. // break;
  594. // }
  595. // }
  596. // }
  597. // if (!has) {
  598. // that.compareList.push(res.devices[i]);
  599. // }
  600. // } else {
  601. // that.compareList.push(res.devices[i]);
  602. // }
  603. // }
  604. // }
  605. // },
  606. // fail: (err) => {
  607. // console.error('获取蓝牙设备列表失败', err);
  608. // }
  609. // });
  610. // }