ble_manager.js 19 KB

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