ble_manager.js 16 KB

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