manager.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. module.exports = Manager;
  2. class Manager {
  3. constructor() {
  4. var that = this;
  5. ///正在连接中的设备
  6. that.connectWillDevice = null;
  7. ///正在连接的设备,成功后返回的数据
  8. that.callBackConnect = null;
  9. ///搜索过快会失败,给的一定的缓冲时间
  10. that.requestBlueTime = 0;
  11. ///蓝牙是否已打开,是否可用
  12. that.isAvailable = false;
  13. ///蓝牙正在搜索中,则不允许继续搜索
  14. that.doStartScaning = false;
  15. ///蓝牙设备搜索的所有在线设备,用来和现有设备比较
  16. that.compareList = [];
  17. ///离线的所有设备,也可以用来比较
  18. that.dissmissDevice = [];
  19. ///当前蓝牙ble连接设备的相关属性
  20. that.services = {};
  21. that.serviceIndex = 0;
  22. that.notify = false;
  23. that.write = false;
  24. that.read = false;
  25. that.writeCharaterId = "";
  26. that.writeServiceId = "";
  27. that.notifyCharaterId = "";
  28. that.notifyServiceId = "";
  29. that.readCharaterId = "";
  30. that.readServiceId = "";
  31. }
  32. ///获取比较的数据
  33. getCompareList() {
  34. var that = this;
  35. return that.compareList;
  36. }
  37. setCompareList(compareList) {
  38. var that = this;
  39. that.compareList = compareList;
  40. }
  41. getDissmissDevice() {
  42. var that = this;
  43. return that.dissmissDevice;
  44. }
  45. setConnectWillDevice(connectWillDevice) {
  46. var that = this;
  47. that.connectWillDevice = connectWillDevice;
  48. }
  49. getCallBackConnect() {
  50. var that = this;
  51. return that.callBackConnect;
  52. }
  53. setCallBackConnect(callBackConnect) {
  54. this.callBackConnect = callBackConnect;
  55. }
  56. /// 监控蓝牙打开状态
  57. initBlueAdapter() {
  58. var that = this;
  59. wx.onBluetoothAdapterStateChange(function (res) {
  60. that.isAvailable = res.available;
  61. if (!that.isAvailable) {
  62. that.compareList = [];
  63. that.dissmissDevice = [];
  64. getCurrentPages()[0].closeBlueResetOffline(false, true);
  65. }
  66. })
  67. }
  68. ///监听搜索设备列表
  69. listenBlueDevices() {
  70. var that = this;
  71. const hex_util = require('./../../utils/hex_util');
  72. wx.onBluetoothDeviceFound(function (res) {
  73. ///第一种情况
  74. if (res.deviceId) {
  75. if (that.callBackConnect != null) {
  76. if (that.connectWillDevice != null && res.name == that.connectWillDevice.clientType) {
  77. res.mac = res.advertisData ? hex_util.buf2hex(res.advertisData) : '';
  78. if (that.callBackConnect != null) {
  79. that.callBackConnect(res);
  80. }
  81. }
  82. } else {
  83. if (res.name != "") {
  84. if (that.compareList.length > 0) {
  85. var has = false;
  86. for (var i = 0; i < that.compareList.length; i++) {
  87. if (res.deviceId == that.compareList[i].deviceId) {
  88. has = true;
  89. break;
  90. }
  91. }
  92. if (!has) {
  93. that.compareList.push(res);
  94. }
  95. } else {
  96. that.compareList.push(res);
  97. }
  98. }
  99. }
  100. }
  101. ///第二种情况
  102. else if (res.devices) {
  103. if (that.callBackConnect != null) {
  104. for (var i = 0; i < res.devices.length; i++) {
  105. var temp = res.devices[i];
  106. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  107. temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
  108. temp.mac2 = that.ab2hex(temp.advertisData ?? "")
  109. if (that.callBackConnect != null) {
  110. that.callBackConnect(temp);
  111. }
  112. break;
  113. }
  114. }
  115. } else {
  116. for (var i = 0; i < res.devices.length; i++) {
  117. if (that.compareList.length > 0) {
  118. var has = false;
  119. for (var j = 0; j < that.compareList.length; j++) {
  120. if (res.devices[i].name != "") {
  121. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  122. has = true;
  123. break;
  124. }
  125. }
  126. }
  127. if (!has) {
  128. that.compareList.push(res.devices[i]);
  129. }
  130. } else {
  131. that.compareList.push(res.devices[i]);
  132. }
  133. }
  134. }
  135. }
  136. ///第三种情况
  137. else if (res[0]) {
  138. if (that.callBackConnect != null) {
  139. if (that.connectWillDevice != null && res[0].name == that.connectWillDevice.clientType) {
  140. res[0].mac = res[0].advertisData ? hex_util.buf2hex(res[0].advertisData) : '';
  141. if (that.callBackConnect != null) {
  142. that.callBackConnect(res[0]);
  143. }
  144. }
  145. } else {
  146. if (res[0].name != "") {
  147. if (that.compareList.length > 0) {
  148. var has = false;
  149. for (var i = 0; i < that.compareList.length; i++) {
  150. if (res[0].deviceId == that.compareList[i].deviceId) {
  151. has = true;
  152. break;
  153. }
  154. }
  155. if (!has) {
  156. that.compareList.push(res[0]);
  157. }
  158. } else {
  159. that.compareList.push(res[0]);
  160. }
  161. }
  162. }
  163. }
  164. });
  165. ///监听 离线和连接成功设备导入
  166. // {"deviceId":"E4:9F:80:09:40:EC","connected":false}
  167. wx.onBLEConnectionStateChange((result) => {
  168. if (result.connected) {
  169. for (var i = 0; i < that.dissmissDevice.length; i++) {
  170. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  171. that.dissmissDevice.splice(i, 1);
  172. break;
  173. }
  174. }
  175. } else {
  176. var has = false;
  177. for (var i = 0; i < that.dissmissDevice.length; i++) {
  178. if (result.deviceId == that.dissmissDevice[i].deviceId) {
  179. has = true;
  180. break;
  181. }
  182. }
  183. if (!has) {
  184. that.dissmissDevice.push(result);
  185. }
  186. }
  187. });
  188. }
  189. // 开始搜索蓝牙设备
  190. async startScan(connectWillDevice, boolean, callBackConnect) {
  191. var that = this;
  192. ///限制搜索没有打开蓝牙一直询问打开蓝牙
  193. var isAvailable = that.isAvailable;
  194. if (!isAvailable && callBackConnect == null) {
  195. return;
  196. }
  197. const route_util = require('../utils/route_util');
  198. const route_constant = require('../utils/route_constant');
  199. const indexRoot = route_constant.indexRoot;
  200. const connectBleRoot = route_constant.connectBleRoot;
  201. var lastPageRoute = route_util.getLastPageRoute();
  202. if (lastPageRoute != indexRoot && lastPageRoute != connectBleRoot) {
  203. return;
  204. }
  205. ///蓝牙连接 做限制
  206. if (lastPageRoute == indexRoot) {
  207. if (that.doStartScaning == true) {
  208. return;
  209. }
  210. }
  211. const time_util = require('./../../utils/time_util');
  212. that.doStartScaning = true;
  213. var currentMill = time_util.getCurrentMills();
  214. var waitMills = 0;
  215. var reduce = currentMill - that.requestBlueTime;
  216. const delayMills = 6 * 1000;
  217. if (reduce > 0 && reduce < delayMills) {
  218. waitMills = delayMills - reduce;
  219. }
  220. if (waitMills > 0) {
  221. await time_util.delayMills(waitMills);
  222. }
  223. if (callBackConnect == null && lastPageRoute == connectBleRoot) {
  224. that.doStartScaning = false;
  225. return;
  226. }
  227. wx.openBluetoothAdapter({
  228. success: function (res) {
  229. wx.stopBluetoothDevicesDiscovery({
  230. success: (res) => {
  231. that.search(connectWillDevice, boolean, callBackConnect);
  232. },
  233. fail: (err) => {
  234. that.doStartScaning = false;
  235. that.requestBlueTime = time_util.getCurrentMills();
  236. if (boolean != null) {
  237. boolean(false);
  238. }
  239. }
  240. });
  241. },
  242. fail: function (res) {
  243. that.doStartScaning = false;
  244. that.requestBlueTime = time_util.getCurrentMills();
  245. if (boolean != null) {
  246. boolean(false);
  247. }
  248. }
  249. });
  250. }
  251. ///搜索设备
  252. search(connectWillDevice, boolean, callBackConnect) {
  253. var that = this;
  254. const time_util = require('./../../utils/time_util');
  255. wx.startBluetoothDevicesDiscovery({
  256. allowDuplicatesKey: true,
  257. success: function (res) {
  258. // that.getConnectedDevices();
  259. that.doStartScaning = false;
  260. that.requestBlueTime = time_util.getCurrentMills();
  261. if (boolean != null) {
  262. boolean(true);
  263. }
  264. that.setConnectWillDevice(connectWillDevice);
  265. that.setCallBackConnect(callBackConnect);
  266. that.compareList = [];
  267. },
  268. fail(err) {
  269. that.doStartScaning = false;
  270. that.requestBlueTime = time_util.getCurrentMills();
  271. if (boolean != null) {
  272. boolean(false);
  273. }
  274. },
  275. });
  276. }
  277. // 停止搜索
  278. stopScan() {
  279. var that = this;
  280. that.setCallBackConnect(null);
  281. that.setConnectWillDevice(null);
  282. return new Promise((resolve, reject) => {
  283. wx.stopBluetoothDevicesDiscovery({
  284. success: (res) => {
  285. resolve(res);
  286. },
  287. fail: (err) => {
  288. reject('停止搜索失败');
  289. }
  290. });
  291. });
  292. }
  293. ///开始连接设备
  294. startConnect(device) {
  295. return new Promise((resolve, reject) => {
  296. var deviceId = device.deviceId;
  297. wx.createBLEConnection({
  298. deviceId: deviceId,
  299. success: function (res) {
  300. resolve(true);
  301. },
  302. fail: function (res) {
  303. resolve(false);
  304. }
  305. });
  306. });
  307. }
  308. ///初始化 接收数据 获取特征值
  309. getNotifyCharaterId(device) {
  310. var that = this;
  311. return new Promise((resolve, reject) => {
  312. var deviceId = device.deviceId;
  313. wx.getBLEDeviceServices({
  314. deviceId: deviceId,
  315. success: function (res) {
  316. that.services = res.services;
  317. that.getCharacteristics(device);
  318. }
  319. })
  320. });
  321. }
  322. ///获取设备真正的属性特征值
  323. getCharacteristics(device) {
  324. var that = this;
  325. var deviceId = device.deviceId;
  326. var index = that.serviceIndex;
  327. var notify = that.notify;
  328. var write = that.write;
  329. var read = that.read;
  330. var services = that.services;
  331. wx.getBLEDeviceCharacteristics({
  332. deviceId: deviceId,
  333. serviceId: services[index].uuid,
  334. success: function (res) {
  335. console.log(res.characteristics)
  336. for (var i = 0; i < res.characteristics.length; i++) {
  337. var properties = res.characteristics[i].properties;
  338. var charaterId = res.characteristics[i].uuid;
  339. if (!that.notify) {
  340. if (properties.notify) {
  341. that.notifyCharaterId = charaterId;
  342. that.notifyServiceId = services[index].uuid;
  343. that.notify = true;
  344. }
  345. }
  346. if (!that.write) {
  347. if (properties.write) {
  348. that.writeCharaterId = charaterId;
  349. that.writeServiceId = services[index].uuid;
  350. that.write = true;
  351. }
  352. }
  353. if (!that.read) {
  354. if (properties.read) {
  355. that.readCharaterId = charaterId;
  356. that.readServiceId = services[index].uuid;
  357. that.read = true;
  358. }
  359. }
  360. }
  361. if (!that.notify) {
  362. index++
  363. that.serviceIndex = index;
  364. that.notify = notify;
  365. that.write = write;
  366. that.read = read;
  367. if (index == services.length) {
  368. that.serviceIndex = 0;
  369. that.notify = false;
  370. that.write = false;
  371. that.read = false;
  372. } else {
  373. that.getCharacteristics(device);
  374. }
  375. } else {
  376. that.monitorCharacteristicValueChange(device);
  377. }
  378. }
  379. })
  380. }
  381. // 监听发送的数据
  382. monitorCharacteristicValueChange(device) {
  383. var that = this;
  384. var deviceId = device.deviceId;
  385. const hex_util = require('./../../utils/hex_util');
  386. wx.notifyBLECharacteristicValueChange({
  387. state: true,
  388. deviceId: deviceId,
  389. serviceId: that.notifyServiceId,
  390. characteristicId: that.notifyCharaterId,
  391. success: function (res) {
  392. wx.onBLECharacteristicValueChange(function (r) {
  393. var receiveText = hex_util.buf2string(r.value);
  394. console.log('接收到数据文字:' + receiveText)
  395. });
  396. }
  397. })
  398. }
  399. // 断开设备的连接
  400. disconnect(device) {
  401. return new Promise((resolve, reject) => {
  402. var deviceId = device.deviceId;
  403. wx.closeBLEConnection({
  404. deviceId: deviceId,
  405. success: (res) => {
  406. resolve(true);
  407. },
  408. fail: (err) => {
  409. resolve(false);
  410. }
  411. });
  412. });
  413. }
  414. ///发送数据
  415. sendData(text, device) {
  416. var that = this;
  417. var deviceId = device.deviceId;
  418. var buffer = new ArrayBuffer(text.length)
  419. var dataView = new Uint8Array(buffer)
  420. for (var i = 0; i < text.length; i++) {
  421. dataView[i] = text.charCodeAt(i)
  422. }
  423. wx.writeBLECharacteristicValue({
  424. deviceId: deviceId,
  425. serviceId: that.writeServiceId,
  426. characteristicId: that.writeCharaterId,
  427. value: buffer,
  428. success: function (res) {},
  429. fail(err) {}
  430. });
  431. }
  432. }
  433. ///获取 所有搜索过的蓝牙设备
  434. // getConnectedDevices() {
  435. // var that = this;
  436. // const hex_util = require('./../../utils/hex_util');
  437. // wx.getBluetoothDevices({
  438. // success: (res) => {
  439. // if (that.callBackConnect != null) {
  440. // for (var i = 0; i < res.devices.length; i++) {
  441. // var temp = res.devices[i];
  442. // if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  443. // temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
  444. // if (that.callBackConnect != null) {
  445. // that.callBackConnect(temp);
  446. // }
  447. // break;
  448. // }
  449. // }
  450. // } else {
  451. // for (var i = 0; i < res.devices.length; i++) {
  452. // if (that.compareList.length > 0) {
  453. // var has = false;
  454. // for (var j = 0; j < that.compareList.length; j++) {
  455. // if (res.devices[i].name != "") {
  456. // if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  457. // has = true;
  458. // break;
  459. // }
  460. // }
  461. // }
  462. // if (!has) {
  463. // that.compareList.push(res.devices[i]);
  464. // }
  465. // } else {
  466. // that.compareList.push(res.devices[i]);
  467. // }
  468. // }
  469. // }
  470. // },
  471. // fail: (err) => {
  472. // console.error('获取蓝牙设备列表失败', err);
  473. // }
  474. // });
  475. // }