ble_manager.js 18 KB

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