ble_manager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. 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. async 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].toString(16);
  176. }
  177. console.log('开始发送数据:', 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('发现设备1:', res);
  281. }
  282. if (callback) {
  283. callback(newDevices);
  284. }
  285. });
  286. }
  287. getMac() {
  288. }
  289. ab2hex(buffer) {
  290. var hexArr = Array.prototype.map.call(
  291. new Uint8Array(buffer),
  292. function (bit) {
  293. return ('00' + bit.toString(16)).slice(-2)
  294. }
  295. )
  296. return hexArr.join(':');
  297. }
  298. fiterDevice(res) {
  299. var devices = res.devices.filter(device => {
  300. const name = device.name || '';
  301. const localName = device.localName || '';
  302. let isNot = this.isNotEmpty(name) || this.isNotEmpty(localName);
  303. if (isNot) {
  304. // console.log('是猫王设备名称:', device.advertisData, device.serviceData)
  305. let mac = this.ab2hex(device.advertisData)
  306. // console.log(mac)
  307. device.mac = mac
  308. }
  309. return isNot
  310. });
  311. let newDevices = devices.map((device) => {
  312. let uuid = device.advertisServiceUUIDs[0] ?? ""
  313. return {
  314. deviceId: device.deviceId,
  315. name: device.name,
  316. localName: device.localName,
  317. uuid: uuid,
  318. mac: device.mac,
  319. connectable: device.connectable
  320. }
  321. });
  322. return newDevices
  323. }
  324. isNotEmpty(name) {
  325. let isNot = (name !== ''
  326. && (name.startsWith("MW_") ||
  327. name.startsWith("MW-") ||
  328. name.startsWith("猫王") ||
  329. name.startsWith("妙播") ||
  330. name.startsWith("AirSmart") ||
  331. name === "le")
  332. )
  333. // if (!isNot && name !== '') {
  334. // console.log('不是猫王设备名称:', name)
  335. // }
  336. return isNot;
  337. }
  338. // 连接到指定设备
  339. async connectToDevice(device) {
  340. return new Promise((resolve, reject) => {
  341. console.log("开始连接蓝牙:", device.deviceId)
  342. wx.createBLEConnection({
  343. deviceId: device.deviceId,
  344. success: (res) => {
  345. this.device = device
  346. console.log('连接成功:', res);
  347. resolve(true);
  348. },
  349. fail: (err) => {
  350. this.device = null
  351. console.error('连接失败:', err);
  352. reject(false);
  353. }
  354. });
  355. });
  356. }
  357. // 停止搜索
  358. stopScan() {
  359. return new Promise((resolve, reject) => {
  360. wx.stopBluetoothDevicesDiscovery({
  361. success: (res) => {
  362. console.log('停止搜索成功:', res);
  363. resolve(res);
  364. },
  365. fail: (err) => {
  366. console.error('停止搜索失败:', err);
  367. reject(new Error('停止搜索失败'));
  368. }
  369. });
  370. });
  371. }
  372. closeBle() {
  373. wx.closeBluetoothAdapter({
  374. success(res) {
  375. console.log(res)
  376. }
  377. })
  378. }
  379. // 发现服务
  380. discoverServices(deviceId) {
  381. console.log('发现服务:', deviceId);
  382. return new Promise((resolve, reject) => {
  383. wx.getBLEDeviceServices({
  384. deviceId: deviceId,
  385. success: (res) => {
  386. // this.device.services = res.services;
  387. let service_id = "";
  388. for (let i = 0; i < res.services.length; i++) {
  389. if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1
  390. || res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
  391. || res.services[i].uuid.toUpperCase().indexOf("ae800") != -1
  392. ) {
  393. service_id = res.services[i].uuid;
  394. break;
  395. }
  396. console.log('发现服务1:', service_id);
  397. service_id = res.services[i].uuid;
  398. }
  399. this.device.serviceId = service_id;
  400. console.log('发现服务2:', service_id);
  401. resolve(service_id);
  402. // resolve(res.services);
  403. },
  404. fail: (err) => {
  405. this.device.serviceId = null;
  406. console.error('发现服务失败:', err);
  407. reject([]);
  408. }
  409. });
  410. });
  411. }
  412. // 发现特征值 read / write
  413. discoverCharacteristics(deviceId, serviceId) {
  414. console.log('发现特征值:' + deviceId + " , " + serviceId);
  415. // if (deviceId !== this.device.deviceId) {
  416. // console.log('设备id不匹配')
  417. // return false
  418. // }
  419. return new Promise((resolve, reject) => {
  420. wx.getBLEDeviceCharacteristics({
  421. deviceId: deviceId,
  422. serviceId: serviceId,
  423. success: (res) => {
  424. // this.characteristics[serviceId] = res.characteristics;
  425. console.log('发现特征值2:', res);
  426. // this.device.characteristics = res.characteristics;
  427. resolve(res.characteristics);
  428. },
  429. fail: (err) => {
  430. this.device.characteristics = null;
  431. console.error('发现特征值失败:', err);
  432. reject("");
  433. }
  434. });
  435. });
  436. }
  437. // 读取特征值
  438. readCharacteristicValue(characteristicId) {
  439. console.log('开始读取特征值', characteristicId)
  440. return new Promise((resolve, reject) => {
  441. wx.readBLECharacteristicValue({
  442. deviceId: this.device.deviceId,
  443. serviceId: this.device.serviceId,
  444. characteristicId: characteristicId,
  445. success: (res) => {
  446. const name = this.parseBLEValue(res.value); // 解析读取到的值
  447. console.log('读取特征值成功:', name, res);
  448. resolve(res);
  449. },
  450. fail: (err) => {
  451. console.error('读取特征值失败:', err);
  452. reject("");
  453. }
  454. });
  455. });
  456. }
  457. // 解析读取到的设备名称
  458. parseBLEValue(buffer) {
  459. return String.fromCharCode.apply(null, new Uint8Array(buffer));
  460. }
  461. // 监听特征值变化
  462. notifyCharacteristicValueChange(characteristicId, callback) {
  463. console.log('监听特征值变化:', characteristicId);
  464. wx.notifyBLECharacteristicValueChange({
  465. deviceId: this.device.deviceId, //设备mac IOS和安卓系统不一样
  466. serviceId: this.device.serviceId, //服务通道,这里主要是notify
  467. characteristicId: characteristicId, //notify uuid
  468. state: true,
  469. success: function (res) {
  470. console.log("开启notify 成功")
  471. //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
  472. wx.onBLECharacteristicValueChange(function (characteristic) {
  473. let buffer = characteristic.value
  474. let dataView = new DataView(buffer)
  475. let dataResult = []
  476. for (let i = 0; i < dataView.byteLength; i++) {
  477. // console.log("0x" + dataView.getUint8(i).toString(16))
  478. // dataResult.push("0x" + dataView.getUint8(i).toString(16))
  479. dataResult.push(dataView.getUint8(i))
  480. }
  481. const result = dataResult
  482. console.log("拿到的数据:", result)
  483. if (callback) {
  484. callback(result)
  485. }
  486. })
  487. },
  488. fail: function (res) {
  489. console.log("订阅特征失败:", res)
  490. }
  491. })
  492. }
  493. setWrite(wirte, characteristicId) {
  494. console.log('写入特征值:', characteristicId)
  495. // this.device.wirte = wirte
  496. this.device.characteristicId = characteristicId;
  497. }
  498. }
  499. // const ble = new bleManager();
  500. // 导出 bleManager 类
  501. module.exports = bleManager;