ble_manager.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. // 引入必要的微信小程序 API
  2. // const wx = require('wx');
  3. class bleManager {
  4. constructor() {
  5. var that = this;
  6. that.isAvailable = false;
  7. that.hasPermission = false;
  8. that.scanDevices = [];
  9. that.publicDevice = null;
  10. that.compareList = [];
  11. that.connectWillDevice = null;
  12. that.callBackConnect = null;
  13. }
  14. ///获取比较的数据
  15. getCompareList() {
  16. return this.compareList;
  17. }
  18. getConnectWillDevice() {
  19. return this.connectWillDevice;
  20. }
  21. setConnectWillDevice(connectWillDevice) {
  22. this.connectWillDevice = connectWillDevice;
  23. }
  24. getCallBackConnect() {
  25. return this.callBackConnect;
  26. }
  27. setCallBackConnect(callBackConnect) {
  28. this.callBackConnect = callBackConnect;
  29. }
  30. /// 监控蓝牙打开状态
  31. initBluetoothAdapter() {
  32. var that = this;
  33. wx.onBluetoothAdapterStateChange(function (res) {
  34. that.isAvailable = res.available;
  35. })
  36. }
  37. ///监听搜索设备列表
  38. getBluetoothDevices() {
  39. var that = this;
  40. wx.onBluetoothDeviceFound(function (res) {
  41. ///第一种情况
  42. if (res.deviceId) {
  43. if (that.callBackConnect != null) {
  44. if (that.connectWillDevice != null && res.name == that.connectWillDevice.clientType) {
  45. res.advertisData = res.advertisData ? that.buf2hex(res.advertisData) : '';
  46. that.callBackConnect(res);
  47. }
  48. } else {
  49. if (res.name != "") {
  50. if (that.compareList.length > 0) {
  51. var has = false;
  52. for (var i = 0; i < that.compareList.length; i++) {
  53. if (res.deviceId == that.compareList[i].deviceId) {
  54. has = true;
  55. break;
  56. }
  57. }
  58. if (!has) {
  59. that.compareList.push(res);
  60. }
  61. } else {
  62. that.compareList.push(res);
  63. }
  64. }
  65. }
  66. }
  67. ///第二种情况
  68. else if (res.devices) {
  69. if (that.callBackConnect != null) {
  70. for (var i = 0; i < res.devices.length; i++) {
  71. var temp = res.devices[i];
  72. if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
  73. temp.advertisData = temp.advertisData ? that.buf2hex(temp.advertisData) : '';
  74. that.callBackConnect(temp);
  75. break;
  76. }
  77. }
  78. } else {
  79. for (var i = 0; i < res.devices.length; i++) {
  80. if (that.compareList.length > 0) {
  81. var has = false;
  82. for (var j = 0; j < that.compareList.length; j++) {
  83. if (res.devices[i].name != "") {
  84. if (res.devices[i].deviceId == that.compareList[j].deviceId) {
  85. has = true;
  86. break;
  87. }
  88. }
  89. }
  90. if (!has) {
  91. that.compareList.push(res.devices[i]);
  92. }
  93. } else {
  94. that.compareList.push(res.devices[i]);
  95. }
  96. }
  97. }
  98. }
  99. ///第三种情况
  100. else if (res[0]) {
  101. if (that.callBackConnect != null) {
  102. if (that.connectWillDevice != null && res[0].name == that.connectWillDevice.clientType) {
  103. res[0].advertisData = res[0].advertisData ? that.buf2hex(res[0].advertisData) : '';
  104. that.callBackConnect(res[0]);
  105. }
  106. } else {
  107. if (res[0].name != "") {
  108. if (that.compareList.length > 0) {
  109. var has = false;
  110. for (var i = 0; i < that.compareList.length; i++) {
  111. if (res[0].deviceId == that.compareList[i].deviceId) {
  112. has = true;
  113. break;
  114. }
  115. }
  116. if (!has) {
  117. that.compareList.push(res[0]);
  118. }
  119. } else {
  120. that.compareList.push(res[0]);
  121. }
  122. }
  123. }
  124. }
  125. });
  126. }
  127. ///获取数据
  128. buf2hex(buffer) {
  129. return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  130. }
  131. // 开始搜索蓝牙设备
  132. startScan(boolean) {
  133. var that = this;
  134. wx.closeBluetoothAdapter({
  135. complete: function (res) {
  136. wx.openBluetoothAdapter({
  137. success: function (res) {
  138. wx.getBluetoothAdapterState({
  139. success: function (res) {},
  140. fail(err) {
  141. boolean(false);
  142. },
  143. })
  144. wx.startBluetoothDevicesDiscovery({
  145. allowDuplicatesKey: false,
  146. success: function (res) {
  147. boolean(true);
  148. that.compareList = [];
  149. },
  150. fail(err) {},
  151. })
  152. },
  153. fail: function (res) {
  154. wx.showModal({
  155. title: '提示',
  156. content: '请检查手机蓝牙是否打开',
  157. showCancel: false,
  158. success: function (res) {}
  159. });
  160. boolean(false);
  161. }
  162. })
  163. }
  164. })
  165. }
  166. // 停止搜索
  167. stopSearch() {
  168. return new Promise((resolve, reject) => {
  169. wx.stopBluetoothDevicesDiscovery({
  170. success: (res) => {
  171. console.log('停止搜索成功:', res);
  172. resolve(res);
  173. },
  174. fail: (err) => {
  175. console.error('停止搜索失败:', err);
  176. reject(new Error('停止搜索失败'));
  177. }
  178. });
  179. });
  180. }
  181. closeBle() {
  182. console.log('关闭蓝牙了')
  183. closeBluetoothAdapter();
  184. }
  185. // 断开与指定设备的连接
  186. disconnect() {
  187. var that = this;
  188. let device = that.publicDevice ?? {};
  189. let deviceId = device.deviceId ?? ""
  190. if (deviceId.length === 0) {
  191. return;
  192. }
  193. return new Promise((resolve, reject) => {
  194. wx.closeBLEConnection({
  195. deviceId: that.publicDevice.deviceId ?? "",
  196. success: (res) => {
  197. that.publicDevice = null;
  198. console.log('断开连接成功:', res);
  199. resolve(res);
  200. },
  201. fail: (err) => {
  202. console.error('断开连接失败:', err);
  203. reject(new Error('断开连接失败'));
  204. }
  205. });
  206. });
  207. }
  208. // 发送数据到指定设备
  209. async sendData(data) {
  210. var that = this
  211. return new Promise((resolve, reject) => {
  212. var buffer = null;
  213. // todo 判断是否是buffer
  214. // if (Buffer.isBuffer(data)) {
  215. // buffer = data;
  216. // } else {
  217. buffer = new ArrayBuffer(data.length);
  218. // 下面是赋值,不能删
  219. const dataView = new DataView(buffer);
  220. data.forEach((value, index) => {
  221. dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
  222. });
  223. // }
  224. console.log('开始发送数据:', data, buffer);
  225. wx.writeBLECharacteristicValue({
  226. deviceId: that.publicDevice.deviceId,
  227. serviceId: that.publicDevice.serviceId,
  228. characteristicId: that.publicDevice.characteristicId,
  229. value: buffer,
  230. success: (res) => {
  231. // console.log('数据发送成功:');
  232. resolve(res);
  233. },
  234. fail: (err) => {
  235. console.error('数据发送失败:', err);
  236. reject(new Error('数据发送失败'));
  237. }
  238. });
  239. });
  240. }
  241. ab2hex(buffer) {
  242. var hexArr = Array.prototype.map.call(
  243. new Uint8Array(buffer),
  244. function (bit) {
  245. return ('00' + bit.toString(16)).slice(-2)
  246. }
  247. )
  248. return hexArr.join(':');
  249. }
  250. fiterDevice(res) {
  251. var that = this;
  252. var devices = res.devices.filter(device => {
  253. const name = device.name || '';
  254. const localName = device.localName || '';
  255. let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName);
  256. if (isNot) {
  257. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  258. let mac = that.ab2hex(device.advertisData)
  259. // console.log(mac)
  260. device.mac = mac
  261. }
  262. return isNot
  263. });
  264. let newDevices = devices.map((device) => {
  265. let uuid = device.advertisServiceUUIDs[0] ?? ""
  266. return {
  267. deviceId: device.deviceId,
  268. name: device.name,
  269. localName: device.localName,
  270. uuid: uuid,
  271. mac: device.mac,
  272. connectable: device.connectable
  273. }
  274. });
  275. return newDevices
  276. }
  277. isNotEmpty(name) {
  278. let isNot = (name !== '' &&
  279. (name.startsWith("MW_") ||
  280. name.startsWith("MW-") ||
  281. // name.startsWith("猫王") ||
  282. // name.startsWith("妙播") ||
  283. // name.startsWith("AirSmart") ||
  284. name === "le")
  285. )
  286. // if (!isNot && name !== '') {
  287. // console.log('不是猫王设备名称:', name)
  288. // }
  289. return isNot;
  290. }
  291. // 连接到指定设备
  292. async connectToDevice(device) {
  293. var that = this;
  294. return new Promise((resolve, reject) => {
  295. console.log("开始连接蓝牙:", device.deviceId)
  296. wx.createBLEConnection({
  297. deviceId: device.deviceId,
  298. success: (res) => {
  299. that.publicDevice = device
  300. console.log('连接成功:', res);
  301. resolve(true);
  302. },
  303. fail: (err) => {
  304. that.publicDevice = null
  305. console.error('连接失败:', err);
  306. resolve(false);
  307. }
  308. });
  309. });
  310. }
  311. // 发现服务
  312. discoverServices(deviceId) {
  313. var that = this;
  314. console.log('发现服务:', deviceId);
  315. return new Promise((resolve, reject) => {
  316. wx.getBLEDeviceServices({
  317. deviceId: deviceId,
  318. success: (res) => {
  319. // that.publicDevice .services = res.services;
  320. let service_id = "";
  321. for (let i = 0; i < res.services.length; i++) {
  322. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
  323. res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  324. // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  325. ) {
  326. service_id = res.services[i].uuid;
  327. break;
  328. }
  329. console.log('发现服务1:', service_id);
  330. service_id = res.services[i].uuid;
  331. }
  332. that.publicDevice.serviceId = service_id;
  333. console.log('发现服务2:', service_id);
  334. resolve(service_id);
  335. // resolve(res.services);
  336. },
  337. fail: (err) => {
  338. that.publicDevice.serviceId = null;
  339. console.error('发现服务失败:', err);
  340. reject([]);
  341. }
  342. });
  343. });
  344. }
  345. // 发现特征值 read / write
  346. discoverCharacteristics(deviceId, serviceId) {
  347. var that = this;
  348. console.log('发现特征值:' + deviceId + " , " + serviceId);
  349. // if (deviceId !== that.publicDevice .deviceId) {
  350. // console.log('设备id不匹配')
  351. // return false
  352. // }
  353. return new Promise((resolve, reject) => {
  354. wx.getBLEDeviceCharacteristics({
  355. deviceId: deviceId,
  356. serviceId: serviceId,
  357. success: (res) => {
  358. // that.characteristics[serviceId] = res.characteristics;
  359. console.log('发现特征值2:', res);
  360. // that.publicDevice .characteristics = res.characteristics;
  361. resolve(res.characteristics);
  362. },
  363. fail: (err) => {
  364. that.publicDevice.characteristics = null;
  365. console.error('发现特征值失败:', err);
  366. reject("");
  367. }
  368. });
  369. });
  370. }
  371. // 读取特征值
  372. readCharacteristicValue(characteristicId) {
  373. var that = ths;
  374. console.log('开始读取特征值', characteristicId)
  375. return new Promise((resolve, reject) => {
  376. wx.readBLECharacteristicValue({
  377. deviceId: that.publicDevice.deviceId,
  378. serviceId: that.publicDevice.serviceId,
  379. characteristicId: characteristicId,
  380. success: (res) => {
  381. const name = that.parseBLEValue(res.value); // 解析读取到的值
  382. console.log('读取特征值成功:', name, res);
  383. resolve(res);
  384. },
  385. fail: (err) => {
  386. console.error('读取特征值失败:', err);
  387. reject("");
  388. }
  389. });
  390. });
  391. }
  392. // 解析读取到的设备名称
  393. parseBLEValue(buffer) {
  394. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  395. }
  396. // 监听特征值变化
  397. notifyCharacteristicValueChange(characteristicId, callback) {
  398. var that = this;
  399. console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
  400. wx.notifyBLECharacteristicValueChange({
  401. deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样
  402. serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
  403. characteristicId: characteristicId, //notify uuid
  404. state: true,
  405. success: function (res) {
  406. console.log("开启notify 成功")
  407. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  408. wx.onBLECharacteristicValueChange(function (characteristic) {
  409. let buffer = characteristic.value
  410. let dataView = new DataView(buffer)
  411. let dataResult = []
  412. for (let i = 0; i < dataView.byteLength; i++) {
  413. // console.log("0x" + dataView.getUint8(i).toString(16))
  414. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  415. dataResult.push(dataView.getUint8(i))
  416. }
  417. const result = dataResult
  418. console.log("拿到的数据:", result)
  419. if (callback) {
  420. callback(result)
  421. }
  422. })
  423. },
  424. fail: function (res) {
  425. console.log("订阅特征失败:", res)
  426. }
  427. })
  428. }
  429. setWrite(wirte, characteristicId) {
  430. var that = this;
  431. console.log('写入特征值:', characteristicId)
  432. // that.publicDevice .wirte = wirte
  433. that.publicDevice.characteristicId = characteristicId;
  434. }
  435. }
  436. // const ble = new bleManager();
  437. // 导出 bleManager 类
  438. module.exports = bleManager;
  439. // wx.getSetting({
  440. // success(res) {
  441. // if (res.authSetting["scope.userFuzzyLocation"]) {
  442. // // 成功
  443. // // that.getBluetoothStatus();
  444. // console.log("有定位权限")
  445. // resolve(true);
  446. // } else if (res.authSetting["scope.userFuzzyLocation"] === undefined) {
  447. // wx.authorize({
  448. // scope: "scope.userFuzzyLocation",
  449. // success() {
  450. // console.log("再次获取定位权限")
  451. // resolve(that.getSetting());
  452. // }
  453. // });
  454. // } else {
  455. // wx.showModal({
  456. // title: '请打开系统位置获取定位权限',
  457. // success(res) {
  458. // if (res.confirm) {
  459. // console.log('用户点击确定')
  460. // wx.openSetting({
  461. // complete() {
  462. // // that.getSetting();
  463. // // resolve(that.getSetting());
  464. // }
  465. // })
  466. // } else if (res.cancel) {
  467. // console.log('用户点击取消');
  468. // }
  469. // }
  470. // })
  471. // console.log("没有有定位权限")
  472. // reject(false);
  473. // }
  474. // }
  475. // })
  476. // // 获取已连接的蓝牙设备
  477. // getConnectedDevices() {
  478. // var that = this;
  479. // if (!that.isAvailable && !that.hasPermission) {
  480. // return [];
  481. // }
  482. // return new Promise((resolve, reject) => {
  483. // wx.getConnectedBluetoothDevices({
  484. // // services: ["FFC0", "ffc0", "FFC1", "FFC2", "ffc1", "ffc2", "AB00", "ab00", "AB01", "AB02", "FFF1", "fff1", "FFE2", "FFE5",],
  485. // // services: ["ab00", "ffe5", "1111", "FFC0", "FFC1", "FFF1", ],
  486. // // services: [],
  487. // // services: [
  488. // // "0000ab00-0000-1000-8000-00805f9b34fb",
  489. // // "0000ffc0-0000-1000-8000-00805f9b34fb",
  490. // // "0000FFF0-0000-1000-8000-00805F9B34FB",
  491. // // "0000FFF1-0000-1000-8000-00805F9B34FB",
  492. // // "0000FFE5-0000-1000-8000-00805F9B34FB",
  493. // // ],
  494. // success: (res) => {
  495. // console.log('已连接的蓝牙设备==11==:', newDevices);
  496. // let newDevices = that.fiterDevice(res)
  497. // console.log('已连接的蓝牙设备==22==:', newDevices);
  498. // resolve(newDevices);
  499. // },
  500. // fail: (err) => {
  501. // console.error('获取已连接的蓝牙设备失败:', err);
  502. // reject([]);
  503. // }
  504. // });
  505. // });
  506. // }