ble_manager.js 13 KB

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