ble.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import bluetoothTool from "@/plugins/BluetoothTool.js";
  2. import permission from "@/plugins/permission.js";
  3. const statusMap = [
  4. {
  5. code: 0,
  6. msg: "蓝牙设备已打开",
  7. },
  8. {
  9. code: 1,
  10. msg: "蓝牙设备未打开",
  11. },
  12. {
  13. code: 2,
  14. msg: "当前设备不支持蓝牙",
  15. },
  16. ];
  17. export default {
  18. namespaced: true,
  19. // 储存数据
  20. state: {
  21. discoveredDevices: [], // 已发现的蓝牙设备
  22. connectedBleDevice: null, // 当前连接的蓝牙设备
  23. connectedDeviceId: "", // 已连接的蓝牙设备ID
  24. },
  25. // 修改数据
  26. mutations: {
  27. // 设置已发现的蓝牙设备
  28. setDiscoveredDevices(state, data) {
  29. console.log("setDiscoveredDevices------", data);
  30. state.discoveredDevices = data;
  31. },
  32. // 设置已发现的蓝牙设备
  33. addDiscoveredDevice(state, device) {
  34. console.log("addDiscoveredDevice------", device);
  35. state.discoveredDevices.push(device);
  36. },
  37. // 已连接蓝牙设备
  38. setConnectedBleDevice(state, data) {
  39. console.log(111111, data);
  40. state.connectedBleDevice = { ...data };
  41. },
  42. // 设置已连接蓝牙设备ID
  43. setConnectedDeviceId(state, data) {
  44. state.connectedDeviceId = data;
  45. },
  46. },
  47. actions: {
  48. // 检查蓝牙设备打开状态
  49. checkBleStatus({ commit }) {
  50. return new Promise((resolve) => {
  51. // 检查蓝牙是否打开
  52. if (bluetoothTool.isSupportBluetooth()) {
  53. console.log("蓝牙设备支持");
  54. if (bluetoothTool.getBluetoothStatus()) {
  55. console.log("蓝牙设备已打开");
  56. resolve({
  57. code: statusMap[0].code,
  58. msg: statusMap[0].msg,
  59. });
  60. } else {
  61. console.log("蓝牙设备未打开");
  62. resolve({
  63. code: statusMap[1].code,
  64. msg: statusMap[1].msg,
  65. });
  66. }
  67. } else {
  68. resolve({
  69. code: statusMap[2].code,
  70. msg: statusMap[2].msg,
  71. });
  72. }
  73. });
  74. },
  75. // 初始蓝牙
  76. initBle({ commit, state }) {
  77. console.log("state======", state);
  78. // 检查蓝牙权限
  79. permission
  80. .androidPermissionCheck("bluetooth")
  81. .then(() => {
  82. bluetoothTool.init({
  83. // 监听蓝牙状态变化
  84. listenBTStatusCallback: (state) => {
  85. if (state == "STATE_ON") {
  86. console.log("蓝牙已打开:", state);
  87. // 可以在这里添加蓝牙打开后的初始化逻辑
  88. } else if (state == "STATE_OFF") {
  89. console.log("蓝牙已关闭:", state);
  90. // 可以在这里添加蓝牙关闭后的清理逻辑
  91. }
  92. },
  93. // 发现新设备回调
  94. discoveryDeviceCallback: function (device) {
  95. try {
  96. // 基本验证
  97. if (!device || !device.name) {
  98. console.log("无效设备:", device);
  99. return;
  100. }
  101. // 设备名称过滤
  102. const deviceName = device.name.toUpperCase();
  103. const isBleDevice =
  104. deviceName.endsWith("_BLE") ||
  105. deviceName.endsWith("-LE") ||
  106. deviceName.endsWith("-BLE");
  107. // 如果是BLE设备,直接返回
  108. if (isBleDevice) {
  109. console.log("发现BLE设备:", device);
  110. return;
  111. }
  112. // 设备去重
  113. const isDuplicate = state.discoveredDevices.find(
  114. (item) => item.address === device.address
  115. );
  116. if (isDuplicate) {
  117. console.log("重复设备:", device);
  118. return;
  119. }
  120. // 添加设备到列表
  121. console.log("发现新设备:", device);
  122. commit("addDiscoveredDevice", device);
  123. } catch (error) {
  124. console.error("处理设备发现回调出错:", error);
  125. }
  126. },
  127. // 搜索完成回调
  128. discoveryFinishedCallback: function () {
  129. console.log("蓝牙设备搜索完成");
  130. // 可以在这里添加搜索完成后的处理逻辑
  131. },
  132. // 读取数据回调
  133. readDataCallback: function (dataByteArr) {
  134. try {
  135. if (!dataByteArr || dataByteArr.length === 0) {
  136. console.log("无数据读取");
  137. return;
  138. }
  139. console.log("读取到数据:", dataByteArr);
  140. // 这里可以添加数据处理逻辑
  141. } catch (error) {
  142. console.error("处理数据读取回调出错:", error);
  143. }
  144. },
  145. // 连接异常回调
  146. connExceptionCallback: function (e) {
  147. console.error("蓝牙连接异常:", e);
  148. // 可以在这里添加连接异常的处理逻辑
  149. uni.showToast({
  150. icon: "none",
  151. title: "蓝牙连接异常,请重试",
  152. duration: 2000,
  153. });
  154. },
  155. });
  156. })
  157. .catch((error) => {
  158. console.error("蓝牙权限检查失败:", error);
  159. uni.showToast({
  160. icon: "none",
  161. title: "请授予蓝牙权限",
  162. duration: 2000,
  163. });
  164. });
  165. },
  166. // 搜索蓝牙设备
  167. async discovery({ commit }) {
  168. // 使用openBluetoothAdapter 接口,免去主动申请权限的麻烦
  169. uni.openBluetoothAdapter({
  170. success: async (res) => {
  171. try {
  172. await permission.androidPermissionCheck("bluetooth");
  173. commit("setDiscoveredDevices", []);
  174. bluetoothTool.discoveryNewDevice();
  175. console.log("openBluetoothAdapter=====", res);
  176. } catch (err) {
  177. bluetoothTool.shortToast(`授权失败:!${err}`);
  178. console.log("授权失败:", err);
  179. }
  180. },
  181. });
  182. },
  183. // 连接蓝牙
  184. connectBT({ commit }, device) {
  185. uni.showLoading({
  186. title: "连接中",
  187. });
  188. return new Promise((resolve) => {
  189. bluetoothTool.connDevice(device.address, (result) => {
  190. uni.hideLoading();
  191. if (result) {
  192. console.log(result);
  193. bluetoothTool.cancelDiscovery();
  194. commit("setConnectedBleDevice", device);
  195. commit("setConnectedDeviceId", device.address);
  196. uni.showToast({
  197. icon: "none",
  198. title: "连接成功",
  199. });
  200. resolve(device);
  201. } else {
  202. uni.showToast({
  203. icon: "none",
  204. title: "连接失败",
  205. });
  206. resolve(null);
  207. }
  208. });
  209. });
  210. },
  211. // 断开连接
  212. closeBluetooth({ commit, state }) {
  213. if (state.connectedDeviceId != "") {
  214. bluetoothTool.closeBtSocket();
  215. commit("setConnectedBleDevice", null);
  216. commit("setConnectedDeviceId", "");
  217. }
  218. },
  219. cancelDiscovery() {
  220. bluetoothTool.cancelDiscovery();
  221. },
  222. },
  223. };