manager.js 14 KB

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