manager.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. console.log("gadsfasdfadfaf===mmm==" + deviceId);
  291. return new Promise((resolve, reject) => {
  292. console.log("gadsfasdfadfaf===oooo==" + deviceId);
  293. wx.createBLEConnection({
  294. deviceId: deviceId,
  295. success: function (res) {
  296. console.log("gadsfasdfadfaf===qqqq==" + JSON.stringify(res));
  297. resolve(true);
  298. },
  299. fail: function (res) {
  300. console.log("gadsfasdfadfaf===ppp==" + JSON.stringify(res));
  301. var errCode = res.errCode;
  302. var errMsg = res.errMsg;
  303. if (errCode == -1 && errMsg == "createBLEConnection:fail:already connect") {
  304. resolve(true);
  305. } else {
  306. resolve(false);
  307. }
  308. }
  309. });
  310. });
  311. }
  312. ///初始化 接收数据 获取特征值
  313. getNotifyServices(device) {
  314. var deviceId = device.deviceId;
  315. console.log("gadsfasdfadfaf===nnn==" + deviceId);
  316. return new Promise((resolve, reject) => {
  317. console.log("gadsfasdfadfaf===ppp==" + deviceId);
  318. wx.getBLEDeviceServices({
  319. deviceId: deviceId,
  320. success: function (res) {
  321. console.log("gadsfasdfadfaf===xxxx==" + JSON.stringify(res));
  322. resolve(res.services);
  323. },
  324. fail: function (res) {
  325. console.log("gadsfasdfadfaf===yyy==" + JSON.stringify(res));
  326. resolve(null);
  327. }
  328. });
  329. });
  330. }
  331. ///获取设备真正的属性特征值
  332. getCharacteristics(device, services, index, notify, write, read, succeed, fail) {
  333. var that = this;
  334. var deviceId = device.deviceId;
  335. wx.getBLEDeviceCharacteristics({
  336. deviceId: deviceId,
  337. serviceId: services[index].uuid,
  338. success: function (res) {
  339. var notifyCharaterId = "";
  340. var notifyServiceId = "";
  341. for (var i = 0; i < res.characteristics.length; i++) {
  342. var properties = res.characteristics[i].properties;
  343. var charaterId = res.characteristics[i].uuid;
  344. if (!notify) {
  345. if (properties.notify) {
  346. notifyCharaterId = charaterId;
  347. notifyServiceId = services[index].uuid;
  348. notify = true;
  349. }
  350. }
  351. if (!write) {
  352. if (properties.write) {
  353. that.writeCharaterId = charaterId;
  354. that.writeServiceId = services[index].uuid;
  355. write = true;
  356. }
  357. }
  358. if (!read) {
  359. if (properties.read) {
  360. that.readCharaterId = charaterId;
  361. that.readServiceId = services[index].uuid;
  362. read = true;
  363. }
  364. }
  365. }
  366. if (!notify) {
  367. index++
  368. if (index == services.length) {
  369. fail();
  370. } else {
  371. that.getCharacteristics(device, services, index, notify, write, read, succeed, fail);
  372. }
  373. } else {
  374. succeed(notifyServiceId, notifyCharaterId);
  375. }
  376. }
  377. })
  378. }
  379. // 监听发送的数据
  380. monitorCharacteristicValueChange(device, notifyServiceId, notifyCharaterId) {
  381. return new Promise((resolve, reject) => {
  382. var deviceId = device.deviceId;
  383. wx.notifyBLECharacteristicValueChange({
  384. state: true,
  385. deviceId: deviceId,
  386. serviceId: notifyServiceId,
  387. characteristicId: notifyCharaterId,
  388. success: function (res) {
  389. resolve(true);
  390. },
  391. fail: function (res) {
  392. resolve(false);
  393. }
  394. });
  395. });
  396. }
  397. ///收取到的数据转换为文字
  398. onBLECharacteristicValueChange(callback) {
  399. wx.onBLECharacteristicValueChange(function (r) {
  400. callback(r.value);
  401. });
  402. }
  403. // 断开设备的连接
  404. disconnect(device) {
  405. return new Promise((resolve, reject) => {
  406. var deviceId = device.deviceId;
  407. wx.closeBLEConnection({
  408. deviceId: deviceId,
  409. success: (res) => {
  410. resolve(true);
  411. },
  412. fail: (err) => {
  413. resolve(false);
  414. }
  415. });
  416. });
  417. }
  418. ///发送数据
  419. sendData(device, text) {
  420. return new Promise((resolve, reject) => {
  421. var that = this;
  422. var deviceId = device.deviceId;
  423. var buffer = new ArrayBuffer(text.length)
  424. var dataView = new Uint8Array(buffer)
  425. for (var i = 0; i < text.length; i++) {
  426. dataView[i] = text.charCodeAt(i)
  427. }
  428. wx.writeBLECharacteristicValue({
  429. deviceId: deviceId,
  430. serviceId: that.writeServiceId,
  431. characteristicId: that.writeCharaterId,
  432. value: buffer,
  433. success: function (res) {
  434. resolve(true);
  435. },
  436. fail(err) {
  437. resolve(false);
  438. }
  439. });
  440. });
  441. }
  442. }
  443. module.exports = Manager;
  444. ///获取 所有搜索过的蓝牙设备
  445. // getConnectedDevices() {
  446. // var that = this;
  447. // const hex_util = require('./../../utils/hex_util');
  448. // wx.getBluetoothDevices({
  449. // success: (res) => {
  450. // if (that.callBackConnect != null) {
  451. // for (var i = 0; i < res.devices.length; i++) {
  452. // var temp = res.devices[i];
  453. // if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  454. // temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
  455. // if (that.callBackConnect != null) {
  456. // that.callBackConnect(temp);
  457. // }
  458. // break;
  459. // }
  460. // }
  461. // } else {
  462. // for (var i = 0; i < res.devices.length; i++) {
  463. // if (that.compareList.length > 0) {
  464. // var has = false;
  465. // for (var j = 0; j < that.compareList.length; j++) {
  466. // if (res.devices[i].name != "") {
  467. // if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  468. // has = true;
  469. // break;
  470. // }
  471. // }
  472. // }
  473. // if (!has) {
  474. // that.compareList.push(res.devices[i]);
  475. // }
  476. // } else {
  477. // that.compareList.push(res.devices[i]);
  478. // }
  479. // }
  480. // }
  481. // },
  482. // fail: (err) => {
  483. // console.error('获取蓝牙设备列表失败', err);
  484. // }
  485. // });
  486. // }