ble_manager.js 16 KB

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