ble_manager.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. // 引入必要的微信小程序 API
  2. // const wx = require('wx');
  3. class bleManager {
  4. constructor() {
  5. this.hasPermission = false;
  6. this.isAvailable = false;
  7. // this.devices = [];
  8. this.connectedDeviceId = null;
  9. // this.services = [];
  10. this.serviceId = null;
  11. this.deviceId = null;
  12. this.characteristicId = null;
  13. }
  14. // 检查蓝牙权限
  15. async checkBluetoothPermission() {
  16. return new Promise((resolve, reject) => {
  17. // 获取蓝牙权限
  18. const _this = getApp();
  19. wx.getSetting({
  20. success(res) {
  21. if (res.authSetting["scope.bluetooth"]) {
  22. _this.globalData.scopeBluetooth = true;
  23. resolve(true);
  24. } else if (res.authSetting["scope.bluetooth"] === undefined) {
  25. _this.globalData.scopeBluetooth = false;
  26. wx.authorize({
  27. scope: "scope.bluetooth",
  28. complete() {
  29. _this.getBluetoothStatus();
  30. }
  31. });
  32. resolve(false);
  33. } else {
  34. _this.globalData.scopeBluetooth = false;
  35. wx.showModal({
  36. title: '请打开系统蓝牙进行配网',
  37. content: '如已打开蓝牙仍然弹框,请尝试重启小程序',
  38. success(res) {
  39. if (res.confirm) {
  40. console.log('用户点击确定')
  41. wx.openSetting({
  42. complete() {
  43. // _this.getBluetoothStatus();
  44. }
  45. })
  46. } else if (res.cancel) {
  47. console.log('用户点击取消')
  48. }
  49. }
  50. })
  51. resolve(false);
  52. };
  53. }
  54. })
  55. })
  56. }
  57. // 初始化蓝牙适配器
  58. initBluetoothAdapter() {
  59. return new Promise((resolve, reject) => {
  60. wx.openBluetoothAdapter({
  61. success: (res) => {
  62. this.isAvailable = true;
  63. resolve(true);
  64. },
  65. fail: (err) => {
  66. this.isAvailable = false;
  67. reject(false);
  68. }
  69. });
  70. });
  71. }
  72. // 获取已连接的蓝牙设备
  73. getConnectedDevices() {
  74. return new Promise((resolve, reject) => {
  75. wx.getConnectedBluetoothDevices({
  76. services: ["ffc0", "ab00", "ffe5"],
  77. // services: ["0000ab00-0000-1000-8000-00805f9b34fb"
  78. // , "0000ffc0-0000-1000-8000-00805f9b34fb"
  79. // ],
  80. success: (res) => {
  81. // const connectedDevices = res.devices.map(device => ({
  82. // deviceId: device.deviceId,
  83. // name: device.name || device.localName
  84. // }));
  85. console.log('已连接的蓝牙设备:', res.devices);
  86. resolve(res.devices);
  87. },
  88. fail: (err) => {
  89. console.error('获取已连接的蓝牙设备失败:', err);
  90. reject(new Error('获取已连接的蓝牙设备失败'));
  91. }
  92. });
  93. });
  94. }
  95. // 断开与指定设备的连接
  96. disconnect(deviceId) {
  97. return new Promise((resolve, reject) => {
  98. wx.closeBLEConnection({
  99. deviceId: deviceId,
  100. success: (res) => {
  101. this.connectedDeviceId = null;
  102. console.log('断开连接成功:', res);
  103. resolve(res);
  104. },
  105. fail: (err) => {
  106. console.error('断开连接失败:', err);
  107. reject(new Error('断开连接失败'));
  108. }
  109. });
  110. });
  111. }
  112. // 发送数据到指定设备
  113. sendData(data) {
  114. return new Promise((resolve, reject) => {
  115. const buffer = new ArrayBuffer(data.length);
  116. const view = new Uint8Array(buffer);
  117. for (let i = 0; i < data.length; i++) {
  118. view[i] = data.charCodeAt(i);
  119. }
  120. wx.writeBLECharacteristicValue({
  121. deviceId: this.deviceId,
  122. serviceId: this.serviceId,
  123. characteristicId: this.characteristicId,
  124. value: buffer,
  125. success: (res) => {
  126. console.log('数据发送成功:', res);
  127. resolve(res);
  128. },
  129. fail: (err) => {
  130. console.error('数据发送失败:', err);
  131. reject(new Error('数据发送失败'));
  132. }
  133. });
  134. });
  135. }
  136. getSetting() {
  137. const _this = this;
  138. wx.getSetting({
  139. success(res) {
  140. if (res.authSetting["scope.userFuzzyLocation"]) {
  141. // 成功
  142. _this.getBluetoothStatus();
  143. } else if (res.authSetting["scope.userFuzzyLocation"] === undefined) {
  144. wx.authorize({
  145. scope: "scope.userFuzzyLocation",
  146. success() {
  147. _this.getSetting();
  148. }
  149. });
  150. } else {
  151. wx.showModal({
  152. title: '请打开系统位置获取',
  153. success(res) {
  154. if (res.confirm) {
  155. console.log('用户点击确定')
  156. wx.openSetting({
  157. complete() {
  158. // _this.getSetting();
  159. }
  160. })
  161. } else if (res.cancel) {
  162. console.log('用户点击取消');
  163. }
  164. }
  165. })
  166. }
  167. }
  168. })
  169. }
  170. // 开始搜索蓝牙设备
  171. startScan(success, fail) {
  172. wx.startBluetoothDevicesDiscovery({
  173. services: ["ffc0", "ab00", "ffe5"],
  174. success: (res) => {
  175. // this.onBluetoothDeviceFound();
  176. console.log('蓝牙设备搜索已启动:', res);
  177. if (success) {
  178. success(res);
  179. }
  180. // resolve(res);
  181. },
  182. fail: (err) => {
  183. if (fail) {
  184. fail(err);
  185. }
  186. console.log('启动蓝牙设备搜索失败', err ?? "err is null");
  187. // reject(new Error('启动蓝牙设备搜索失败', err ?? "err is null"));
  188. }
  189. });
  190. // return new Promise((resolve, reject) => {
  191. // wx.startBluetoothDevicesDiscovery({
  192. // services: ["ffc0", "ab00", "ffe5"],
  193. // success: (res) => {
  194. // // this.onBluetoothDeviceFound();
  195. // console.log('蓝牙设备搜索已启动:', res);
  196. // resolve(res);
  197. // },
  198. // fail: (err) => {
  199. // reject(new Error('启动蓝牙设备搜索失败', err ?? "err is null"));
  200. // }
  201. // });
  202. // });
  203. }
  204. // 监听发现新设备的事件
  205. onBluetoothDeviceFound(callback) {
  206. wx.onBluetoothDeviceFound((res) => {
  207. const devices = res.devices.map(device => ({
  208. deviceId: device.deviceId,
  209. name: device.name || device.localName
  210. }));
  211. // this.devices.push(...devices);
  212. console.log('发现设备:', this.devices);
  213. if (callback) {
  214. callback(devices);
  215. }
  216. });
  217. }
  218. // 连接到指定设备
  219. connectToDevice(deviceId) {
  220. return new Promise((resolve, reject) => {
  221. wx.createBLEConnection({
  222. deviceId: deviceId,
  223. success: (res) => {
  224. this.connectedDeviceId = deviceId;
  225. console.log('连接成功:', res);
  226. resolve(res);
  227. },
  228. fail: (err) => {
  229. console.error('连接失败:', err);
  230. reject(new Error('连接失败'));
  231. }
  232. });
  233. });
  234. }
  235. // 停止搜索
  236. stopScan() {
  237. return new Promise((resolve, reject) => {
  238. wx.stopBluetoothDevicesDiscovery({
  239. success: (res) => {
  240. console.log('停止搜索成功:', res);
  241. resolve(res);
  242. },
  243. fail: (err) => {
  244. console.error('停止搜索失败:', err);
  245. reject(new Error('停止搜索失败'));
  246. }
  247. });
  248. });
  249. }
  250. // 发现服务
  251. discoverServices(deviceId) {
  252. return new Promise((resolve, reject) => {
  253. wx.getBLEDeviceServices({
  254. deviceId: deviceId,
  255. success: (res) => {
  256. this.services = res.services;
  257. console.log('发现服务:', this.services);
  258. resolve(res.services);
  259. },
  260. fail: (err) => {
  261. console.error('发现服务失败:', err);
  262. reject(new Error('发现服务失败'));
  263. }
  264. });
  265. });
  266. }
  267. // 发现特征值
  268. discoverCharacteristics(deviceId, serviceId) {
  269. return new Promise((resolve, reject) => {
  270. wx.getBLEDeviceCharacteristics({
  271. deviceId: deviceId,
  272. serviceId: serviceId,
  273. success: (res) => {
  274. // this.characteristics[serviceId] = res.characteristics;
  275. this.characteristicId = res.characteristics;
  276. console.log('发现特征值:', this.characteristicId);
  277. resolve(res.characteristics);
  278. },
  279. fail: (err) => {
  280. console.error('发现特征值失败:', err);
  281. reject(new Error('发现特征值失败'));
  282. }
  283. });
  284. });
  285. }
  286. // 读取特征值
  287. readCharacteristicValue(deviceId, serviceId, characteristicId) {
  288. return new Promise((resolve, reject) => {
  289. wx.readBLECharacteristicValue({
  290. deviceId: deviceId,
  291. serviceId: serviceId,
  292. characteristicId: characteristicId,
  293. success: (res) => {
  294. console.log('读取特征值成功:', res);
  295. resolve(res);
  296. },
  297. fail: (err) => {
  298. console.error('读取特征值失败:', err);
  299. reject(new Error('读取特征值失败'));
  300. }
  301. });
  302. });
  303. }
  304. // 监听特征值变化
  305. notifyCharacteristicValueChange(deviceId, serviceId, characteristicId, state, callback) {
  306. // return new Promise((resolve, reject) => {
  307. wx.notifyBLECharacteristicValueChange({
  308. deviceId: deviceId,
  309. serviceId: serviceId,
  310. characteristicId: characteristicId,
  311. state: state, // true 表示开启通知,false 表示关闭通知
  312. success: (res) => {
  313. console.log('通知特征值变化成功:', res);
  314. // resolve(res);
  315. if (callback) {
  316. callback(res)
  317. }
  318. },
  319. fail: (err) => {
  320. console.error('通知特征值变化失败:', err);
  321. // reject(new Error('通知特征值变化失败'));
  322. }
  323. });
  324. // });
  325. }
  326. // 搜索蓝牙服务
  327. searchServices(deviceId) {
  328. return this.discoverServices(deviceId);
  329. }
  330. // 搜索蓝牙特征值
  331. searchCharacteristics(deviceId, serviceId) {
  332. return this.discoverCharacteristics(deviceId, serviceId);
  333. }
  334. }
  335. const ble = new bleManager();
  336. // 导出 bleManager 类
  337. module.exports = ble;