ble_manager.js 20 KB

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