ble_manager.js 17 KB

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