ble_manager.js 18 KB

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