ble_manager.js 19 KB

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