ble_manager.js 19 KB

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