ble_manager.js 19 KB

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