ble_manager.js 17 KB

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