ble_manager.js 19 KB

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