manager.js 14 KB

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